Java Review - PowerPoint PPT Presentation

1 / 88
About This Presentation
Title:

Java Review

Description:

Certain Java programs applets--can be embedded in Web pages ... System.out.println(d.toString()); // Jan1, 2006 will be printed ... – PowerPoint PPT presentation

Number of Views:33
Avg rating:3.0/5.0
Slides: 89
Provided by: phil202
Category:
Tags: jan1 | java | review

less

Transcript and Presenter's Notes

Title: Java Review


1
Java Review
2
The Java Environment and Classes
  • Platform independent
  • Object oriented
  • Certain Java programsapplets--can be embedded in
    Web pages
  • JVM is a software computer that runs inside an
    actual computer
  • Implementations of JVM for many platforms are
    available
  • Java code is first translated into Java byte code
    instructions which are then interpreted by the JVM

3
Compiling and Executing a Java Program
4
OOP
  • Object Oriented programming (OOP) is the idea of
    developing programs by defining objects that
    interact with each other
  • Java programs are organized around the notion of
    hierarchy of objects and classes

5
Objects
  • An object is an entity which
  • Stores data ---state
  • Can perform actions --- behavior
  • A Java program works by having objects perform
    actions

6
Objects
  • E.g.
  • Bank Account Object
  • State
  • Account number
  • Name
  • Address
  • Balance
  • Action/Behavior
  • Credit
  • Debit
  • Change address
  • Print statement

7
Class
  • Definition/type/model/blueprint of an object
  • Consider a blueprint created by an architect when
    designing a house
  • One blueprint
  • Several houses built using the same blueprint

8
Classes
  • The class is the fundamental programming unit
  • Every program is written as a collection of
    classes
  • Class definitions are stored in separate files
    with the extension .java and the file name must
    be the same as the class name
  • A class is a general description of a group of
    entities that all have the same characteristics
  • When an object is constructed of a class, and
    instance of the class is created.

9
Classes
  • E.g.
  • Bank account class
  • Instance variables
  • String accountNo
  • String name
  • String address
  • Double balance
  • Methods
  • Debit(double amount)
  • Credit(double amount)
  • changeAddress(String newAddress)

10
Encapsulation
  • Combining all the data and methods that are
    involved with a group of entities with the same
    characteristics in one place ---in a class.
  • An object should not allow its internal data to
    be directly manipulated by others
  • All communication with an object should be
    through method calls

11
The Java API
  • Java consists of small core language augmented by
    an extensive collection of packages
  • java.lang (String, Math, Integer, etc.)
  • java.util (random numbers, useful data
    structures like Vector)
  • Java.io input/output and formatting
  • AWT support for GUIs
  • Swing extension of AWT
  • AWT
  • Each package contains a collection of related
    Java classes

12
The import Statement
  • import statement tells the compiler to make the
    names defined in a specified package accessible
    to the code file
  • import java.util. //import all classes from
    java.util
  • import java.util.Vector // import Vector class

13
The main Method
  • The main function identifies where the JVM begins
    execution of an application program
  • Keywords public static void tell the compiler
    that main is accessible outside of the class, is
    static, and does not return a value
  • import javax.swing.
  • public class HelloWorld
  • public static void main(String args)
  • String name JOptionPane.showInputDialog(
    Enter Your Name)
  • JOptionPane.showMessageDialog(null,
    Hello name , welcome to Java!)

HelloWorld.java
14
Primitive Data Types and Reference Variables
  • In Java, a variable can hold either
  • Primitive type value
  • Or, reference to an object
  • Primitive type data is stored in primitive type
    variables
  • Objects are associated with reference
    variables/class type variables which store an
    objects address

15
Primitive Data Types
  • Represent numbers, characters, and Boolean values
  • Integers byte(1), short(2), int(4), and long(8
    bytes)
  • Real numbers float(4) and double(8 bytes)
  • Characters char (2 bytes)
  • Boolean (1 bytes)

16
Declarations
  • Primitive type variables
  • int count
  • double sum 0.0
  • char star
  • boolean isEmpty true
  • Primitive type constants
  • final int MAX_SCORE 999
  • final float G 3.82f

17
Operators
  • Arithmetic
  • -x
  • x y, x - y
  • x y, x / y, x y
  • Increment/Decrement/Assignment
  • x, x, x--, --x
  • x y is equivalent to x x y
  • Comparison
  • x y
  • x ! y
  • x lt y, x gt y, x lt y, x gt y
  • Logical
  • and x y
  • or x y
  • negation !x

