31 March 2003 This lecture covers the reading in Chapter 3: Data Types, Variables, and Arrays |
|
A data type is the characteristic of a variable that determines what kind of data it can hold. Java is a strongly typed language because it requires that every variable and expression have a type. The Java compiler checks for type compatibility among the variables to which you assign values. The Java compiler alerts you of any type mismatch, and you have to fix it before your program will compile.
The output is:
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
A given variable is either a primitive (basic type) or an object.
Each primitive data type has a range of values, which determines its size in memory
Sun's Java Tutorial contains a program that outputs the largest value of the
primitive types.
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/variables.html
Whole numbers without decimals (no floating point).
Type | Size | Range | Example |
Integer types | |||
byte | 8 bits | -128 to 127
-28 to (28-1) |
Colors (RGB) ASCII characters |
short | 16 bits | -32,768 to 32,767
-216 to (216-1) |
Unicode (world languages) |
int | 32 bits | -232 to (232-1) | counters in loops |
long | 64 bits | -264 to (264-1) | big numbers |
Can be float or double.
Floating point types | |||
float | 32 bits (6 digits) | 3.40282e+38 | floating point (currency, temperature, percentage, length) |
double | 64 bits (15 digits) | 1.79769e+308 | double (large numbers or high precision, such as for astronomy or
subatomic physics) The java compiler expects you will perform division by using double instead of float. |
Special types | |||
char | 16 bits (2 bytes) | unicode characters (whereas other languages use 1-byte ASCII text characters) http://www.unicode.org/unicode/standard/WhatIsUnicode.html |
alphabets and numerals |
Special types | |||
boolean | Java reserves 8 bits but only uses 1 | true false Note: These values are keywords. |
logic test with if |
Java stores each primitive type in a fixed amount of memory and Java directly
manipulates the values for primitives.
However, objects and arrays do not have a standard size, and they can become
quite large. Therefore, Java manipulates these reference types by reference.
Although the reference types do not have a standard size, the references to reference types do have a standard size.
Reference types differ from primitives in the way values are copied and compared.
A variable is a name for a piece of memory that stores a value. Each variable must have a name.
Unlike JavaScript and Visual Basic, Java is a strongly typed programming language.
Number are represented in memory using bits. A bit is the smallest unit that
a computer can work with. A bit has two possible values, 0 or 1.
Everything in a computer is represented by bits.
A number is represented by a series of bits which represent different powers of
2.
An 8 bits number (byte):
Value of the number | Bits |
0 | 00000000 |
1 | 00000001 = 2^0 |
4 | 00000100 = 2^2+0^1+0^0 |
8 | 00001000 = 2^3+0^2+0^1+0^0 |
13 = 8 + 4 + 1 | 00001101 = 2^3+2^2+0^1+2^0 |
255 = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 | 11111111 = ... |
A constant variable is a variable which is assigned a value once and cannot be changed afterward (during execution of the program). The compiler optimizes a constant for memory storage and performance.
Examples of constants
A literal is different from a variable.
Whereas a variable is name (or reference) for a
storage area for a value that can change, a literal is the direct representation
of a value.
Boolean | true false (no quotation marks because a Boolean is not a string) |
character | any character in the 16-bit Unicode character set a character literal is enclosed within single quotation marks |
string | a string object (strings are a special object type in Java) String greeting = "Hello!"; |
number | int yearsOnTheJob = 17; double inflationRate = .0306; |
double sum = 382.36; String firstName = "Luke"; // string literal inside quotation marks boolean isExpensive = false;
Here are character literals you might use:
// character literal inside single quote marks '\n' new line '\t' tab
We have already seen Declarations and assignments.
http://java.sun.com/docs/books/tutorial/java/javaOO/variables.html
The expression that initializes a variable (that assigns it a value for initial use) can be an expression with:
We say, "seeing is believing". Java can only compute with variables that it
can see.
Scope is the block of code in which a variable exists and is available for use.
The scope (or visibility) of a variable depends upon WHERE you declare it.
You might declare a variable within a block of code that is a:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/scope.html
Sun's tutorial exposes a common error involving the concept of scope:
if (...) { int myInteger = 17; ... } System.out.println("The value of myInteger = " + myInteger); // error
The final line won't compile because the local variable i
is out of
scope. The scope of i
is the block of code between the {
and }
.
The myInteger variable does not exist after the
closing curly brace (})
ends
that block of code.
QUESTION: Can you use have an instance variable with exactly the same name as a local variable?
QUESTION: Which line numbers define the scope of x? of y?
Let's discuss this example:
and its output:
Value of myInteger is: 1 Value of myInteger is: 2 3 is a multiple of 3 Value of myInteger is: 3 Value of myInteger is: 4 Value of myInteger is: 5 6 is a multiple of 3 Value of myInteger is: 6 Value of myInteger is: 7 Value of myInteger is: 8 9 is a multiple of 3 Value of myInteger is: 9
Let discuss this example with break:
and its output:
counting.. 1 2 3 4 5
Let's look ahead at break in more detail (in a switch statement) and then come back.
Automatic conversion occurs when your expression involves two data types that are compatible with each other, and the conversion is widening, that is, the destination type accommodates larger values the the source type.
For example,
double myInteger = 1; double myFloat = 1.0;
I do not need to use all the memory it takes to store a double (64 bits) if my value is just an integer (32 bits), but Java allows me to make an assignment that involves this explicit conversion.
Casting is the explicit translation of:
In a cast, the Java runtime knows enough about the types and how they are related to do this conversion.
byte, short, int, long, float, double | cast to/from | byte, short, int, long, float, double |
Explicit cast to smaller type - the syntax is (typename)value
Line 9 casts the product of two doubles as an integer.
The output is:
The product as double is 3.75 The product as integer is = 3
Another explicit cast is of integer into byte:
b = (byte) (50 * 2);
Booleans cannot be cast.
When you cast a floating point type to an integer type, or a double to a
float, there may be loss of precision.
For example, (int)3.2 truncates the .2 and returns
3.
Also, when you cast from a larger integer type to a smaller one, if the number is
very large, it might be truncated and return a smaller number.
The output is:
Conversion of int to byte. When int i = 257 is cast as a byte, the byte value is: 1 Conversion of double to int. Truncation when double 323.142 is cast as int 323 Conversion of double to byte. Casting double d 323.142 into byte causes wraparound after 255 67
You can cast an object to another class if the two classes are related by inheritance.
For example, all objects inherit from the superclass Object.
http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Object.html
Therefore, all objects have a GetClass() method.
http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Object.html#getClass()
I do not need to make an explicit cast for my string object to use this method.
The output is:
The class of myClass@111f71 is myClass The class of [Ljava.lang.String;@273d3c is [Ljava.lang.String;
You do not need an explicit cast when upcasting, but you do need an
explicit cast
when downcasting.
For example, this example casts an object as a string.
Object is higher in the class hierarchy than String, so casting an object as a
string is downcasting.
String s = "Heeeeeeeeere's Johnny"; Object o = s; // implicit upcast, no casting syntax needed because all strings inherit from the Object superclass String sz = (String)o; // explicit downcast, need casting syntax because String is a subclass of Object
You can use the instanceof operator to test an object's class before doing a downcast:
String s = "Heeeeeeeeere's Johnny"; Object o = s; String sz; if (o instanceof String) { sz = (String)o; }
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/other.html
Here, the instanceof operator determines whether its first operand is an instance
of its second operand.
Converting is the translation of one type into another, when you cannot do a
simple cast.
Unlike a cast, the runtime does not know enough about the types to do this
automatically.
Some code must be written to handle the conversion
Suppose that you have been storing zip codes as strings, but now you need to
treat those zip codes as integers.
You can use an method of the Integer class to pass in a string argument and get
integer output.
In effect, the following example converts a string object into a integer
primitive.
String myZipCode = "94568"; // myZipCode is a String object int myZip = Integer.parseInt(myZipCode); // myZip is a primitive
http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Integer.html
To convert an integer primitive into an object of its corresponding Integer class:
The output is:
The class to which 94568 is an instance is java.lang.Integer
http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Integer.html#Integer(int)
The most common type of conversion is to and from a String.
The java.lang.Object package defines the toString()
method with a simple default implementation.
Many classes override this implementation to provide a translation that
preserves the object's content.
For example, an XML document might use the toString()
method.
java.lang.Object defines an equals()
method, but the default implementation is simply a = = test.
Some objects override this (which is polymorphism applied to inheritence).
When you compare Strings, the = = operator tests for
identical objects.
More likely, you want to test for identical values
being stored in the String variables.
Every String object has an equals() method for this
test of equivalent values being stored in two string variables.
Whereas line 5 creates a second reference (or variable) to the original object, line 11 reassigns that variable to a new and different object.
The output is:
Contents of first string: some text. Contents of second string: some text. Two variables REFER to same object? Use = = and result is true s2 now refers to a new and different object even if it contains the same value as s1. Contents of first string: some text. Contents of second string: some text. Same object? Use = = and result is false Same value? Use equals and result is true
Java can promote data types when it evaluates an expression.
As the comments state, a byte can be promoted to a float, a char to an integer, a short to a double, an int to a float, and a float to a double.
An array stores multiple variables of
Examples of arrays
Line 4 declares the array named month_days to store a set of values of type int. Line 5 creates the array with 12 elements. Lines 6 through 17 populate the array with integer values.
To get the number of elements in an array, use the length() method of the array object;
The output is:
Internally, a String is an array of characters, an array of char. The Java API, however, considers a String to be an object. Therefore, you benefit from built-in methods and property to help you handle strings.
Here is some starter code for taking command-line input:
______________
course
homepage course
calendar