Transcript Java intro

Java intro
Part 2
1
Access control in Java classes
• Public members: accessible to any code that can
access the class
• Private members: accessible only within the class
(no friend functions!)
• Protected members: accessible by code in:
– Same package
– Subclass as inherited member
– Used more often than private because it allows
extensibility
2
Object creation
• A variable of a class type is simply a
reference to an object
• A declaration is just a declaration, NOT a
call to the object’s constructor
• To call the constructor, invoke operator new
– Allocates dynamic memory for objects
– All objects are dynamic objects
3
Constructors in Java
•
•
•
•
Method with same name as class
Performs initializations of object members
Has no return type
May be overloaded
– Can have multiple constructors
– But no such thing as default arguments
4
Assignment in Java
• For primitive data types, works in familiar
manner:
– variable represents memory location sized to
hold specific data type
– value is stored in memory location via
assignment operator
– example:
int x; // allocates 4 bytes of memory
x = 5; // stores value 0000 0000 0000 0101
5
Assignment in Java
• For objects, variables represent locations
that can hold references; Java’s oh-so-gentle
way of saying “pointers”
• An object reference is created when a
constructor is called using the new operator
• A variable of the object type stores the
reference
6
Objects & assignment
• Because variables hold references to
objects, and not actual objects, two
variables can refer to the same object, as in
the example below:
Greeter worldGreeter = new Greeter (“world”);
Greeter anotherGreeter = worldGreeter;
7
Example continued
// worldGreeter and anotherGreeter both store references to
// the same object
anotherGreeter.setName(“Cate”);
// changes the String variable as referenced by both worldGreeter
// and anotherGreeter; thus:
String s = worldGreeter.sayHello();
System.out.println(s);
// prints Hello Cate! instead of Hello world!
8
Copying an object
• If it is not your intention to have two
variables referencing the same object (it
rarely is), can create a copy of an object to
store in a second variable using the clone()
method
• Method is available for all library classes;
we will see later how to define it for our
own classes
9
clone() method
• Returns generic data type Object
• Use explicit casting to create reference to
desired type
• Example:
Date aDate = new Date();
// stores reference to current date & time
Date anotherDate = (Date)aDate.clone();
// creates new Object, casts as Date & assigns
10
Null references
• Because all object variables contain object
references, can assign value null to any
object variable
• This is useful because null is a value that
can be tested; should assign null to any
variable that doesn’t immediately have an
object reference assigned to it
11
Pointers & Java
• You may have heard that Java doesn’t use
pointers; this is only true in the sense that
Java doesn’t use pointers you have to deal
with directly
– all object variables contain references - they
are, in fact, pointers
– you can’t create invalid pointers
– Java uses automatic garbage collection - you
don’t have to worry about reclaiming memory
12
Parameter passing in Java
• We can describe two types of parameters in
a Java method:
– implicit parameter: calling object
– explicit parameter: argument passed to method;
explicitly defined in method’s parameter list
• When necessary, can refer to the implicit
parameter using the keyword this
13
Parameter passing in Java
• Primitive type arguments (int, double, char, etc.)
are passed by value
• Objects are passed by reference (since all object
variables hold references), but methods can’t
change parameter values - basically, it’s pass by
const reference
• Method can change the state of the calling object
(implicit parameter) but not the received object
(explicit parameter)
14
Basic Error Handling
• Error messages can be sent to System.err
(analogous to cerr) instead of System.out
example: System.err.println (“Invalid input”);
• Still prints to screen, in most cases - can be
useful in situations where errors go
somewhere else, like a printing terminal
15
Ending a program prematurely
• If a program must be aborted because of an
input error, can use System.exit(#) (where #
represents an integer)
• exit is analogous to C++ return statement
• System.exit(0) means everything was OK,
any other number represents error status
16
Exception Handling
• Exception: a run-time event that disrupts
program execution
• Examples:
– file that can’t be opened
– input data inappropriate to variable type
• Java forces programmer to deal with many
such situations ahead of time
17
Exception Handling
• Many standard methods, particularly those
that perform I/O, are declared to “throw
exceptions”
• Compiler won’t recognize client methods
that don’t handle such exceptions
18
Examples of Exceptions
• NullPointerException: attempting to call a method
on a null reference
• IllegalArgumentException: indicates that data
value passed to a method is outside the bounds of
its domain; can be used to enforce preconditions
• IOException: may occur when attempting to read
or write data; for example, attempt to read data of
wrong type into a variable
19
Unchecked exceptions
• An unchecked exception is one that the
compiler doesn’t force the programmer to
handle; a NullPointerException is this type
of exception
– an unchecked exception can cause your
program to halt with a runtime error
– generally, unchecked exceptions are caused by
conditions under the programmer’s control; in
other words, errors you could have prevented
20
Checked exceptions
• Checked exceptions are caused by external
conditions beyond the programmer’s
control; for example, I/O exceptions
• The compiler insists that the programmer
acknowledge such exceptions by providing
exception-handling code
21
Exception Handling
• Any method that might throw an exception
must be invoked in one of two ways:
– within a method that announces its propensity
to throw the same type of exception:
public static void main(String [] args) throws IOException
public void read (String filename) throws IOException,
ClassNotFoundException
– within a method containing a try/catch block described later
22
Exception handling
• The method just described lets the
exception pass through to a method higher
on the chain of method calls
• The second method traps the (potential)
exception object in your method and treats
the error appropriately
• Catching exceptions means surrounding the
error-prone code with a try block followed
by one or more catch clauses
23
General form of try/catch block
try
{
// code that might throw an exception
}
catch (ExceptionType e)
{
// code that handles specific exception - can have as many
// catch blocks as needed to catch all pertinent exceptions
}
finally
{
// optional clause: executes regardless of whether or not
// an exception was thrown in try block
}
24
Notes on exception handling
syntax
• The exception mechanism deals with an
object, which is an instance of class
Throwable (defined in java.lang.*) or one of
its subclasses
• So catch block looks like a method
declaration with a single parameter, the
Throwable object
25
Throwable objects
• Often contains useful information about
exceptions - examples:
– name of file that couldn’t be opened
– value of illegal array index
• Several methods are defined in Throwable
class, including .getMessage(), which
returns generic message associated with
type of exception caught
26
Strings in Java
• String is a built-in class (not a simple type)
• Sequence of Unicode characters
• String methods include:
– length: returns number of character in String
String name = “Cate Sheller”;
int letters = name.length();
– charAt():returns character at specific index value
char first = name.charAt(0);
27
Strings in Java
• A String variable can hold reference to any
String object – so can assign a different
reference to same variable:
name = “George W. Bush”;
– But String object itself is read-only; can’t
change first letter of George’s name to Q, for
example – it’s NOT an array of char
– String buffer class exists which does allow for
this kind of manipulation
28
Strings & Assignment
• Can assign reference to String to any String
variable (as previously noted)
• To copy String object use:
String name = “Donald Duck”;
String name2 = new String(name);
29
Strings & Logical Comparison
• Operator == works as it does with pointers
in C++: tests to see if 2 variables reference
same object
• Member method .equals can be used to test
contents of 2 strings:
if (name2.equals(name))
30
Strings & Logical Comparison
• Member method .compareTo is more
general comparison operator:
– Returns positive value if calling object is
greater than argument
– Returns 0 if caller equals argument
– Returns negative value if caller is less than
argument
– Example: if (name2.compareTo(name) > 0)
31
Substrings
• The substring method of the String class
returns the string described by two
arguments:
– first argument is position of the first character
in the substring
– second argument is position of the first
character NOT to include in the substring
– difference is the length of the substring
32
Substrings
• The java.util package includes the StringTokenizer
class, which can be used to extract substrings
separated by delimiters
• A StringTokenizer object is created using two
arguments: the string to be broken down, and the
delimiting character (space if not specified):
String colors = “Red&White&Blue”;
StringTokenizer breakup = new StringTokenizer(colors, “&”);
33
StringTokenizer
• Once a StringTokenizer is created, can be
used to access individual substrings in a
sequential fashion
• Example:
while (breakup.hasMoreTokens())
{
String theColor = breakup.nextToken();
…
}
34
String Concatenation &
Displaying Objects
• The + operator concatenates strings with
objects of other simple types
• For implicit type conversion, can
concatenate with an empty string
• Since print() and println() work on Strings,
the concatenation operation makes output of
other types possible
35
String Concatenation &
Displaying Objects
• For newly-defined data type, can create a
toString method which allows output using
print or println
• For example, the method on the following
slide could be used for a Fraction class, with
numerator and denominator represented by
integer variables n and d
36
toString example
public String toString()
{
return (“” + n + ‘/’ + d);
}
37
Converting from String to
numeric type
• To convert from a String to a primitive numeric
type, use the wrapper classes Integer and Double
and their parsing methods, parseInt() and
parseDouble()
• For example:
int n;
String number = “52402”;
n = Integer.parseInt(number);
• The parsing methods will throw the unchecked
NumberFormatException if the String argument
doesn’t contain a number
38
I/O in Java
• Java I/O stream library provides System.in,
System.out and System.err
• To do file I/O, need to declare
– FileInputStream object for input
– FileOutputStream object for output
• No “open” command - use new instead:
FileInputStream infile = new FileInputStream(“source.txt”);
• No need for “close” - another example of
automatic garbage collection
39
Character I/O
• Like C++, Java uses streamed I/O
• Standard input is represented by System.in
(analogous to cin)
• System.in.read( ) returns byte as an int:
closest analog is cin.get(c) - ASCII input, in
other words
40
System.out
• Represents stdout
• String data can be printed using
System.out.print and System.out.println
– can print most primitive types, as they can be
converted to String
– System.out.write prints byte (ASCII character)
data
41
Code example
import java.io.*
class Uppercase
{
public static void main (String [] args) throws IOException
{
int x;
System.out.println(“Enter text to be converted”);
System.out.println (“to uppercase. Hit Ctrl-Z to end”);
while ((x = System.in.read()) != -1)
{
x = Character.toUpperCase((char)x);
System.out.write(x);
}
}
}
42
Notes on example
• The two lines inside the loop:
x = Character.toUppercase((char)x);
System.out.write(x);
• Form the nucleus of the function:
– Character is a class name, and toUppercase is a method
defined in that class
– the toUppercase method works on char (Unicode) data,
so x, which is an int, is cast as char for function to work
on it
– the write method works on byte (ASCII) data
43
Console char input
• As previously noted, System.in.read() reads byte data,
not char
• To read characters from the console, use System.in to
create an InputStreamReader object:
InputStreamReader reader = new InputStreamReader(System.in);
• To read Strings, create a BufferedReader object from
the InputStreamReader, then invoke the readLine()
method:
BufferedReader kbd = new BufferedReader(reader);
String myString = kbd.readLine();
44
GUI input
• A simpler way to read input is via an input dialog
box; you can create one by invoking the
showInputDialog method of JOptionPane class,
which is found in the javax.swing package:
String input = JOptionPane.showInputDialog(“Enter a number:”);
if (input != null)
num = Integer.parseInt(input);
// reads a number by extracting it from returned String
45
GUI output
• Can also create dialog box for output using
showMessageDialog method:
JOptionPane.showMessageDialog (null, “Hey!”);
// first parameter indicates no parent window
// second parameter is message displayed
46
Java intro
Part 2
47