18
Operators
19
Type Compatibility and Conversion
  • Widening conversion operations involving
    mixed-type operands, the numeric type of the
    smaller range is converted to the numeric type of
    the larger range
  • In an assignment operation, a numeric type of
    smaller range can be assigned to a numeric type
    of larger range
  • Automatic/Implicit Typecasting
  • int item 5000
  • double realItem item // okay
  • int x realItem // illegal
  • double float long int short byte

20
Referencing Objects
  • You can declare reference variables that
    reference objects of specified types
  • String greeting hello
  • Two reference variables can reference the same
    object
  • String welcome greeting

21
Creating Objects
  • The new operator creates an instance of a class
  • String name new String(Joe)
  • A constructor executes when new is called
  • Space for the new string is created and
    initialized with the given string
  • The address of the allocated string is stored in
    variable name.

22
Primitive versus reference variable
  • int x 50
  • String name new String (Joe)

x
52
name
Joe
23
null reference
  • String name null
  • String variable name does not contain any address
  • It is possible to reference nothing
  • Garbage Collector
  • You do not have to worry about deallocating
    memory
  • String s new String(hello)
  • s null
  • Java does automatic garbage collection unlike
    C/C

24
Assignment () and comparison () of reference
variables
  • String s hello
  • String t s // copies the address, but not the
    object itself
  • if (s t) //compares addresses, and returns
    true
  • String u hello
  • if ( s u) // compares addresses and returns
    false
  • Instead use,
  • if (s.equals(u)) //compares contents and returns
    true

25
Java Control Statements
  • The statements execute in the order in which they
    are listed
  • Control Statements alter the sequential flow of
    execution

26
Java Control Statements (continued)
27
Java Control Statements (continued)
28
Methods
  • Programmers use methods to define a group of
    statements that perform a particular operation
  • All method arguments are call-by-value
  • If the argument is a primitive type, its value is
    passed to the method
  • The method cant modify the argument value and
    have the modification remain after return from
    the method

29
Methods (continued)
  • If the argument is of a class type, the value of
    the reference variable is passed, not the value
    of the object itself
  • Reference variables point to the object and any
    modification to the object will remain after
    return from the method
  • We will see an example later

30
The String Class
  • String class defines a data type that is used to
    store a sequence of characters
  • Strings are objects
  • You cannot modify a String object
  • If you attempt to do so, Java will create a new
    object that contains the modified character
    sequence
  • String myName Elliot Koffman
  • myName Koffman, Elliot

31
Common string operations
  • String concatenation
  • String u Hello
  • String t World
  • String s u t // s refers to Hello World
  • int I s.length() //returns 11
  • u.equals(t) // comparison, returns false
  • u.compareTo(t) // returns negative number
  • s.charAt(1) // returns e, index runs from 0 to
    length-1
  • String x u.toUpperCase() //returns HELLO
  • Many more, check String class

32
Wrapper Classes for Primitive Types
  • Sometimes we need to process primitive-type data
    as objects
  • Java provides a set of classes called wrapper
    classes whose objects contain primitive-type
    values Float, Double, Integer, Boolean,
    Character, etc.

33
Wrapper classes (contd)
  • From int to Integer
  • int x 90
  • Integer intObject new Integer(x)
  • From Integer to int
  • int y intObject.intValue() // y contains 90

34
Parsing Numeric Strings to Numbers
  • String to int
  • int year Integer.parseInt(2004) // year
    contains 2004
  • String to double
  • double pi Double.parseDouble(3.1415926)

35
Arrays
  • In Java, an array is also an object
  • The elements are indexes and are referenced using
    a subscripted variable of the form
    arraynamesubscript
  • int scores new int5 //explicit
    instantiation by new
  • scores0 10
  • String names Sally, Jill, Hal,
    Rick //initialization implicitly allocates
    the array

36
I/O
  • Screen output
  • System.out.println(The year is year)
  • Console input
  • BufferedReader class, see ConsoleIO.java
  • All input read as String, need to be parsed if
    you need to read numbers
  • File I/O
  • See FileIO.java for an example

37
Escape Sequences
  • An escape sequence is a sequence of two
    characters beginning with the character \
  • Represents characters or symbols that have a
    special meaning in Java

38
StringTokenizer Class
  • We often need to process individual pieces, or
    tokens, in a string

39
Input/Output using Class JOptionPane
40
Parsing Numeric Strings to Numbers
  • A dialog window always returns a reference to a
    string
  • Therefore, remember a conversion is required

