Java I Refresher - PowerPoint PPT Presentation

1 / 65
About This Presentation
Title:

Java I Refresher

Description:

Saturday, January 7th / Friday, January 13th. Room 819 CTI. Before we begin. Sign up sheet ... We will spend about 50% of the time working through problems. ... – PowerPoint PPT presentation

Number of Views:111
Avg rating:3.0/5.0
Slides: 66
Provided by: jgem
Category:
Tags: 13th | friday | java | refresher | the

less

Transcript and Presenter's Notes

Title: Java I Refresher


1
Java I Refresher
  • Jonathan F. Gemmell
  • Saturday, January 7th / Friday, January 13th
  • Room 819 CTI

2
Before we begin
  • Sign up sheet
  • Survey
  • Does everyones computer work?
  • These slide are new (let me know if you spot a
    typo)
  • This is meant to be a hands-on review. We will
    spend about 50 of the time working through
    problems. Make sure I have your email address,
    so I can send you the solutions to the problems.
  • Please feel free to raise your hand, shout out
    questions, or throw rotten fruit during the
    review.

3
Outline
  • Basic structure of an application
  • Demo HelloWorld
  • Primitive data types and operations
  • Demo MathProblems
  • Using predefined objects
  • Demo StringDemo, ScannerDemo
  • Branching structures (if, if-else, switch)
  • Demo ZipCode
  • Loops (for, while, do-while)
  • Demo Factor
  • Demo MultiplicationTable

4
Outline continued
  • Arrays
  • Demo CalculateAverage
  • More on the structure of an application
  • Demo CircleCalculations
  • Method Overloading
  • Demo PrintNames
  • Objects
  • Demo Rectangle
  • Demo Country and CalculatePopulations

5
Basic structure of an application
  • A Java application consists of a definition of a
    class.
  • The name of the class (ClassName) and the name of
    the file (ClassName.java) must be identical.
  • The class definition has a header (public class
    ClassName) followed by a body inside braces.
  • The body of the class may contain a method called
    main. The main method always has the modifiers
    public, static and void in front of it.

6
Demo HelloWorld
  • Write the following program on your computer
  • public class HelloWorld
  • public static void main (String args)
  • System.out.println("Hello World!")

7
Primitive data types and operations
  • There are eight java primitives
  • boolean true or false
  • byte signed 8-bit integer
  • char 16-bit Unicode 2.0 character
  • short signed 16-bit integer
  • int signed 32-bit integer
  • long signed 64-bit integer
  • float signed 32-bit floating-point
  • double signed 64-bit floating-point

8
Primitive data types and operations
  • Most often you will use.
  • booleans for true/false variables
  • true, false
  • chars for characters
  • a, b, c
  • ints for integers
  • 1, 2, 3 (not 1.00)
  • doubles for decimals
  • 1.0, 3.14, 9.9999999

9
Primitive data types and operations
  • Java is a strongly typed language. An explicit
    type must be assigned to every data value.
  • Ex
  • int x 5
  • int y
  • y 7
  • int z x y
  • System.out.println(z)
  • Output 12
  • Notice that
  • x, y and z are all declared as ints
  • You can only declare a variable once!!!
  • int x 5
  • int x 6 ? Cant re-declare x!!

