Intro to objects, classes, methods & output

advertisement
Primitive types
– logical :
– textual:
– integral:
•
•
•
•
byte
short
int
long
boolean
char
8 bits -27 to 27 – 1
16 bits -215 to 215 – 1
32 bits -231 to 231 – 1
64 bits -263 to 263 – 1
– floating:
• float 32 bits
• double
64 bits
3/28/2003
Columbia University JETT
1
Everything else
• Everything that is not a primitive type is a reference type
• A reference variable contains a reference to an object
•
Circle sun = new Circle();
–
–
–
–
3/28/2003
allocates memory for this new object
initializes attributes
sun
executes constructor
assigns reference to reference variable
Columbia University JETT
2
Object-Oriented Programming
• Each object has
– its own memory
– belongs to a class (instance of a class)
• Class defines
– attributes (defines state)
– behavior (methods)
– Building blocks of Java programs
• Every program creates a class
3/28/2003
Columbia University JETT
3
Intro to Strings
•
•
•
•
String not built into Java
String is a class, part of java.lang package
Automatically imported
Declare:
– String greeting; // note caps
• Allocate space
– greeting = new String ("hello world!");
• or
– String greeting = new String ("hello world!");
• Strings are so common, we can do:
• String greeting = "hello world!";
Java Elements
4
String objects – method charAt
•
•
•
•
•
•
Zero based indexing
String s1 = "hello";
h e l l o
0 1 2 3 4
s1.charAt(0) => h
s1.charAt(3) => l
5
String objects – method substring
•
•
•
•
substring(starting index, ending index+1)
String s2 = “how are you?”;
s2. substring(0,3) => how
s2.substring(8,12) => you?
6
String objects - index
• Index – integer used to indicate location
• Zero based
•
•
•
•
Beware of index
0 <= index < length()
Out of bounds
any String method requiring an index will throw an
IndexOutOfBoundsException if 0 <= index <= length() is violated
• Exception – runtime error
• Exception is thrown when an error is encountered
7
Method
Description
Example: s = “hello”;
charAt(index)
Character at a specific index
s.charAt(1) returns ‘e’
endsWith(text)
Whether or not the string ends
with some text
s.endsWith(“llo”) => true
indexOf(text)
Index of a particular character or
String (-1 if not present)
s.indexOf(“o”) => 4
length()
Number of characters in the
string
s.Length() => 5
startsWith(text)
Whether or not the string starts
with some text
s.startsWith(“hi”) => false
substring(start,
stop);
Characters from start index to
just before stop index
s.substring(1,3) => “el”
toLowerCase()
A new string with all lowercase
letters
s.toLowerCase() => “hello”
toUpperCase()
A new string with all uppercase
letters
s.toUpperCase() => “HELLO”
Java Elements
8
String
• x = 45;
x
45
• String is not a primitive type, class
• String str;
• str = “Java Programming”;
str 2500
2500 Java Programming
reference variable
object
• str = new String (“Java Programming”);
• Reference variable
9
new
•
•
•
•
new is an operator
Causes the system to allocate space for object
Returns address
Instantiates a class object
10
Example of new
•
•
•
•
Scanner console = new Scanner(System.in);
String str = “Hello”; // = new String implied
int[] arr = new int[20];
Time time1 = new Time;
11
String str = "Hello";
• Reference variable
– Variables that store the address
– Any variable declared using a class is a reference
variable
– str is a reference variable of type String
– Memory space with Hello is an object or instance
of type String
12
Strings are immutable
str 2500
2500 Java Programming
Cannot change value at address 2500
Strings are immutable (once created they
cannot be changed)
New assignment creates new object
str = “Hello There!”;
str 3850
3850 Hello There!
str
Hello There!
13
Garbage collection
• “Java Programming” gets reclaimed later
• Happens automatically
– An object is eligible for garbage collection when
there are no more references to that object.
– References that are held in a variable are usually
dropped when the variable goes out of scope.
– Or, you can explicitly drop an object reference by
setting the variable to the special value null.
14
Summary
• Two types of variables in Java
– Primitive
• Store data directly into memory
– Reference
• Store address of object containing data
• An object is an instance of a class
• new is used to instantiate an object
15
Packages, Classes, Methods, import
•
•
•
•
import packageName.*;
java.lang- provides fundamental classes
String, Math
import java.util.*; // compiler determines
relevant classes
• import java.util.Scanner;
Java Elements
16
Console Input
• Scanner is a class
• Need to import java.util
import java.util.*; //allows use of Scanner class
Scanner console = new Scanner (System.in);
• Creates object console (can use any identifier name)
• Associates console with standard input device
• System.in – standard input device
Java Elements
17
Predefined classes and methods
•
•
•
•
Predefined classes
Contain predefined methods
Package contains classes
static method – belongs to class, can be used
by calling the name of the class
• Non-static method – belongs to object of class
18
Using predefined classes and methods
• class Math
• import java.lang.*; // package, automatically
// imported
• Math contains all static methods
• Math.pow(2, 3) // method call
•
// 2 arguments
. member access operator
19
Math methods
•
•
•
•
•
•
•
•
•
•
•
static double abs (double) Returns the absolute value of the argument
static float abs (float) Returns the absolute value of the argument
static int abs (int) Returns the absolute value of the argument
static long abs (long) Returns the absolute value of the argument
static double exp (double) Returns e raised to the power of the argument
static double log (double) Returns the natural logarithm of the argument
static double pow (double base, double exp) Returns the base raised to
the exp power
static double random () Returns a pseudorandom number in the range [0,
1)
static long round (double) Returns the nearest integer to the argument
static int round (float) Returns the nearest integer to the argument
static double sqrt (double) Returns the square root of the argument
20
Formatting output with printf
•
•
•
•
System.out.printf (formatString);
System.out.printf (“Hello There!”);
System.out.printf (formatString, argumentList);
System.out.printf (“There are %.2f inches in %d
centimeters.%n”, centimeters/2.54, centimeters);
• %.2f and %d – format specifiers
• Each format specifier in formatString must have one
corresponding argument in the argumentList
• When outputting the format string, the format
specifiers are replaced with the formatted values of the
corresponding arguments
21
%[argument_index$][flags][width][.precision]conversion
• Expressions in square brackets are optional
• argument_list - integer indicating the position of the
argument in the argument list
• flags – set of characters modifies the output format
• width – integer indicating minimum number of
characters to be written to the output
• precision – integer used to restrict the nymber of
characters
• conversion – character indicating how the argument
should be formatted
22
Supported conversions
Conversion
Result is
s
General
A string
c
Character
A Unicode character
d
Integral
Formatted as a decimal integer
e
Floating point
Formatted as a decimal number in computerized
scientific notation
f
Floating point
Formatted as a decimal number
%
Percent
%
n
Line separator
Platform-specific line separator
23
double x = 15.674;
double y = 235.73;
double z = 9525.9864;
System.out.printf("x = %.2f %n", x);
System.out.printf("y = %.2f %n", y);
System.out.printf("z = %.2f %n", z);
x = 15.67
// note rounding
y = 235.73
z = 9525.99
24
double x = 15.674;
double y = 235.73;
double z = 9525.9864;
System.out.printf("x = %.3f %n", x);
System.out.printf("y = %.3f %n", y);
System.out.printf("z = %.3f %n", z);
x = 15.674
y = 235.730
z = 9525.986
25
int num = 96;
rate = 15.50;
System.out.println("123456789012345");
System.out.printf("%5d %n", num);
System.out.printf("%5.2f %n", rate);
System.out.printf("%5d%6.2f %n", num, rate);
System.out.printf("%5d %6.2f %n", num, rate);
123456789012345
96
15.50
96 15.50
96 15.50
26
width represents minimum
System.out.printf("%1d %n", 8756);
8756
System.out.printf("%2d %n", 8756);
8756
System.out.printf("%3d %n", 8756);
8756
System.out.printf("%4d %n", 8756);
8756
System.out.printf("%5d %n", 8756);
8756
27
Exercises
1.
How does the variable of a primitive type differ from a reference variable?
2.
What is an object?
3.
Consider the following statements:
String str = “Going to the park.”;
char ch;
int len;
int position;
a.
What value is stored in ch by the following statement?
ch = str.charAt(0);
b. What value is stored in ch by the following statement?
ch = str.charAt(10);
c. What value is stored in len by the following statement?
len = str.length();
d. What value is stored in position by the following statement?
position = str.indexOf(‘t’);
e. What value is stored in position by the following statement?
position = str.indexOf(“park”);
28
4. Consider the following statements:
String str = “Going to the amusement park.”;
char ch;
int len;
int position;
What is the output of the following statements?
a. System.out.println (str.substring (0,5));
b. System.out.println (str.substring (13,22);
c. System.out.println (str.toUpperCase());
d. System.out.println (str.toLowerCase());
e. System.out.println (str.replace(‘t’,’*’));
29
5. Consider the following statements:
double x = 75.3987;
double y = 987.89764;
What is the output of the following statements?
a. System.out.printf(“%5.2f %n”, x);
b. System.out.printf(“%6.2f %n”, y);
c. System.out.printf(“%7.3f %n”, x);
d. System.out.printf(“%6.3f %n”, y);
30
Download