41
Defining your own classes
  • A class contains declarations of
  • Instance variables
  • Methods
  • public class Date
  • // instance variables
  • private String month
  • private int day
  • private int year
  • // constructor(s)
  • public Date()
  • month Jan
  • day 1
  • year 2006
  • .

instance variable
42
Date class continued
  • public int getDay() return day
  • public void setDay(int day) this.day day
  • public toString() return month day
    , year
  • // end of Date class
  • see Date.java for full class definition

43
Constructor
  • Special method
  • Same name as class
  • Invoked when object is created
  • Initializes the object
  • We can (and usually have ) multiple constructors
  • public Date(String month, int day, int year)
  • this.month month
  • this.year year
  • this.day day
  • this refers to the calling object
  • Creating a Date object with new generates a call
    to appropriate constructor
  • Date d new Date()
  • Date d2 new Date(Feb, 2, 2006)

local variable
instance variable
44
Copy Constructor
  • is a constructor with a single argument of the
    same type
  • Should create an exact copy of the parameter
  • Should create an independent copy
  • public Date(Date aDate)
  • month aDate.month
  • year aDate.year
  • day aDate.day
  • d2 will be created as an exact copy of d, but as
    a separate object
  • Date d new Date()
  • Date d2 new Date(d)

instance variable
45
Accessor methods
  • Used to get the data stored in an object
  • public int getDay() return day
  • Outsiders can access the data using accessors.
    Direct access should not be allowed.
  • Invocation
  • Date d new Date()
  • int aDay d.getDay() // aDay contains 1

46
Mutator methods
  • To update the data stored
  • public void setDay(int day)
  • this.day day
  • invocation
  • Date d new Date()
  • d.setDay(20)

47
access modifiers private versus public
  • private inside view, private members are not
    directly accessible by outsiders. These data
    fields can be accessed only within the class
    definition
  • Instance variables are declared private.
  • Date d new Date()
  • d.day 30 //invalid
  • public available for direct access to everyone.
  • d.setDay(30) //okay

48
toString
  • Expected in all classes
  • returns a String representation of the object
  • Date d new Date()
  • System.out.println(d.toString()) // Jan1, 2006
    will be printed
  • System.out.println(d) // Jan1, 2006 will be
    printed again
  • //implicit
    call to toString()

49
equals
  • Expected in all classes
  • Returns boolean if two objects are equal
  • Date d new Date()
  • Date d2 new Date()
  • if (d.equals(d2) ) //returns true

parameter object
Calling object
50
Method Overloading
  • Two or more methods can have the same name, but
    should have different signaturesdifferent number
    and/or type of parameters
  • public void setDate(int month, int day, int
    year)
  • // int, int, int
  • public void setDate(String month, int day, int
    year)
  • // String, int, int
  • Date d new Date()
  • d.setDate(2,2,2007) // will call the first
    setDate
  • Return type is not a part of the signature

51
Defining Your Own Classes
  • Unified Modeling Language is often used to
    represent a class
  • Standard means of documenting class relationships
    widely used in industry

52
static methods
  • static methods require no calling object
  • Call with class name
  • Math.max(a, b)

53
The Class Math
  • Provides a collection of methods that are useful
    for performing common mathematical operations

54
static variables
  • Variable that belongs to a class not to an object
  • Only one copy
  • Can be used to communicate between objects
    created from a class
  • See Employee.java
  • Constants are usually defines static as well
  • public class SomeClass
  • public static final double PI 3.14159
  • Later use refer to as
  • SomeClass.PI

55
Objects as arguments to methods
  • See ToyClass.java and ClassParameterDemo.java
  • A method cannot change the value of a variable of
    a primitive type that is an argument to the
    method
  • A method CAN change the values of instance
    variables of an argument of a class type

56
Classes with class type instance variables
  • See Employee.java and Company.java
  • Be careful with privacy leaks
  • Make a copy of the class type instance variable
    when returning from a method
  • Make a copy of a class type parameter when
    initializing/setting an instance variable and
    when copying in a copy constructor
  • Make a copy of class type instance variable in
    copy constructors

57
Introduction to Inheritance and Class Hierarchies
  • Popularity of OOP is that it enables programmers
    to reuse previously written code saved as classes
  • All Java classes are arranged in a hierarchy,
    starting with Object, which is the superclass of
    all Java classes
  • Inheritance and hierarchical organization allow
    you to capture the idea that one thing may be a
    refinement or extension of another
  • Inheritance is the process by which a new class
    called the subclass is created from another class
    called the superclass.

58
A Superclass and a Subclass
  • Consider two classes Computer and Laptop
  • A laptop is a kind of computer and is therefore a
    subclass of computer