10
Primitive data types and operations
  • Common operations on primitives
  • Addition, Multiplication, etc
  • double z x y,
  • double z x y
  • Modulus
  • int z x y
  • Numerical comparison and equality
  • boolean z ( x
  • boolean a (x y)
  • Recall that one equals sign ( ) is an
    assignment
  • Two equals signs ( ) is a comparison

11
Primitive data types and operations
  • Casting
  • Will this compile?
  • double x 3
  • double y 2
  • int z x / y
  • Notice that a double has 64 bits, while an int
    has only 32. Trying to assign the value of x/y
    to z is like trying to pour a gallon of water
    into a 2-liter bottle. Try this instead.
  • double x 3
  • double y 2
  • int z (double)(x / y)
  • This is called casting. But be careful! You
    could lose precision. In the above example z
    will equal 1, not 1.5

12
Primitive data types and operations
  • What is the value of z? Why?
  • int x 3
  • int y 2
  • int z x / y
  • In integer math the decimal gets thrown out. z
    equals 1, not 1.5

13
Primitive data types and operations
  • Modulus is a useful operation. It results in the
    remainder of the division operation.
  • 10 3 1
  • 6 2 0
  • 5 3 2
  • 14 5 4
  • What is the value of z?
  • int z 8 3

14
Demo MathProblems (5 minutes)
  • Write an application called MathProblems.
    Declare variables where appropriate. Try some of
    the examples in the previous slides. Be sure to
    try at least one example of primitive operations,
    casting, integer math, and modulus.

15
Using predefined objects
  • One of the strengths of Java is the ability to
    create objects in your program from a large
    variety of pre-defined classes.
  • REMEMBER THIS WEBSITE!!!!!
  • http//java.sun.com/j2se/1.5.0/docs/api/index.html
  • Notice that primitive data types create a
    variable, whereas a class produces an object.
  • Each pre-defined class has a collection of public
    methods defined for it.

16
Using predefined objects
  • The String class
  • One of the first classes you used in Java 211 was
    the String class. A String represents a sequence
    of characters.
  • To create a String object
  • String s new String(A string of characters)
  • There is also a short-hand way to create a
    String
  • String s Another string of characters

17
Using predefined objects
  • Methods of the String class
  • int length() returns the number of characters in
    a String
  • String s "this is a String"
  • int i s.length()
  • char charAt(int index) returns the character at
    the index specified
  • String s "this is a String"
  • char c s.charAt(3)
  • int indexOf(char target) returns the index of
    the first occurrence of the target. -1 otherwise.
  • String s "this is a String"
  • int i s.indexOf('S')

18
Using predefined objects
  • String substring(int start, int end) returns a
    String that represents the characters from
    positions start to end
  • String s "this is a String"
  • String t s.substring(5,10)
  • Many more!
  • Concatenation
  • You can concatenate two Strings together with the
    operator. You can also concatenate a String
    and a primitive.
  • String s "this is a String."
  • String t "this is also a String"
  • String u s t

19
StringDemo
  • Write an application that declares some Strings.
    Use the methods described in the previous slide.
    Concatenate two Strings together. Try
    concatenating a String and a primitive.

20
Using predefined objects
  • The Scanner class
  • The Scanner class allows a program to read input
    taken from standard input. It can be found in
    the java.util package so you must put import
    java.util. in the program in order to use it.
  • Declare and initialize a Scanner object
  • Scanner s new Scanner(System.in)
  • Use the Scanner object to obtain an integer
    value
  • int x s.nextInt()
  • Use the Scanner object to obtain a decimal value
  • double y s.nextDouble()

21
Using predefined objects
  • The Scanner class cont.
  • In order to use the Scanner class to input a
    String
  • 1. Declare and initialize the Scanner object
  • 2. Change the delimiter from whitespace to the
    line separator
  • 3. Use the Scanner object to input a String
  • Scanner s new Scanner(System.in)
  • s.useDelimiter( System.getProperty("line.separator
    ") )
  • String str s.next()

22
ScannerDemo
  • Write an application that declares and
    initializes a Scanner object. Use it to input
    integer values, decimal values, and Strings.
    Print the input values to the screen.

23
Branching structures
  • This is the most basic if-statement
  • if (boolean expression)
  • //do this block of
  • If the boolean expression is true, the program
    will execute the next block of code.

24
Branching structures
  • Compound ifelse statements
  • if (boolean expression)
  • //do this
  • else if (boolean expression)
  • //do something else
  • else
  • //do yet something else

25
Branching structures
  • A switch statement evaluates the given integer
    and execute the appropriate block of code.
  • switch (x)
  • case 1 //this block of code will be executed
    if x equals 1
  • System.out.println("first case")
  • break
  • case 2 //this block of code will be executed
    if x equals 2
  • System.out.println("second case")
  • break
  • default //this block of code will be executed
    as a default
  • System.out.println("third case")
  • break

26
Demo ZipCode
  • Write an application that takes a three digit
    area code from a user and then tells a user where
    s/he lives.
  • 312 Chicago
  • 212 New York
  • 510 San Francisco
  • 972 Dallas
  • Write one version that uses a switch statement
    and a second version that uses a compound if-else
    statement.

27
Loops
  • The purpose of a loops is to repeat a block of
    code many times.
  • for loop
  • while loop
  • do- while loop

28
Loops
  • for loop
  • Use a for loop when you know exactly how many
    times you want to repeat the loop. You may know
    the particular value, or know a variable that
    contains the value.
  • The for loop has three crucial parts
  • The initialization of the counter
  • The boolean statement that tests the continuation
    condition
  • Incrementing the counter
  • For loops are useful when working with arrays (as
    we will see)
  • EX print hello 5 times.
  • for(int i0 i
  • System.out.println("hello")

29
Loops
  • while loop
  • Use a while loop when you want to repeat a block
    of code an unknown number of times (maybe not at
    all)
  • A while loop will repeat the block of code until
    the boolean statement is no longer true
  • while (boolean expression)
  • //do this block of code

30
Loops
  • do-while
  • Use a do-while loop when you want to repeat a
    block of code an unknown number of times, but at
    least once.
  • Perfect for user inputs.
  • EX ask a user for a number between 1 and 10,
    repeat until the user enters a valid number.
  • Scanner s new Scanner(System.in)
  • int input
  • do
  • System.out.print("Enter a number between 1 and
    10 ")
  • input s.nextInt()
  • while(input 10)

31
Demo Factor
  • Write an application that prompts the user for a
    positive integer and prints to the screen the
    factors of the input. The program should not
    accept negative numbers as an input, and should
    continue to ask for a value until the user enters
    a proper input.
  • For example, if the user enters 7, the output
    should be 1 and 7. If the user enters 12, the
    output should be 1, 2, 3, 4, 6, and 12.

32
Demo MultiplicationTable
  • It is crucial for you to understand and be able
    to implement nested loops. A nested loop is a
    loop inside another. Using nested loops, write
    an application that prints to the screen a five
    by five multiplication table.

33
Arrays
  • In Java, arrays are objects
  • You can create an array of any primitive or
    object class by using
  • The declaration of an integer array
  • int x
  • The declaration of a String array
  • String s
  • Declaring an array does not create the object or
    allocate memory. It merely creates the variable.

34
Arrays
  • Initializing arrays
  • Use the key word new to initialize an array and
    provide the type of the array, and the size of
    the array within the brackets.
  • int x new int100
  • Creates an int array x, 100 elements long
  • String s new String10
  • Creates a String array s, 10 elements long

35
Arrays
  • Modifying elements
  • int x new int10
  • x0 5
  • x2 8
  • In the above example, a new array is declared and
    initialized. The 0th element is set to 5, while
    the 2nd element is set to 8. Recall that a 10
    element array is numbered 0 through 9.
  • Accessing elements
  • int i x2
  • In the above example, the program will access the
    2nd element of the array and assign its value to
    the integer variable i.
  • Array Length
  • In Java, an array knows how long it is.
  • int x new int20
  • int l x.length

36
Demo CalculateAverage
  • Write an application that creates an int array of
    size 20, fills it with random numbers in the
    range 0 through 99, prints the array to the
    screen, and then calculates and prints the
    average of the numbers. (hint use for loops)
  • To generate a random number in the range 0
    through 99
  • int x (int)(Math.random() 100)

37
More on the structure of an application
  • So far the example programs have had only one
    method (the main method) and none of the examples
    have had any class variables. In practice, most
    programs will have many class variables and many
    methods.

38
More on the structure of an application
  • Class variables
  • A class variable is declared at the class level,
    rather than inside the body of a method.
    Consequently, the scope of variable extends
    throughout the entire class.
  • public class Test
  • static int i
  • public static void main (String args)
  • i 5
  • Notice that even while the variable i is declared
    outside the main method, it can still be accessed
    inside the main method.
  • Also notice the variable i has the modifier
    static. More on this later.

39
More on the structure of an application
  • Scope
  • public class Scope
  • int x 5
  • public static void main (String args)
  • int y 6
  • if (y 6)
  • int z 7
  • What is the scope of the variables x, y and z?
    Notice how proper indentation makes determining
    the scope easier.

40
More on the structure of an application
  • Methods A method has two parts
  • Header Describes the method in general terms,
    including its name, visibility, inputs and
    outputs.
  • Visibility modifier
  • Return type
  • Method Name
  • List of parameters
  • Body Describes the specific actions the method
    will perform
  • The body consists of a sequence of program
    statements to be executed. If the method returns
    a value, there must be a return statement.

41
More on the structure of an application
  • Visibility modifiers
  • public
  • Visible outside the class
  • Called a service method
  • private
  • Not visible outside the class
  • It can only be used by methods inside the class
  • Called a support method

42
More on the structure of an application
  • Return type
  • Can be any primitive, a class, or void.
  • It tells us what kind of result comes back from
    the method when it is evaluated.
  • If a method is supposed to return a value, there
    must be a return statement.

43
More on the structure of an application
  • Method Name
  • Gives the method a name, so that it can be called
    from elsewhere in the program.
  • The convention is to use lower case letters
    except for the first letter of subsequent words.
    No white spaces.
  • EX calculateSum
  • EX getLastName
  • EX SetPhoneNumber ? not convention

44
More on the structure of an application
  • List of parameters
  • A list of the type and name of the expected
    inputs
  • Type gives what kind of data is expected for that
    input
  • Name gives the name by which it will be referred
    to during the methods execution
  • Parameters are given in parentheses, separated by
    commas.
  • There does not need to be any parameters at all
    if the method does not require them.

45
More on the structure of an application
  • An example of a method
  • public static int squareNumber(int n)
  • int result n n
  • return result
  • Visibility modifier - public
  • Return type - int
  • Method Name - squareNumber
  • List of parameters an int named n

46
More on the structure of an application
  • Another Example
  • private static void printSum(double x, double y)
  • double result x y
  • System.out.println(result)
  • Visibility modifier - private
  • Return type - void
  • Method Name - printSum
  • List of parameters a double named x and a
    double named y

47
Demo CircleCalculations
  • Write a program with a class variable named pi
    equal to 3.14.
  • Write a method (dont put it in main!) that asks
    the user to enter a radius (double) and returns
    this value.
  • Write a method that accepts a radius (double) as
    a parameter and calculates the area of the circle
    with that radius. It should return the area. (
    a pi r2 )
  • Write a method that accepts a radius (double) as
    input and prints to the screen the circumference
    of a circle given the radius. The return type
    should be void. ( c 2 r pi )
  • In the main method call these three methods
    appropriately.

48
Method Overloading
  • Methods expect the proper input. The compiler
    will object if the wrong type or number of
    variables are supplied as arguments.
  • An overloaded method has several different
    definitions, all with the same method name, but
    different types and/or number of inputs.

49
Method Overloading
  • Signature
  • The ordered list of types of parameters in the
    header of a method is called a signature.
  • As long as they have different signatures, we can
    define as many methods as we want with the same
    name. The compiler will choose the correct
    method based on the methods signature.

50
Demo PrintNames
  • Write a method called printName that accepts a
    String called lastName as a parameter. It should
    print to the screen the name provided.
  • EX if the input is Smith, it should print out
    Mr. Smith.
  • Write a method with the same method name. This
    method should take two Strings as parameters,
    firstName and lastName.
  • EX if the inputs are John and Smith, it
    should print out John Smith
  • Write a third method with the same method name.
    This method should take two Strings as arguments
    and one char.
  • EX if the inputs are John, A, and Smith,
    the method should print out John A. Smith.
  • Write a main method to test the overloaded
    methods.

51
Objects
  • You have already used built-in classes
  • String and Scanner for example
  • You must now learn to write your own.
  • A class should contain two distinct pieces of
    information
  • Properties The state of the object
  • Given by the data members or instance variables
  • Behaviors The capabilities of the object
  • Given by the methods or instance methods

52
Objects
  • Anatomy of a class
  • public class ClassName
  • //instance variables
  • //constructor(s)
  • //methods(s)

53
Objects
  • Instance Variables
  • Typically, instance variables are not directly
    accessible. All your instance variables should
    be declared private.
  • public any program can see (and perhaps
    modify!) this data
  • private only visible to methods of the class
  • EX
  • public class Rectangle
  • private int width
  • private int height
  • .
  • Any object you create from the Rectangle class
    will have its own width and height.

54
Objects
  • Constructor
  • Constructors are a special type of method. They
    are often used to initialize the data members of
    a class when you create objects. They are
    automatically called upon declaration of an
    object.
  • They should be declared public
  • They should have exactly the same name of the
    class
  • Like any other method, they may or may not have
    parameters

55
Objects
  • Constructor cont
  • public Rectangle(int w, int h)
  • width w
  • height h
  • In this example the constructor takes two
    parameters, both ints, and assigns their values
    to the instance variables of the class.

56
Objects
  • Constructor cont..
  • To call the constructor and create an object of
    the Rectangle class
  • Rectangle r new Rectangle(2,3)
  • Assuming our Rectangle class is complete, this
    will create Rectangle object with a width of 2
    and a height of 3.

57
Objects
  • Instance methods represent the operations that
    can be performed by objects in the class
  • The methods can also be public or private
  • When deciding which to use, consider whether or
    not you want the operation available outside the
    class.
  • Consider the methods on the following slides
  • Notice the getter and setter methods
  • Notice that the calculateArea method will be
    called on a specific Rectangle object and will
    return the area of a that specific Rectangle
    object.

58
Objects
  • public void setWidth(int w)
  • width w
  • public void setHeight(int h)
  • height h
  • public int getWidth()
  • return width

59
Objects
  • public int getHeight()
  • return height
  • public int calculateArea()
  • int area width height
  • return area

60
Objects
  • Static
  • Notice that neither of the methods or instance
    variables in the Rectangle class are static.
  • Static variables or methods belong to the class
    as a whole rather than to a particular object of
    the class.
  • You do not need to declare an object from a class
    in order to use static methods
  • Conversely, you must declare an object from a
    class in order to use non-static methods
  • Non-static variables belong to a specific
    instance of the class, not the class as a whole.

61
Demo Rectangle
  • Implement the Rectangle class as described in the
    notes.
  • Create a second program called RectangleDriver
    that creates many Rectangle objects and
    thoroughly tests all the methods.
  • Add to the rectangle class a static int that
    keeps count of how many Rectangle objects have
    been created.

62
Country and CalculatePopulations
  • We have gone over many small examples together.
    Now I would like you to go over a larger example
    on your own.
  • I will be happy to speak with you individually if
    you require help.
  • Dont forget that tutors are available at CTI
    seven days a week and are happy to help you with
    your studies.

63
Country and CalculatePopulations
  • Write a Class called Country
  • It should contain the following instance
    variables
  • A String for the name of the country
  • An int for the population of the country (in
    millions)
  • A double for the growth rate of the country
  • It should contain the follows methods
  • A constructor to initialize all the member
    variables
  • Appropriate getter and setter methods.
  • A method called calculatePopulationForYear that
    takes as a parameter a year (int) and using the
    population and growth rate of the country
    calculates the population for that year. Ill
    give you this formula.

64
Country and CalculatePopulations
  • Write a class called CalculatePopulations
  • It should create an array of 5 countries and
    instantiate the Country objects using the
    constructor of the Country class.
  • See http//www.cia.gov/cia/publications/factbook/
    for a list of countries and the populations, etc.
  • It should print to the screen the five countries
    (hint use a for loop) and label them 0 through
    4.
  • It should then ask the user to input an int, 0
    through 4, and repeat until the user enters an
    appropriate number.

65
Country and CalculatePopulations
  • CalculatePopulations cont..
  • It should then ask the user to input a year
    greater than 2000. Repeat if necessary.
  • Finally, it should print to the screen the
    population of the selected country in the
    selected year.
Write a Comment
User Comments (0)
About PowerShow.com