59
Shape, Circle, Rectangle
  • Consider one superclass Shape
  • Two subclasses Circle, Rectangle
  • Store code and data that is common to all
    subclasses in the superclass, Shape
  • color
  • getColor()
  • setColor()
  • Circle and Rectangle inherit all the instance
    variables and the methods that Shape has.
  • Circle and Rectangle are allowed to define new
    instance variables and new methods that are
    specific to them.
  • Circle
  • center, radius
  • getArea(), getPerimeter()

60
Shape class
  • public class Shape
  • private String color
  • public Shape()
  • color red
  • public String getColor() return color
  • public String setColor( String newColor)
  • color newColor
  • public String toString()
  • return color

61
  • public class Circle extends Shape
  • public static final double PI 3.14159
  • private Point center
  • private double radius
  • public Circle()
  • super() // calls the constructor of the
    superclass
  • center new Point(0,0,0)
  • radius 1.0
  • public double getArea()
  • return PI radius radius
  • public double getPerimeter()
  • return 2 PI radius
  • public String toString()
  • return super.toString() center ,
    radius

62
Initializing Data Fields in a Subclass and the
No-Parameter Constructor
  • Private data fields belonging to a superclass
    must be initialized by invoking the superclasss
    constructor with the appropriate parameters
  • super()
  • It has to be the first statement in the
    constructor
  • If the execution of any constructor in a subclass
    does not invoke a superclass constructor, Java
    automatically invokes the no-parameter
    constructor for the superclass
  • Initializes that part of the object inherited
    from the superclass before the subclass starts to
    initialize its part of the object

63
Protected Visibility for Superclass Data Fields
  • Private data fields are not accessible to derived
    classes
  • Protected visibility allows data fields to be
    accessed either by the class defining it or any
    subclass. E.g. if we define color in Shape class
    as
  • protected String color
  • It is directly accessible from Circle and
    Rectangle and any other derived classes.
  • In general, it is better to use private
    visibility because subclasses may be written by
    different programmers and it is always good
    practice to restrict and control access to the
    superclass data fields

64
Method Overriding
  • If a subclass has a method found within its
    superclass, that method will override the
    superclasss method
  • toString() is overridden in Circle
  • The keyword super can be used to gain access to
    superclass methods overridden in the subclass.
  • super.toString()

65
Is-a Versus Has-a Relationships
  • Inheritance defines a is-a relationship
  • Laptop is-a Computer
  • Circle is-a Shape
  • Shape is-a Object
  • One misuse of inheritance is confusing the has-a
    relationship with the is-a relationship
  • The has-a relationship means that one class has
    the second class as an attribute
  • e.g. Circle class has-a Point instance variable,
    center. Point is another class.

66
Polymorphism
  • Suppose you are not sure whether a shape
    referenced in a program is a Circle or Rectangle.
  • How can this situation arise?
  • If you declare the variable as a Shape type you
    can use it to reference an object of either type.
  • A variable of a superclass type can reference an
    object of a subclass type
  • Shape s
  • s new Circle() //circle is a shape

67
Polymorphism
  • Polymorphism allows the JVM to determine which
    method to invoke at run time
  • System.out.println(s.toString())
  • will invoke the toString() method of the Circle
    class, since s references a Circle object.
  • At compile time, the Java compiler cannot
    determine what type of object a superclass may
    reference but it is known at run time
  • Late (Dynamic) Binding

68
Polymorphism
  • Lets a single reference variable refer to objects
    of many different types.
  • What type is shapeArrayi??
  • Shape shapeArray new Shape3
  • shapeArray0 new Circle()
  • shapeArray1 new Rectangle()
  • shapeArray2 new Oval()
  • for (int i 0 i lt shapeArray.length i)
  • System.out.println(shapeArrayi)

69
draw() method in Shape class???
  • Shape shapeArray new Shape3
  • shapeArray0 new Circle()
  • shapeArray1 new Rectangle()
  • shapeArray2 new Oval()
  • for (int i 0 i lt shapeArray.length i)
  • shapeArrayi.draw()
  • The Shape class does not represent a specific
    shape. How do we implement its draw method??
  • For the above code to compile, Shape class needs
    a draw() method

70
Abstract Classes
  • Let the compiler know that Shape is an abstract
    class declares but does not implement some
    methods.
  • An abstract class can have abstract methods, data
    fields, and concrete methods
  • Abstract method a method with no body. The
    subclass class will provide its actual
    implementation.
  • public abstract class Shape
  • public abstract void draw()
  • // derived classes will define their draw
    methods.

71
  • public class Circle extends Shape
  • public void draw()
  • //Circle drawing code goes here

72
Abstract Classes
  • An abstract class cannot be instantiated
  • new Shape() is not allowed.
  • An abstract class can have constructors to
    initialize its data fields when a new subclass is
    created.
  • May implement an interface but it doesnt have to
    define all of the methods declared in the
    interface
  • Implementation is left to its subclasses

73
Class Object
  • Object is the root of the class hierarchy every
    class has Object as a superclass
  • All classes inherit the methods defined in class
    Object but may be overridden

74
The Methods toString and equals
  • You should always override the toString method if
    you want to represent an objects state
  • If you do not override it, the toString method
    for class Object will return a stringjust not
    the string you want or are expecting
  • The Object.equals method has a parameter of type
    Object
  • Compares two objects to determine whether they
    are equal
  • You must override the equals method if you want
    to be able to compare two objects of a class

75
Exceptions
  • A program often encounters problems as it
    executes. It may have trouble reading data, there
    might be illegal characters in the data, or an
    array index might go out of bounds.
  • An exception is a problem that occurs when a
    program is running. Often the problem is caused
    by circumstances outside the control of the
    program, such as bad user input. When an
    exception occurs, the Java virtual machine
    creates an object of class Exception which holds
    information about the problem.
  • Exceptions are defined within a class hierarchy
    that has the class Throwable as its superclass
  • Classes Error and Exception are subclasses of
    Throwable
  • We focus on Exception class and its descendants

76
The Class Throwable
  • All exception classes inherit the methods of
    Throwable

77
The Class Throwable (continued)
78
Checked and Unchecked Exceptions
  • Two categories of exceptions checked and
    unchecked
  • Checked exception normally not due to programmer
    error and is beyond the control of the programmer
  • FileNotFoundException
  • Unchecked exception may result from programmer
    error
  • NullPointerException

79
Checked and Unchecked Exceptions (continued)
80
Catching and Handling Exceptions
  • When an exception is thrown, the normal sequence
    of execution is interrupted
  • Default behavior
  • Program stops
  • JVM displays an error message
  • The programmer may override the default behavior
    by
  • Enclosing statements in a try block
  • Processing the exception in a catch block

81
Uncaught Exceptions
  • When an exception occurs that is not caught, the
    program stops and the JVM displays an error
    message and a stack trace
  • The stack trace shows the sequence of method
    calls, starting at the method that threw the
    exception and ending at main

82
The try-catch-finally Sequence
  • Write a try-catch sequence to catch an exception
  • Handle it rather than relying on the JVM
  • try
  • statements that may throw an exception
  • statements that should not execute if an
    exception is thrown
  • catch (Exception e)
  • statements to handle the exception e
  • ltother catch blocksgt
  • finally
  • statements executed no matter what

83
  • import java.lang.
  • import java.io.
  • public class Square
  • public static void main ( String args )
    throws IOException
  • BufferedReader stdin new
    BufferedReader ( new InputStreamReader( System.in
    ) )
  • String inData
  • int num
  • System.out.println("Enter an integer")
  • inData stdin.readLine()
  • try
  • num Integer.parseInt( inData )
  • System.out.println("The square of "
    inData " is " numnum )
  • catch(NumberFormatException e)
  • System.out.println("You entered bad
    data." )
  • System.out.println("Run the program
    again." )

84
try-catch-finally
  • Catch block is skipped if all statements within
    the try block execute without error
  • Catch block within the first catch clause having
    an appropriate exception class executes, others
    are skipped

85
Throwing Exceptions
  • Instead of catching an exception in a lower-level
    method, it can be caught and handled by a
    higher-level method
  • Declare that the lower-level method may throw a
    checked exception by adding a throws clause to
    the method header

86
  • methodA(
  • try
  • methodB()
  • catch (IOException e)
  • System.out.println(e.getMessage())
  • methodB() throws IOException
  • // some File operation that may throw and
    IOException

87
Throwing Exceptions (continued)
  • Can use a throw statement in a lower-level method
    to indicate that an error condition has been
    detected
  • Once the throw statement executes, the
    lower-level method stops executing immediately.
    Exception is thrown out to the caller of the
    method.
  • methodB() throws MyException
  • throw new MyException()

88
Which exception to throw?
  • An already defined Java Exception
  • OR, write your own Exception class
  • public class MyException extends Exception
  • public MyException()
  • super(Default Message for MyException)
  • public MyException(String message)
  • super(message)
Write a Comment
User Comments (0)
About PowerShow.com