Top Banner

of 170

Computer Science 1301

Apr 04, 2018

Download

Documents

BSASciti
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 7/30/2019 Computer Science 1301

    1/170

    11

    Chapter 2

    JAVA FUNDAMENTALS

  • 7/30/2019 Computer Science 1301

    2/170

    22

    // A simple Java program that displays the message// Have a good semester! on a line on the computer screen// displayMessage.java Created using: jGrasp

    // By L. Thompson

    public class displayMessage{

    public static void main(String[ ] args){

    System.out.println("Have a good semester!");}

    }

  • 7/30/2019 Computer Science 1301

    3/170

    33

    // A simple Java program that displays the message// Have a good semester! on a line on the computer screen// displayMessage.java Created using: jGrasp

    // By L. Thompson

    public class displayMessage{

    public static void main(String[ ] args){

    System.out.println("Have a good semester!");}

    }

    These are

    comments. They

    are ignored by the

    compiler.

  • 7/30/2019 Computer Science 1301

    4/170

    44

    THE PARTS OF A JAVA PROGRAM

    Comments

    Comments are notes of explanation used to documentprograms, sections of programs, or program statements for the

    humans who must read programs.

    The program displayMessage.java begins with the followingcomments:

    // A simple Java program that displays the message// Have a good semester! on a line on the computer screen// displayMessage.java Created using: jGrasp// By L. Thompson

    Every program should start with a similar comment. Describe

    what the program does and supply the name of the file

    containing the program and the name of the author of the

    program.

  • 7/30/2019 Computer Science 1301

    5/170

    55

    THE PARTS OF A JAVA PROGRAM

    Comments

    The compiler, the program that translates Java programs to bytecode, ignores everything from the two forward slashes to theend of the line.

    Comments do not end with a semicolon.

  • 7/30/2019 Computer Science 1301

    6/170

    66

    // A simple Java program that displays the message// Have a good semester! on a line on the computer screen// displayMessage.java Created using: jGrasp

    // By L. Thompson

    public class displayMessage{

    public static void main(String[ ] args){

    System.out.println("Have a good semester!");}

    }

    The compiler ignores blanklines. It is a good idea to use

    blank lines to make your

    program easier to read.

  • 7/30/2019 Computer Science 1301

    7/170

    77

    // A simple Java program that displays the message// Have a good semester! on a line on the computer screen// displayMessage.java Created using: jGrasp

    // By L. Thompson

    public class displayMessage{

    public static void main(String[ ] args){

    System.out.println("Have a good semester!");}

    }

    This is a

    class

    definition.

    This is the class header for the

    class named displayMessage.

  • 7/30/2019 Computer Science 1301

    8/170

    88

    THE PARTS OF A JAVA PROGRAM

    Class Definition

    Every Java program must have at least one class definition.

    We will use a class as a container that has the statements thatcomprise our application. The class named displayMessage

    contains the statements that make up our application in thesample program.

    public class displayMessage{

    public static void main(String[ ] args){

    System.out.println("Have a good semester!");}

    }

  • 7/30/2019 Computer Science 1301

    9/170

    99

    THE PARTS OF A JAVA PROGRAM

    Class Definition

    public class displayMessage{

    public static void main(String[ ] args){

    System.out.println("Have a good semester!");}

    }

    The wordpublic is an access specifier that controls where the class canbe accessed from. The keywordpublic in the class header specifiesthat the class is unrestricted (i.e. the class can be accessed from anyother class).

    The keyword class marks the beginning of the class. The class name, displayMessage, was chosen by the programmer. It is

    a user-defined identifier.

    The class header does not end with a semicolon. It is only thebeginning of a class definition; it is not a complete statement.

  • 7/30/2019 Computer Science 1301

    10/170

    1010

    THE PARTS OF A JAVA PROGRAM

    Class Definition

    public class displayMessage{

    public static void main(String[ ] args){

    System.out.println("Have a good semester!");}

    }

    There cannot be more than one public class in a file.

    When a Java file contains a public class, the name of the public

    class and the filename (without the .java extension) must be

    the same. Therefore, the source file containing the class shownabove must be named:

    displayMessage.java

  • 7/30/2019 Computer Science 1301

    11/170

    1111

    THE PARTS OF A JAVA PROGRAM

    Class Definition

    public class displayMessage{

    public static void main(String[ ] args){

    System.out.println("Have a good semester!");}

    }

    The { is an opening brace.

    The } is the closing brace.

    All the statements in the class definition are enclosed in a set of

    braces {}. We say that the braces delimit the body of the class. It is considered good programming style to indent the

    statements inside a set of braces one level.

  • 7/30/2019 Computer Science 1301

    12/170

    1212

    // A simple Java program that displays the message// Have a good semester! on a line on the computer screen// displayMessage.java Created using: jGrasp

    // By L. Thompson

    public class displayMessage{

    public static void main(String[ ] args){

    System.out.println("Have a good semester!");}

    }

    This is a

    method

    definition.

    This is the method header for the

    method named main.

  • 7/30/2019 Computer Science 1301

    13/170

    1313

    THE PARTS OF A JAVA PROGRAM

    Method Definition

    The method definition shown below is from displayMessage.java:

    public static void main(String[ ] args){

    System.out.println("Have a good semester!");

    }

    A method is a named block of statements that perform aspecific task when executed.

    Every Java application has a method called main. Java

    programs begin executing at the main method. The method header is not a complete statement, so it does

    not end with a semicolon.

    All the statements in a method definition are enclosed in a setof braces {}.

    There is no semicolon

    here.

  • 7/30/2019 Computer Science 1301

    14/170

    1414

    // A simple Java program that displays the message// Have a good semester! on a line on the computer screen// displayMessage.java Created using: jGrasp

    // By L. Thompson

    public class displayMessage{

    public static void main(String[ ] args){

    System.out.println("Have a good semester!");}

    }

    This statement tells the

    computer to display the

    message Have a good

    semester! on the computer

    screen.

  • 7/30/2019 Computer Science 1301

    15/170

    1515

    THE PARTS OF A JAVA PROGRAM

    Theprintln Method

    In displayMessage.java we used the following statement:

    System.out.println("Have a good semester!");

    A sequence of characters between the pair of quotation marksis called a string literal.

    The quotation marks delimit the string literal, they will not bedisplayed on the screen.

    Theprintln statement ends with a semicolon. It is a complete

    Java statement that instructs the computer to display a messageon the computer screen.

  • 7/30/2019 Computer Science 1301

    16/170

    1616

    THEprint METHOD,println METHOD, and the

    JAVA API

    Many of the programs we write will display text in a consolewindow.

    The console window is the standard output device.

    We will send strings of text to a console window using objectsfrom the Java API (Application Programmer Interface).

    The Java API is a standard library of prewritten classesavailable to Java programs for performing common operations.

  • 7/30/2019 Computer Science 1301

    17/170

    1717

    THEprint METHOD,println METHOD, and the

    JAVA API

    The program named displayMessage.java contains the statement:

    System.out.println("Have a good semester!");

    This statement uses the System class from the Java API. The System class contains objects and methods that perform

    system level tasks.

    The outobject is a member of the System class that contains themethods namedprintandprintln. These methods perform the

    task of writing characters in a console window on the computerscreen.

  • 7/30/2019 Computer Science 1301

    18/170

    1818

    THEprint METHOD,println METHOD, and the

    JAVA API

    System.out.println("Have a good semester!");

    The line above is read System dot outdotprintln

    The dot is the membership operator in Java. It is used tospecify thatprintln is a member method of the outobject whichis a member of the System class.

    *** See Figure 2-3 from the text

    Membership operators

  • 7/30/2019 Computer Science 1301

    19/170

    1919

    THEprint METHOD,println METHOD, and the

    JAVA API

    System.out.println("Have a good semester!");

    The value that is to be displayed on the computer screen isplaced inside parentheses.

    A value passed to a method is called an argument.

    The argument passed to theprintln method in this example is thestring literal "Have a good semester!".

  • 7/30/2019 Computer Science 1301

    20/170

    2020

    THEprint METHOD,println METHOD, and the

    JAVA API

    Theprintln method displays a stream of characters and thenadvances the cursor to the beginning of the next line.

    Theprintmethod displays a stream of characters, but does not

    advance the cursor to the next line.

  • 7/30/2019 Computer Science 1301

    21/170

    2121

    THEprint METHOD,println METHOD, and the

    JAVA API

    // A portion of the Gettysburg Address by Abraham Lincoln// gettysburgA.java Created using: jGRASP// By L. Thompson

    public class gettysburgA{

    public static void main(String[ ] args){

    // This version uses the println method

    System.out.println("Four score and seven years ago");System.out.println("Our fathers brought forth on this continent,");System.out.println("a new nation, conceived in liberty,");System.out.println("and dedicated to the proposition that all men are created equal.");

    }}

  • 7/30/2019 Computer Science 1301

    22/170

    2222

    THEprint METHOD,println METHOD, and the

    JAVA API

    // A portion of the Gettysburg Address by Abraham Lincoln// gettysburgB.java Created using: jGRASP// By L. Thompson

    public class gettysburgB{

    public static void main(String[ ] args){

    // This version uses the print method

    System.out.print("Four score and seven years ago");System.out.print("Our fathers brought forth on this continent,");System.out.print("a new nation, conceived in liberty,");System.out.print("and dedicated to the proposition that all men are created equal.");

    }}

    Here we used the print method instead

    of the println method.

  • 7/30/2019 Computer Science 1301

    23/170

    2323

    THEprint METHOD,println METHOD, and the

    JAVA API

    The characters sent to console are displayed in a continuousstream.

    A subsequent insertion begins where the previous insertion leftoff.

    Even if the output is broken into several print statements, oneon each line, the output is displayed as one long continuousstream.

    Spaces we want included in the output must be included in theliterals we send to the method.

  • 7/30/2019 Computer Science 1301

    24/170

    2424

    THEprint METHOD,println METHOD, and the

    JAVA API

    Here we try to make the output look a little bit nicer by embedding

    some spaces in our strings.

    // A portion of the Gettysburg Address by Abraham Lincoln// gettysburgC.java Created using: jGRASP// By L. Thompson

    public class gettysburgC{

    public static void main(String[ ] args){

    // This version uses the print method, but in this// version I have embedded spaces in the strings to separate// the strings in the output.

    System.out.print("Four score and seven years ago ");System.out.print("Our fathers brought forth on this continent,");System.out.print(" a new nation, conceived in liberty,");System.out.print(" and dedicated to the proposition that all men are created equal.");

    }

    }

    Inserted spaces at

    these points

  • 7/30/2019 Computer Science 1301

    25/170

    2525

    THEprint METHOD,println METHOD, and the

    JAVA API

    It is possible to mix the use of theprintandprintln methods to getthe desired output.

    // A portion of the Gettysburg Address by Abraham Lincoln// gettysburgD.java Created using: jGRASP// By L. Thompson

    public class gettysburgD{

    public static void main(String[ ] args){

    // This version uses a combination of the print and println methods

    System.out.println("Four score and seven years ago");System.out.print("Our fathers brought forth on this continent,");System.out.println(" a new nation, conceived in liberty,");System.out.print("and dedicated to the proposition that all men are created equal.");

    }}

  • 7/30/2019 Computer Science 1301

    26/170

    2626

    THEprint METHOD,println METHOD, and the

    JAVA API

    Escape Sequences

    Another way to tell the computer to move the cursor to the

    beginning of a new line is to embed the newline escape

    sequence in a string literal at the point you want the new

    line to begin.

    The newline escape sequence is \n.

    In general, an escape sequence is a backslash, \, followed

    by one or more characters.

    Escape sequences are used to control the way output is

    displayed.

  • 7/30/2019 Computer Science 1301

    27/170

    2727

    THEprint METHOD,println METHOD, and the

    JAVA API

    Escape Sequences

    Causes a double quotation mark to be printeddouble quote\

    Causes a single quotation mark to be printedsingle quote\

    Causes a backslash to be printedbackslash\\

    Causes the cursor to go to the beginning of the current line, not

    the next linecarriage return\r

    Causes the cursor to back up, or move left, one positionbackspace\b

    Causes the cursor to skip over to the next tab stoptab\t

    Advances the cursor to the next line for subsequent printingnewline\n

  • 7/30/2019 Computer Science 1301

    28/170

    2828

    THEprint METHOD,println METHOD, and the

    JAVA API

    Escape Sequences// A portion of the Gettysburg Address by Abraham Lincoln

    // gettysburgE.java Created using: jGRASP

    // By L. Thompson

    public class gettysburgE

    {

    public static void main(String[ ] args)

    {

    // This version uses a combination of the print and println methods

    // It also uses the newline and horizontal tab escape sequences

    System.out.println("Four score and seven years ago");

    System.out.print("Our fathers brought forth on this continent,");

    System.out.print("\na new nation,conceived in liberty,\n");System.out.print("and dedicated to the proposition\n\nthat all men are reated\tequal.");

    }

    }

  • 7/30/2019 Computer Science 1301

    29/170

    2929

    VARIABLES

    A variable is a named location in the computers memory thatcan store a value that may be changed during the execution ofthe program.

    Part of the job of programming is determining what values

    need to be stored. The values stored in variables are often the inputs of the

    program and the results of calculations/processing.

  • 7/30/2019 Computer Science 1301

    30/170

    3030

    VARIABLES

    Declaring Variables

    In Java, variables must be declared before they are used.

    A variable declaration is a Java statement that tells the

    compiler that storage is needed for a value of a particular data

    type.

    A variable declaration consists of the data type of the variable(the kind of data it can store) followed by the name of the

    variable.

    A variable declaration ends with a semicolon.

  • 7/30/2019 Computer Science 1301

    31/170

    3131

    VARIABLES

    Declaring Variables

    The statement below declares a variable namedpayments that can beused to store an integer (whole number) value.

    int payments;

    The declaration

    begins with the data

    type. The keyword

    intis a data type for

    whole numbers.

  • 7/30/2019 Computer Science 1301

    32/170

    3232

    VARIABLES

    Declaring Variables

    The statement below declares a variable named interestRate thatcan be used to store a double (real number) value.

    double interestRate;

    The keyword double

    is a data type for

    real numbers.

  • 7/30/2019 Computer Science 1301

    33/170

    3333

    VARIABLES

    Declaring Variables

    You may declare several variables of the same data type in a singlestatement by separating the variable names with commas.

    int payments, month, day, year;

    The statement above is equivalent to the group of statementsbelow:

    int payments;

    int month;int day;int year;

  • 7/30/2019 Computer Science 1301

    34/170

    3434

    VARIABLES

    Rules for Naming Variables and Other Identifiers

    There are some rules that must be followed when creating the namesof variables and other identifiers.

    1. Do not use any of the Java key words as identifiers.

    2. The first character of an identifier must be an a-z, A-Z, anunderscore character (_), or the dollar sign ($).

    3. After the first character you can use letters a-z or A-Z, digits 0-9,underscores, or dollar signs.

    4. Spaces are not allowed in identifiers.

  • 7/30/2019 Computer Science 1301

    35/170

    3535

    VARIABLES

    Conventions for Naming Variables

    It is good programming style to give your identifiersmeaningful names. This means giving them names that give anindication of their usage.

    Write variable names using lowercase letters, capitalizing the

    first letter of the second and subsequent words that make up thevariable name. This helps to visually break up the words sincespaces cannot be used.

    double accountBalance, interestRate;

  • 7/30/2019 Computer Science 1301

    36/170

    3636

    VARIABLES

    Assigning a Value to a Variable

    Values may be assigned to variables using an assignmentstatement.

    We can store the value 36 in the variable namedpayments using

    the following assignment statement:

    payments = 36;

    An assignment copies the value of the expression on the right

    of the assignment operator into the location correspondingto the variable that is on the left of the assignment operator.

  • 7/30/2019 Computer Science 1301

    37/170

    3737

    // A program to calculate and display the area of two circles// AreaOf2Circles.java Created using: jGRASP// by L. Thompson

    public class AreaOf2Circles{public static void main(String[ ] args){

    double area, radius;

    // Calculate and display 1st area

    radius = 2.0;area = 3.14159 * radius * radius;System.out.print("The area of a circle with radius " + radius);System.out.println(" is " + area);

    Continued on the next slide

  • 7/30/2019 Computer Science 1301

    38/170

    3838

    Continued from the previous slide

    // Calculate and display 2nd area

    radius = 3.0;area = 3.14159 * radius * radius;System.out.print("The area of a circle with radius " + radius);System.out.println(" is " + area);

    }}

    Sample output:

    The area of a circle with radius 2.0 is 12.56636

    The area of a circle with radius 3.0 is 28.274309999999996

  • 7/30/2019 Computer Science 1301

    39/170

    3939

    VARIABLES

    When a numeric variable is used in a mathematical expression, thevalue stored in the memory location corresponding to the variableis used in the calculation.

  • 7/30/2019 Computer Science 1301

    40/170

    4040

    VARIABLES

    Displaying the Values of Variables

    We can display the value of a variable using aprintorprintlnstatement.

    int apples;

    apples = 5;System.out.print(apples); // 5 is displayed

    Notice that the variable name is not enclosed in quotationmarks.

    If quotation marks were placed around apples, it would be astring literal, and the characters between the quotation marks

    would be displayed on the computer screen, not the value in the

    apples variable.

  • 7/30/2019 Computer Science 1301

    41/170

    4141

    THE STRING CONCATENATION

    OPERATOR (+)

    The + operator can be used in two ways

    As the addition operator on numeric values

    As the concatenation operator when at least one of itsoperands is a string

    If either side of the + operator is a string, string concatenation isperformed and the resulting value is a string.

  • 7/30/2019 Computer Science 1301

    42/170

    4242

    THE STRING CONCATENATION

    OPERATOR (+)

    In the statement below, the concatenation operator creates the new

    string Hello World which is then passed as the argument to the

    rintln method and is displayed on the computer screen.

    System.out.println("Hello " + "World");

  • 7/30/2019 Computer Science 1301

    43/170

    4343

    THE STRING CONCATENATION

    OPERATOR (+)

    In the statement below, the concatenation operator creates the new

    string The value is: 2 which is then passed as the argument to the

    rintln method and is displayed on the computer screen. Notice the

    value ofnumberis not a string. The + operator converts the integer

    2 to a string and then appends this string to the string The valueis:, creating a new string.

    int number;

    number = 2;

    System.out.println("The value is: " + number);

  • 7/30/2019 Computer Science 1301

    44/170

    4444

    LITERALS

    A literal is aconstant value written in the code of a program.

    Literals are frequently used as:

    Values assigned to variables/attributes

    Operands in a arithmetic operations

    Display values

  • 7/30/2019 Computer Science 1301

    45/170

    45

    // A program to calculate and display the area of two circles// AreaOf2Circles.java Created using: jGRASP// by L. Thompson

    public class AreaOf2Circles{

    public static void main(String[] args){

    double area, radius;

    // Calculate and display 1st area

    radius = 2.0;area = 3.14159 * radius * radius;System.out.print("The area of a circle with radius " + radius);System.out.println(" is " + area);

    // Calculate and display 2nd area

    radius = 3.0;area = 3.14159 * radius * radius;System.out.print("The area of a circle with radius " + radius);System.out.println(" is " + area);

    }}

    Highlighted are

    some of the literalsused in this

    program. Can you

    find more?

  • 7/30/2019 Computer Science 1301

    46/170

    4646

    PRIMITIVE DATA TYPES

    Values in Java are classified according to their data type.

    The data type of a value determines how the value isrepresented in the computer and the kinds of operations that canbe performed on the value.

  • 7/30/2019 Computer Science 1301

    47/170

    4747

    PRIMITIVE DATA TYPES

    Numeric Data Types

    Numeric values can be divided into two classifications:

    Integer

    Floating-point

    Integers are whole numbers: 294

    111123

    950

    Floating-point numbers may have a decimal point:

    12.1

    169.5

    1347.98

  • 7/30/2019 Computer Science 1301

    48/170

    4848

    PRIMITIVE DATA TYPES

    Numeric Data Types

    The integer and floating-point categories are separated into a

    number of types that differ in the amount of storage allocated and

    the range of values that can be stored.

  • 7/30/2019 Computer Science 1301

    49/170

    4949

    PRIMITIVE DATA TYPES

    Numeric Data Types

    Table 2-5 textData Type

    (Key words) Size Range

    byte 1 byte Integers in the range-128 to +127

    short 2 bytes Integers in the range of -32,768 to +32,767

    int 4 bytes Integers in the range of -2,147,483,648 to +2,147,483,647

    long 8 bytes Integers in the range of -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807

    float 4 bytes Floating-point numbers in the range of

    3.4 10-38 to 3.4 1038, with 7 digits of accuracydouble 8 bytes Floating-point numbers in the range of

    1.7 10-308 to 1.7 10308, with 15 digits of accuracy

  • 7/30/2019 Computer Science 1301

    50/170

    5050

    PRIMITIVE DATA TYPES

    Numeric Data Types

    Integer Date TypesInteger data types are used for storing whole numbers.

    Example:

    byte rating;

    int offset;long acctNum;short days;

    offset = 7;acctNum = 1234567890;

  • 7/30/2019 Computer Science 1301

    51/170

    5151

    PRIMITIVE DATA TYPES

    Numeric Data Types

    Integer Data Types - Integer LiteralsWhen you write an integer literal in a Java program, it is

    automatically stored as a type int.

    The assignment statement in the segment below is assigning a

    value of type intto a variable of type short:

    byte rating;int offset;long acctNum;short days;

    days = 28;

  • 7/30/2019 Computer Science 1301

    52/170

    5252

    PRIMITIVE DATA TYPES

    Numeric Data Types

    Floating-Point Data Types Floating-point data types are used for holding numeric values

    that may include a decimal point.

    Thefloatdata type is considered a single-precision data type.It can hold a floating-point number with 7 digits of accuracy.

    The double data type uses twice as much memory as thefloatdata type; it is the double-precision floating-point data type.The double can hold a floating-point value with 15 digits ofaccuracy.

  • 7/30/2019 Computer Science 1301

    53/170

    5353

    PRIMITIVE DATA TYPES

    Numeric Data Types

    Floating-Point Data TypesExample:

    double range;float amount;

    range = 5.5;

  • 7/30/2019 Computer Science 1301

    54/170

    5454

    PRIMITIVE DATA TYPES

    Numeric Data Types

    Floating-Point Data TypesFloating-point values are typically stored inside the computer in anotation similar to scientific notation, called E notation.

    Decimal Notation Scientific Notation E Notation36.78 3.678 X 101 3.678E1

    218976.9 2.189769 X 105 2.189769E5

    .00445 4.45 X 10-3 4.45E3

    *** See Table 2-6 of the text

  • 7/30/2019 Computer Science 1301

    55/170

    5555

    PRIMITIVE DATA TYPES

    Numeric Data Types

    Floating-Point Data Types - Floating-Point Literals Floating-point literals are stored in memory with type double.

    Because of this, a problem can arise when you assign afloating-point literal to a variable of typefloat.

    Java is a strongly typed language, which means it will only let

    you store a value of a compatible data type in a variable. Since a double value can be much larger than a variable of type

    floatcan hold and the double has greater precision, the

    assignment statement below, which assigns the value to the

    variable named amount, will produce a compiler error.

    double range;float amount;

    amount = 27.98;range = 1.53e-5;

  • 7/30/2019 Computer Science 1301

    56/170

    5656

    PRIMITIVE DATA TYPES

    Numeric Data Types

    Floating-Point Data Types - Floating-Point LiteralsYou can get around this problem by specifying that the floating-

    point literal be stored as a type float by using the suffix F after the

    literal. The following segment will work.

    double range;float amount;

    amount = 27.98F;range = 1.53e-5;

  • 7/30/2019 Computer Science 1301

    57/170

    5757

    PRIMITIVE DATA TYPES

    The boolean Data Type

    Expressions that evaluate to a true or false value are calledBoolean expressions.

    The boolean data type allows you to create variables that canhave either the value true or the value false.

    The contents of a boolean variable may not be copied to avariable of any other data type.

  • 7/30/2019 Computer Science 1301

    58/170

    5858

    PRIMITIVE DATA TYPES

    Theboolean Data Type

    // A program to demo the boolean data type// BooleanDemo.java Creating using: JGRASP// by: L. Thompson

    public class BooleanDemo{

    public static void main(String[ ] args)

    {int number;boolean result;

    number = 15;

    result = number > 5;System.out.println("The value of result is " + result);

    result = number < 10;System.out.println("Now the value of result is " + result);

    }}

  • 7/30/2019 Computer Science 1301

    59/170

    5959

    PRIMITIVE DATA TYPES

    Theboolean Data Type

    Sample output for BooleanDemo.java:

    The value of result is true

    Now the value of result is false

  • 7/30/2019 Computer Science 1301

    60/170

    6060

    PRIMITIVE DATA TYPES

    Thechar Data Type

    A variable of type char, meaning character, can be used to store asingle character.

    Example:

    char grade;

    grade = A;

  • 7/30/2019 Computer Science 1301

    61/170

    6161

    PRIMITIVE DATA TYPES

    Thechar Data Type

    Character constants/literals are enclosed in single quotationmarks as in A. If you leave off the quotation marks, the

    compiler will thinkA is a variable you forgot to define whichis a syntax error.

    A is not equivalent to A. A is a string literal. String literals cannot be assigned to character variables.

    Characters are actually encoded in binary (sequences of onesand zeroes). Java uses Unicode to encode characters. Unicodeuses 16 bits (2 bytes) to encode each character.

    *** See Appendix B of the text

  • 7/30/2019 Computer Science 1301

    62/170

    6262

    PRIMITIVE DATA TYPES

    Thechar Data Type

  • 7/30/2019 Computer Science 1301

    63/170

    6363

    PRIMITIVE DATA TYPES

    Thechar Data Type

    Example:

    char grade;

    grade = A; // Assigns the binary equivalent of 65 to grade

  • 7/30/2019 Computer Science 1301

    64/170

    6464

    PRIMITIVE DATA TYPES

    Thechar Data Type

    The following statements contain a syntax error:

    char grade;

    grade = A; // Cannot assign a string to a character variable

  • 7/30/2019 Computer Science 1301

    65/170

    6565

    VARIABLE ASSIGNMENT AND

    INITIALIZATION

    The = symbol is the assignment operator in Java.

    The assignment operator is a binary operator, because it takestwo operands.

    The operand on the left of the assignment operator must

    correspond to a location in memory whose contents may bechanged. The operand on the right of the assignment operatorcan be any expression that has a value.

    An assignment statement stores the value of the expression thatis the right operand of the assignment operator in the memory

    location corresponding to the left operand of the assignmentoperator.

  • 7/30/2019 Computer Science 1301

    66/170

    6666

    VARIABLE ASSIGNMENT AND

    INITIALIZATION

    You may give a variable an initial value when you declare thevariable. This is called initializing the variable.

    Examples:

    float average = 96.2F;char letterGrade = 'A';long ID = 123456789;float salary = 564248.56F, bonus, retirement = 175.00f;boolean error = false;

    Notice that the variable bonus is uninitialized, it contains anunknown bit pattern. It is an error to print this value or use it in acalculation before it is given a value, because you have no ideawhat it contains.

  • 7/30/2019 Computer Science 1301

    67/170

    6767

    READING INPUT FROM THE KEYBOARD

    The Scanner Class

    The standard input device is normally the computer keyboard.

    The Java API has an object System.in which is associated withthe standard input device. We will use this object inconjunction with the Scannerclass to read input data from the

    keyboard. The Scannerclass has methods that can be used to read input

    and format it as primitive data values or strings.

  • 7/30/2019 Computer Science 1301

    68/170

    6868

    READING INPUT FROM THE KEYBOARD

    The Scanner Class

    To use the Scannerclass in our program we must put thefollowing statement near the top of our file, before any classdefinition:

    import java.util.Scanner;

    This statement tells the compiler where to find the Scannerclass.

  • 7/30/2019 Computer Science 1301

    69/170

    6969

    READING INPUT FROM THE KEYBOARD

    The Scanner Class

    You must also create a Scannerobject and connect it to theSystem.in object. You can do this with a statement like thefollowing:

    Scanner keyboard = new Scanner(System.in);

  • 7/30/2019 Computer Science 1301

    70/170

    7070

    READING INPUT FROM THE KEYBOARD

    The Scanner Class

    Scanner keyboard = new Scanner(System.in);

    The words Scanner keyboarddeclare a variable namedkeyboardwith data type Scanner. This variable will referencean object of the Scannerclass.

    You could have chosen any name you wanted for the variable,but keyboardis a good one since you are going to use it toaccess the keyboard.

  • 7/30/2019 Computer Science 1301

    71/170

    7171

    READING INPUT FROM THE KEYBOARD

    The Scanner Class

    Scanner keyboard = new Scanner(System.in);

    We use the assignment operator, =, because we want to assign avalue to the keyboardvariable.

    G

  • 7/30/2019 Computer Science 1301

    72/170

    7272

    READING INPUT FROM THE KEYBOARD

    The Scanner Class

    Scanner keyboard =new Scanner(System.in);

    The word, new, is a Java key word. The new key word is usedto create an object in memory.

    The type of object is listed after the key word new, this is

    Scanner. So we are creating an object of the Scannerclass. Inside the parentheses, we have System.in. Here we are saying

    that we want the object we are creating to be connected withthe System.in object, which again is associated with thekeyboard.

    We are assigning the address of the object created to ourvariable named keyboard, so keyboardwill reference theobject we have linked with the actual keyboard.

    READING INPUT FROM THE KEYBOARD

  • 7/30/2019 Computer Science 1301

    73/170

    7373

    READING INPUT FROM THE KEYBOARD

    The Scanner Class

    Every object created from the Scannerclass has methods that reada string of characters entered at the keyboard, converts them to aspecified type, and returns this value to be stored in a variable ofcompatible type.

    READING INPUT FROM THE KEYBOARD

  • 7/30/2019 Computer Science 1301

    74/170

    7474

    READING INPUT FROM THE KEYBOARD

    The Scanner Class

    For example the code below could be used to read an integerentered at the keyboard and store it in an integer variable namedage.

    int age;

    System.out.print(Enter your age: );age = keyboard.nextInt( );

    READING INPUT FROM THE KEYBOARD

  • 7/30/2019 Computer Science 1301

    75/170

    7575

    READING INPUT FROM THE KEYBOARD

    The Scanner Class

    The following statement is a prompt:

    System.out.print(Enter your age: );

    A prompt is a message that lets the user know what input is

    expected. Whenever you want the user to enter a value at the keyboard,

    you must display an appropriate prompt on the computerscreen.

    READING INPUT FROM THE KEYBOARD

  • 7/30/2019 Computer Science 1301

    76/170

    7676

    READING INPUT FROM THE KEYBOARD

    The Scanner Class

    int age;

    System.out.print(Enter your age: );age = keyboard.nextInt( );

    We are calling the nextInt( ) method of the keyboardobject toget a value entered by the user at the keyboard.

    The nextInt( ) method formats the characters entered bythe user as an intand returns the integer value.

    The integer value is assigned to the variable named age.

    READING INPUT FROM THE KEYBOARD

  • 7/30/2019 Computer Science 1301

    77/170

    7777

    READING INPUT FROM THE KEYBOARD

    The Scanner Class

    If you had named your Scannerclass object something else, saydog, the statements above would need to be changed as follows:

    Scanner dog = new Scanner(System.in);

    int age;

    System.out.print(Enter your age: );age = dog.nextInt( );

    READING INPUT FROM THE KEYBOARD

  • 7/30/2019 Computer Science 1301

    78/170

    7878

    READING INPUT FROM THE KEYBOARD

    The Scanner Class

    *** See Table 2-17 of the text for a listing of other useful

    methods of the Scanner class

    *** See the Java API online

  • 7/30/2019 Computer Science 1301

    79/170

    79

    // A program to calculate and display the area of a rectangle with side lengths entered by the user.// Source filename: RectangleArea.java Created using: jGrasp// Written by: L. Thompson

    import java.util.Scanner;

    public class RectangleArea{

    public static void main(String[ ] args){

    double length, width; // The length and width of the rectangledouble area; // The area calculated for the rectangle

    // Create a Scanner object to read input

    Scanner keyboard = new Scanner(System.in);

    // Get the dimensions of the rectangle from the user

    System.out.print("Enter the length of the rectangle: ");

    length = keyboard.nextDouble( );System.out.print("Enter the width of the rectangle: ");width = keyboard.nextDouble( );

    Continued on the next slide

  • 7/30/2019 Computer Science 1301

    80/170

    80

    Continued from the previous slide

    // Calculate the area of the rectangle

    area = length * width;

    // Display the results of the calculation

    System.out.print("\nA rectangle with length " + length + "\nand width ");System.out.println(width + " has an area of " + area);

    }}

    ARITHMETIC OPERATORS

  • 7/30/2019 Computer Science 1301

    81/170

    8181

    ARITHMETIC OPERATORS

    Java provides many operators that are useful for manipulatingdata and performing arithmetic operations.

    Operators can be classified as unary, binary, or ternarydepending on the number of operands the operator requires.

    Unary operators require a single operand. Binary operators require two operands.

    Ternary operators require three operands.

    ARITHMETIC OPERATORS

  • 7/30/2019 Computer Science 1301

    82/170

    8282

    ARITHMETIC OPERATORS

    Negation Operator ()

    The negation operator is a unary operator that negates the value ofits operand.

    The following statements define a variable named angle and assignthe value -50 to that variable.

    int angle;

    angle = 50;

    ARITHMETIC OPERATORS

  • 7/30/2019 Computer Science 1301

    83/170

    8383

    ARITHMETIC OPERATORS

    Addition Operator (+)

    The addition operator is a binary operator that returns the sum of itstwo operands.

    The following statement adds the value in amountto the value in

    bonus and stores the result in total.

    total = amount + bonus;

    ARITHMETIC OPERATORS

  • 7/30/2019 Computer Science 1301

    84/170

    8484

    ARITHMETIC OPERATORS

    Subtraction Operator()

    The subtraction operator is a binary operator that returns the resultof subtracting its right operand from its left operand.

    The following statement subtracts the value 27 from 70 and storesthe result (43) in amount.

    amount = 70 27;

    ARITHMETIC OPERATORS

  • 7/30/2019 Computer Science 1301

    85/170

    8585

    ARITHMETIC OPERATORS

    Multiplication Operator (*)

    The multiplication operator is a binary operator that returns theproduct of its two operands.

    The following statement multiplies the value in rate by the value intime and stores the result in distance.

    distance = rate * time;

    ARITHMETIC OPERATORS

  • 7/30/2019 Computer Science 1301

    86/170

    8686

    ARITHMETIC OPERATORS

    Division Operator (/)

    The division operator is a binary operator that returns the quotient ofits left operand divided by its right operand.

    The following statement divides the value inplayers by the value inmaxPlayers and stores the result in teams.

    teams = players / maxPlayers;

    ARITHMETIC OPERATORS

  • 7/30/2019 Computer Science 1301

    87/170

    8787

    ARITHMETIC OPERATORS

    Division Operator (/)

    If both operands of the division operator are integers the

    quotient is an integer. The fractional part is discarded.

    In the statements below, the expression 161 / 2 has the value 80,because both operands of the division operator are of type int. The.5 is discarded. The value 80.0 is assigned tox.

    double x;

    x = 161 / 2;

    ARITHMETIC OPERATORS

  • 7/30/2019 Computer Science 1301

    88/170

    8888

    ARITHMETIC OPERATORS

    Division Operator (/)

    If at least one of the operands of the division operator is a

    floating-point type the quotient is a floating-point type.

    In the statements below, the expression 161.0 / 2 has the value 80.5.The value 80.5 is assigned to the variablex.

    double x;

    x = 161.0 / 2;

    ARITHMETIC OPERATORS

  • 7/30/2019 Computer Science 1301

    89/170

    8989

    ARITHMETIC OPERATORS

    Division Operator (/)

    What is the data type of the result ofplayers / maxPlayers in thestatements below?

    double teams;

    teams = players / maxPlayers;

    ARITHMETIC OPERATORS

  • 7/30/2019 Computer Science 1301

    90/170

    9090

    ARITHMETIC OPERATORS

    Modulus Operator(%)

    The modulus operator is a binary operator that returns the remainderof a division operation. We can use this operator to find the numberof items left over after an integer division.

    The following statement divides 12by 10 and stores the remainderof the division (2) in nextDigit.

    nextDigit = 12 % 10;

    OPERATOR PRECEDENCE

  • 7/30/2019 Computer Science 1301

    91/170

    9191

    OPERATOR PRECEDENCE

    An expression may consist of a literal value, a variable, or be acombination of operators and operands.

    The evaluation of some expressions like 4 + 21 isstraightforward.

    Others are not so straightforward, for instance 16 8 / 4. Thevalue of this expression depends on whether the subtraction orthe division is performed first.

    OPERATOR PRECEDENCE

  • 7/30/2019 Computer Science 1301

    92/170

    9292

    OPERATOR PRECEDENCE

    In Java, mathematical expressions are processed from left toright.

    When two operators share an operand, the operation specifiedby the operator with the highest precedence is performed first.

    *** See Table 2-8 and Appendix C of the text

    Division has higher precedence than subtraction.

    In the expression:

    16 8 / 4

    the division, 8 / 4, is performed first, producing a quotient of 2.

    Then 2 is subtracted from 16 producing a result of 14.

    OPERATOR PRECEDENCE

  • 7/30/2019 Computer Science 1301

    93/170

    9393

    OPERATOR PRECEDENCE

    Continued on the next slide

  • 7/30/2019 Computer Science 1301

    94/170

    9494

    OPERATOR PRECEDENCE

  • 7/30/2019 Computer Science 1301

    95/170

    9595

    OPERATOR PRECEDENCE

    If two operators sharing an operand have the same precedence,the operators work according to their associativity.

    Associativity is either left to right or right to left.

    For instance, if a multiplication and division operator share an

    operand these operations will be performed left to right since

    multiplication and division associate from left to right.

    OPERATOR PRECEDENCE

  • 7/30/2019 Computer Science 1301

    96/170

    9696

    OPERATOR PRECEDENCE

    What is the value of the following expression?

    2 + 3 * 4

    OPERATOR PRECEDENCE

  • 7/30/2019 Computer Science 1301

    97/170

    9797

    OPERATOR PRECEDENCE

    What is the value of the following expression?

    10 + 3 * 8

    OPERATOR PRECEDENCE

  • 7/30/2019 Computer Science 1301

    98/170

    9898

    OPERATOR PRECEDENCE

    What is the value of the following expression?

    17 7 % 4 * 2

    OPERATOR PRECEDENCE

  • 7/30/2019 Computer Science 1301

    99/170

    9999

    OPERATOR PRECEDENCE

    What is the value of the following expression?

    15 + 20 / 8 + 6 * 2

    GROUPING WITH PARENTHESES

  • 7/30/2019 Computer Science 1301

    100/170

    100100

    GROUPING WITH PARENTHESES

    You may enclose an expression in parentheses to ensure that it isevaluated before other expressions that involve its operands.

    Example:

    y = (a b) / 4;

    Without the parentheses, the value ofb / 4 would have been

    calculated first and then this value would have been subtracted from

    a.

    GROUPING WITH PARENTHESES

  • 7/30/2019 Computer Science 1301

    101/170

    101101

    G OU NG N S S

    Example:

    x = 10 (8 4);

    The value of the expression, 10 (8 4), is 6. Without the

    parentheses, the expression is 10 8 4, in this expression 8 wouldhave been subtracted from 10 first, resulting in a value of 2, and

    then 4 would have been subtracted from 2, to produce the value 2.

    TheMath Class

  • 7/30/2019 Computer Science 1301

    102/170

    102102

    The Java API provides a class namedMath which includes manymethods for performing mathematical operations.

    TheMath Class

  • 7/30/2019 Computer Science 1301

    103/170

    103103

    TheMath.pow( ) Method

    Java does not have an exponent operator.

    To raise a number to a power we can use theMath.pow( )method. You can think of a method as a routine that performs a

    specific operation.

    TheMath.pow( ) method takes two double arguments.Arguments are data values sent to a method.

    TheMath.pow( ) method raises the value of the first argument tothe power of the second argument and returns the result of this

    calculation as a value of type double.

    TheMath Class

  • 7/30/2019 Computer Science 1301

    104/170

    104104

    TheMath.pow( ) Method

    Suppose that we want to calculate the volume of a cube. Thevolume of a cube, v, is specified by the algebraic formula:

    v = s3

    where s is the length of the side of the cube.

    In our program, we could specify this calculation as follows:

    v = Math.pow(s, 3);

    TheMath Class

  • 7/30/2019 Computer Science 1301

    105/170

    105105

    TheMath.pow( ) Method

    v = Math.pow(s, 3);

    Math.pow(s, 3) is a call to thepow method which is a member oftheMath class.

    This call is an expression, the value of this expression is the

    value returned by the method. In our case, this value is assignedto the variable v.

    Suppose s has the value 3.3, the value returned by the method

    call and assigned to v is 35.937.

    TheMath Class

  • 7/30/2019 Computer Science 1301

    106/170

    106106

    TheMath.pow( ) Method

    The value returned by theMath.pow( ) method can be usedanywhere a double value can be used.

    For example the algebraic expression j = y (x + 2)6could

    be encoded in Java as:

    = y - Math.pow(x + 2, 6);

    TheMath Class

  • 7/30/2019 Computer Science 1301

    107/170

    107107

    TheMath.sqrt( ) Method

    Java does not have a square root operator.

    We can use theMath.sqrt( ) method to find the square root of anumber.

    TheMath.sqrt( ) method takes a double argument and returnsthe square root of the argument as a value of type double.

    TheMath Class

  • 7/30/2019 Computer Science 1301

    108/170

    108108

    TheMath.sqrt( ) Method

    For example the algebraic expression:

    could be encoded in Java as:

    z = 4 * Math.sqrt(a + b);

    z a b 4

    COMBINED ASSIGNMENT OPERATORS

  • 7/30/2019 Computer Science 1301

    109/170

    109109

    In programs, it is quite common to get the current value of avariable, modify it, and then reassign the new value back to the

    original variable.

    Example:

    x = x + 10;

    This statement specifies that the value 10 is added to the current

    contents of the variablex and the resulting value becomes the new

    contents ofx. Effectively, this statement increases the value of thevariablex by 10.

    COMBINED ASSIGNMENT OPERATORS

  • 7/30/2019 Computer Science 1301

    110/170

    110110

    +=

    Java provides a shorthand way to write this statement using thecombined assignment += operator.

    Instead of writing

    x = x + 10;

    we can write:

    x += 10;

    The (+=) operator adds the value of the right operand to the current

    value of its left operand and stores the result in the left operand.

    COMBINED ASSIGNMENT OPERATORS

  • 7/30/2019 Computer Science 1301

    111/170

    111111

    =

    The (-=) operator subtracts the value of the right operand from thecurrent value of its left operand and stores the result in the left

    operand.

    For example:

    balance = balance withdrawals;

    could be written:

    balance - = withdrawals;

    COMBINED ASSIGNMENT OPERATORS

  • 7/30/2019 Computer Science 1301

    112/170

    112112

    *=

    The (*=) operator multiplies the value of the right operand by thecurrent value of its left operand and stores the result in the left

    operand.

    For example:

    j = j * a;

    could be written:

    *= a;

    COMBINED ASSIGNMENT OPERATORS

  • 7/30/2019 Computer Science 1301

    113/170

    113113

    /=

    The (/=) operator divides the current value of its left operand by thevalue of the right operand and stores the result in the left operand.

    COMBINED ASSIGNMENT OPERATORS

  • 7/30/2019 Computer Science 1301

    114/170

    114114

    %=

    The (%=) operator divides the current value of its left operand bythe value of the right operand and stores the remainder of the

    division in the left operand.

    COMBINED ASSIGNMENT OPERATORS

  • 7/30/2019 Computer Science 1301

    115/170

    115115

    The left operand of a combined assignment operator must be avariable.

    *** See Table 2-13 of the text

    COMBINED ASSIGNMENT OPERATORS

  • 7/30/2019 Computer Science 1301

    116/170

    116116

    The combined assignment operators have lower precedencethan the arithmetic operators +, -, *, /, and %.

    *** See Appendix C of the text

    For example:

    w /= b + 1;

    is equivalent to

    w = w / (b + 1);

    CONVERSION BETWEEN PRIMITIVE DATA

  • 7/30/2019 Computer Science 1301

    117/170

    117117

    TYPES

    The Java compiler checks that the values assigned to variables areof a type compatible with the variables data type.

    CONVERSION BETWEEN PRIMITIVE DATA

  • 7/30/2019 Computer Science 1301

    118/170

    118118

    TYPES

    For example, the compiler permits the following statements:

    int x = 5;float y;

    y = x; // Assigns an int to a float

    CONVERSION BETWEEN PRIMITIVE DATA

  • 7/30/2019 Computer Science 1301

    119/170

    119119

    TYPES

    However, the compiler rejects the assignment statement in thesegment below, saying possible loss of precision.

    double g = 13.9;int z;

    z = g; // Assigns a double to an int

    The compiler will not allow this assignment, because the data type

    double can hold a fractional value and also it can hold larger and

    smaller values than an intcan hold.

    CONVERSION BETWEEN PRIMITIVE DATA

  • 7/30/2019 Computer Science 1301

    120/170

    120120

    TYPES

    In Java the primitive data types are ranked. One data type outranksanother if it can hold a larger value.

    *** See Figure 2-6 of the text

    Numeric data type

    doublefloatlongintshortbyte

    Highest Ranking

    Lowest Ranking

    CONVERSION BETWEEN PRIMITIVE DATA

  • 7/30/2019 Computer Science 1301

    121/170

    121121

    TYPES

    If you write an assignment statement that assigns a value of a lower-ranking data type to a variable of a higher-ranking data type, Java

    automatically converts the value of the lower-ranking data type to

    the higher-ranking data type before the assignment. This type of

    conversion is called a widening conversion.

    The following is an example of a widening conversion:

    int x = 5;float y;

    y = x; // Assigns an int to a float

    CONVERSION BETWEEN PRIMITIVE DATA

    TYPES

  • 7/30/2019 Computer Science 1301

    122/170

    122122

    TYPES

    In general, Java does not automatically perform narrowingconversions. A narrowing conversion is a conversion from a

    higher-ranking data type to a lower-ranking data type.

    The following is an example of a narrowing conversion:

    double g = 13.9;int z;

    z = g; // Assigns a double to an int

    CONVERSION BETWEEN PRIMITIVE DATA

    TYPES

  • 7/30/2019 Computer Science 1301

    123/170

    123123

    TYPES

    The Cast Operator The cast operator is a unary operator that allows you to convert

    a value to a different data type.

    You can specify either a narrowing or a widening conversionusing the cast operator.

    The cast operator is a parenthesized data type.

    It specifies that the following operand is to be converted to thedata type in parentheses.

    CONVERSION BETWEEN PRIMITIVE DATA

    TYPES

  • 7/30/2019 Computer Science 1301

    124/170

    124124

    TYPES

    The Cast Operator

    double g = 13.9;int z;

    z = (int) g; // Makes a copy of the value in g that is type int & then assigns this value to z

    When you convert a floating-point type to an integer type, anyfractional portion is truncated (discarded).

    It is not rounded. In the statement above, the value 13 isassigned toz.

    The operand of the cast operator is not changed by theoperation. A copy of the value is made that is of the specifieddata type. The value in the variable g is not changed in thesegment above, it is still 13.9.

    See the programDemoTypeConv.java on webct. Compile this

  • 7/30/2019 Computer Science 1301

    125/170

    125125

    p g yp j p

    program, find and correct all syntax errors using the cast operator.

    Are there still logical errors? How could these be fixed? Make sure

    you understand the automatic data type conversions and theimplications of these?

    CONVERSION BETWEEN PRIMITIVE DATA

    TYPES

  • 7/30/2019 Computer Science 1301

    126/170

    126126

    TYPESAutomatic Type Conversion in Arithmetic Expressions

    When an arithmetic operator has operands of different data types,Java will temporarily convert the operand of the lower-ranking datatype to the higher-ranking data type.

    The result of the operation will be the same data type as the higher-

    ranking operand. When values of type byte and shortare used in arithmetic

    expressions, they are temporarily converted to type int.

    CONVERSION BETWEEN PRIMITIVE DATA

    TYPES

  • 7/30/2019 Computer Science 1301

    127/170

    127127

    TYPESAutomatic Type Conversion in Arithmetic Expressions

    Given the following declarations:

    int x = 16, y = 7;float f = 3.0F;

    What is the value and data type of the following expression?

    x / 5

    CONVERSION BETWEEN PRIMITIVE DATA

    TYPES

  • 7/30/2019 Computer Science 1301

    128/170

    128128

    TYPESAutomatic Type Conversion in Arithmetic Expressions

    Given the following declarations:

    int x = 16, y = 7;float f = 3.0F;

    What is the value and data type of the following expression?

    x / f

    CONVERSION BETWEEN PRIMITIVE DATA

    TYPES

  • 7/30/2019 Computer Science 1301

    129/170

    129129

    TYPESAutomatic Type Conversion in Arithmetic Expressions

    Given the following declarations:

    int x = 16, y = 7;float f = 3.0F;

    What is the value and data type of the following expression?

    f * 5 / 6

    CONVERSION BETWEEN PRIMITIVE DATA

    TYPES

  • 7/30/2019 Computer Science 1301

    130/170

    130130

    TYPESAutomatic Type Conversion in Arithmetic Expressions

    Given the following declarations:

    int x = 16, y = 7;float f = 3.0F;

    What is the value and data type of the following expression?

    17 / (y - 5) * f

    CONVERSION BETWEEN PRIMITIVE DATA

    TYPES

  • 7/30/2019 Computer Science 1301

    131/170

    131131

    TYPESAutomatic Type Conversion in Arithmetic Expressions

    Given the following declarations:

    int x = 16, y = 7;float f = 3.0F;

    What is the value and data type of the following expression?

    4.4 + x % 9

    What happens if you try to assign the value of the expression above

    to the integer variabley?

    Creating Named Constants Using the Key Word

    final

  • 7/30/2019 Computer Science 1301

    132/170

    132132

    final

    A named constant is a location in memory, given a name, whichcontains a data value that cannot be changed during the execution of

    the program.

    The declaration of a named constant looks like the declaration of a

    variable, except the key wordfinal precedes the data type in thedeclaration of a constant.

    Example:

    final double SALES_TAX_RATE = .0825;

    Creating Named Constants Using the Key Word

    final

  • 7/30/2019 Computer Science 1301

    133/170

    133133

    final

    Examples:

    final double RATE_PER_MILE = .50;final double BONUS_LEVEL = 1000000;final double INTEREST_RATE = .05667;final int INCHES_PER_FOOT = 12;

    final double LBS_PER_KG = 2.20;

    A named constant is a way of representing a literal value. Insteadof using the literal value in expressions, we use the named

    constant. Named constants are used to make programs more

    readable and to facilitate the modification of programs. By convention, programmers use all uppercase letters and

    separate words using the underscore character when naming

    constants. This helps distinguish named constants from variable

    names.

    Creating Named Constants Using the Key Word

    final

  • 7/30/2019 Computer Science 1301

    134/170

    134134

    final

    Examples:

    final double RATE_PER_MILE = .50;final double BONUS_LEVEL = 1000000;final double INTEREST_RATE = .05667;final int INCHES_PER_FOOT = 12;

    final double LBS_PER_KG = 2.20;

    A named constant must be given a value when it is declared.

    It is a syntax error to write a statement that attempts tochange the value in a named constant after its declaration.

    TheMath.PINamed Constant

  • 7/30/2019 Computer Science 1301

    135/170

    135135

    TheMath class, from the Java API, provides a named constant,Math.PI,which we can use in our programs. This constant has the value

    3.141592653589793, which is an approximation of the mathematical value

    pi.

    In our programAreaOf2Circles.java, we could have used the followingstatement to calculate the area of a circle:

    area = Math.PI * Math.pow(radius, 2.0);

    SCOPE

  • 7/30/2019 Computer Science 1301

    136/170

    136136

    The scope of a variable is the part of the program where thevariable can be accessed by name.

    Variables declared inside a method are called local variables.

    The scope of a local variable begins at its declaration and ends atthe closing brace, }, of the block in which it is defined.

    The compiler reads a program from top to bottom. The compilermust encounter the declaration of a variable before it finds the

    variable used in any other statement, or a syntax error occurs.

    You cannot declare two variables with the same name in the samescope.

    THE String CLASS

  • 7/30/2019 Computer Science 1301

    137/170

    137137

    Java does not have a primitive data type for holding a string ofcharacters.

    The Java API includes a class named String. Objects of theString class can be used to store and process strings.

    THE String CLASS

    Objects and Classes

  • 7/30/2019 Computer Science 1301

    138/170

    138138

    Objects and Classes

    Objects are software entities that have attributes and methods. An objects attributes are data values that are stored in the

    object.

    An objects methods are procedures for performing operationson the objects attributes.

    A class is a pattern from which objects are created/instantiated.

    THE String CLASS

  • 7/30/2019 Computer Science 1301

    139/170

    139139

    The first step in using an object of the String class is to declare avariable that can be used to reference an object of this class. This can

    be accomplished with a statement like the following:

    String street;

    This statement declares a variable named streetthat will reference an

    object of the String class.

    THE String CLASS

    Variables of Primitive Data Types vs Class Type

  • 7/30/2019 Computer Science 1301

    140/170

    140140

    Variables of Primitive Data Types vs. Class Type

    Variables

    A variable of a primitive data type, like int,float, double, char, long,

    etc. holds an actual data value.

    The statement below declares a variable of the primitive data type int.

    The variable named numbercontains the data value 25.int number = 25;

    number 25

    THE String CLASS

    Variables of Primitive Data Types vs Class Type

  • 7/30/2019 Computer Science 1301

    141/170

    141141

    Variables of Primitive Data Types vs. Class Type

    VariablesA class type variable holds the memory address of an object. We saythat a class variable references the object or is a reference variable.

    The statement below declares a variable that can hold the address ofa String object.

    String street;

    street address

    A String object

    THE String CLASS

  • 7/30/2019 Computer Science 1301

    142/170

    142142

    We can create/instantiate an object of the String class using the new

    operator.

    String street;

    street = new String("1600 Pennsylvania Avenue");

    This statement creates an object of the String class that holds the

    string 1600 Pennsylvania Avenue and assigns the address of this

    object to the reference variable named street.

    THE String CLASS

  • 7/30/2019 Computer Science 1301

    143/170

    143143

    Java provides a shorthand way of creating a String object. The

    following creates a String object in memory and stores the address

    of this object in the variable named street.

    street = "1600 Pennsylvania Avenue";

    Objects of other classes cannot be created in a similar way.

    THE String CLASS

  • 7/30/2019 Computer Science 1301

    144/170

    144144

    Objects of the String class have numerous methods for working with

    strings.

    *** See Table 2-15 of the text

    THE String CLASS

  • 7/30/2019 Computer Science 1301

    145/170

    145145

    Objects of the String class have a method named length( ) which

    returns the number of characters in the string, including spaces.

    The value 24 would be assigned to the integer variable named

    numChars in the statements below:

    String street = new String("1600 Pennsylvania Avenue");

    int numChars= street.length( );

    THE String CLASS

  • 7/30/2019 Computer Science 1301

    146/170

    146146

    Objects of the String class have a method named charAt( ) which

    returns the character at the specified index in the string. The first

    character in a string is at index 0; the second character is at index 1,

    etc.

    The character 6 would be assigned to the character variable namedletterin the statements below:

    String street = new String("1600 Pennsylvania Avenue");

    char letter = street.charAt(1);

    THE String CLASS

  • 7/30/2019 Computer Science 1301

    147/170

    147147

    Objects of the String class have a method named toLowerCase( )

    which returns a new string with all the characters converted to

    lowercase.

    The variable named newString will reference a String object

    containing the string 1600 pennsylvania avenue after

    the statements below are executed:

    String street = new String("1600 Pennsylvania Avenue");

    String newString = street.toLowerCase( );

    THE String CLASS

  • 7/30/2019 Computer Science 1301

    148/170

    148148

    Objects of the String class have a method named toUpperCase( )

    which returns a new string with all the characters converted to

    uppercase.

    THE String CLASS

  • 7/30/2019 Computer Science 1301

    149/170

    149149

    The methods discussed above do not change the original string.

    ThetoLowerCase( ) andtoUpperCase( ) methods create new

    String objects.

    *** See the Java API for additional methods for working with

    objects of the String class

    See the program StringDemo.java. See if you can figure out

    what is displayed by tracing the code (i e Try not to use the

  • 7/30/2019 Computer Science 1301

    150/170

    150

    what is displayed by tracing the code. (i.e. Try not to use the

    computer, you will not have access to a computer during the

    exam).

    Problem That Can Occur When a call to the

    nextLine( ) Method is Preceded by a Call to One

  • 7/30/2019 Computer Science 1301

    151/170

    151151

    ( ) y

    the Other Scanner Class Methods

    Calling the Scannerclasses nextLine( ) method following a call to

    one the Scannerclasses methods for reading a value of a primitive

    data type can cause a problem.

    Problem That Can Occur When a call to the

    nextLine( ) Method is Preceded by a Call to One

  • 7/30/2019 Computer Science 1301

    152/170

    152152

    ( ) y

    the Other Scanner Class Methods

    When the user types keystrokes at the keyboard, the keystrokesare stored in area of memory called the keyboard buffer.

    When the user presses the enter key, a newline character iswritten to the keyboard buffer.

    The Scannerclasses methods that read values of primitive datatypes, skip leading newline characters and stop reading at atrailing newline character, leaving this character in the keyboard

    buffer.

    Problem That Can Occur When a call to the

    nextLine( ) Method is Preceded by a Call to One

  • 7/30/2019 Computer Science 1301

    153/170

    153153

    ( ) y

    the Other Scanner Class Methods

    The nextLine( ) method does not skip leading newline characters.

    The nextLine( ) method reads characters from the keyboardbuffer until it reads its first newline character. The nextLine( )method does not put the newline in the String object, but does

    advance the read position past it. You might say the nextLine( )method consumes the newline character, but the other methodswe have learned do not.

    When a call to the nextLine( ) method reads a newline characterthat was left in the buffer by a preceding read using one of the

    other methods of the String class, it appears that the nextLine( )call was skipped, because it does not read any other characters.

    We can fix this problem by inserting another call to thenextLine( ) method to consume the problematic newlinecharacter.

    *** See the program BufferError java Notice that as it is

  • 7/30/2019 Computer Science 1301

    154/170

    154

    *** See the program BufferError.java. Notice that as it iswritten, the user is not allowed to enter the first name.

    Placing a call to thenextLine( ) method after line 21, but

    before line 24 will read past the problematic newlinecharacter.

    When developing a program echo inputs and

  • 7/30/2019 Computer Science 1301

    155/170

    155

    When developing a program, echo inputs and

    intermediate results on the computer screen to verify that

    values are getting stored as you expected.

    You can take these debug statements out before your code

    goes into production.

    COMMENTS

  • 7/30/2019 Computer Science 1301

    156/170

    156156

    Previously, we learned that comments are notes of explanation usedto document programs, sections of programs, or program statementsfor the humans who must read programs.

    COMMENTS

  • 7/30/2019 Computer Science 1301

    157/170

    157157

    In Java there are three ways to write comments.

    Single-Line comments begin with two forward slashes. Thecompiler ignores everything from the two forward slashes to theend of the line.

    Multi-Line comments start with a forward slash followed by anasterisk, /*, and are terminated by an asterisk followed by aforward slash, */. The compiler ignores everything between the

    /* and the */. This type of comment can span multiple lines.

    Documentation comments begin with a forward slash followedby two asterisks, /**, and end with an asterisk followed by aforward slash, */. The compiler also ignores these comments.

    COMMENTS

    Documentation Comments

  • 7/30/2019 Computer Science 1301

    158/170

    158158

    The Sun JDK includes a program namedjavadoc that reads asource code file and creates an HTML file that includes theinformation provided in the documentation comments.

    You should include a documentation comment before each classheader, providing a description of the class.

    You should also include a documentation comment before eachmethod header, which gives a description of the method.

    The HTML file created byjavadoc is formatted in the same wayas the documentation provided for the Java API, so you canproduce documentation for your classes that look just likestandard Java documentation.

    DIALOG BOXES

  • 7/30/2019 Computer Science 1301

    159/170

    159159

    A dialog box is a small graphical window that displays a message orrequests input from the user.

    We can create dialog boxes using theJOptionPane class.

    Two types of boxes we can create using theJOptionPane class are:

    Message Dialog A dialog box that displays a message and anOK button.

    Input Dialog A dialog box that prompts the user for input,provides a text field where input is to be typed,and displays OK and Cancel buttons.

    DIALOG BOXES

  • 7/30/2019 Computer Science 1301

    160/170

    160160

    In order to use theJOptionPane class we must put the statementbelow at the top of our file, before any class definition:

    import javax.swing.JOptionPane;

    DIALOG BOXES

    JOptionPane. showMessageDialog( )

  • 7/30/2019 Computer Science 1301

    161/170

    161161

    TheJOptionPane class has a static method calledshowMessageDialog( ), which we will use to display a messagedialog.

    The statement:

    JOptionPane.showMessageDialog(null, "Go Stars!");

    displays the message dialog shown below:

    DIALOG BOXES

    JOptionPane. showMessageDialog( )

  • 7/30/2019 Computer Science 1301

    162/170

    162162

    JOptionPane.showMessageDialog(null, "Go Stars!");

    The first argument specifies which frame the dialog is to bedisplayed in. In this class we will always specify the default frame

    by passing the key word null. The second argument is the messageyou want displayed in the dialog.

    The dialog box will close when the user clicks the OK button.

    DIALOG BOXES

    JOptionPane. showInputDialog( )

  • 7/30/2019 Computer Science 1301

    163/170

    163163

    TheJOptionPane class has a static method called showInputDialog( ),which we will use to display an input dialog.

    The statement:

    String enteredWeight = JOptionPane.showInputDialog("Enter your weight in pounds.");

    displays the input dialog shown below:

    DIALOG BOXES

    JOptionPane. showInputDialog( )

  • 7/30/2019 Computer Science 1301

    164/170

    164164

    String enteredWeight = JOptionPane.showInputDialog("Enter your weight in pounds.");

    The argument is the message you want displayed in the input dialog.This should be your prompt.

    If the user clicks the OK button, the String variable will reference thestring entered by the user in the text field. If the user clicks the Cancelbutton, the String variable will reference a special value null.

    DIALOG BOXES

    JOptionPane. showInputDialog( )

  • 7/30/2019 Computer Science 1301

    165/170

    165165

    String enteredWeight = JOptionPane.showInputDialog("Enter your weight in pounds.");

    Notice that the showInputDialog( ) method always returns the usersinput as a String. This is a problem is you wanted a numeric value thatyou could use in a mathematical expression. (You cannot do math on

    strings.)

    DIALOG BOXES

    JOptionPane. showInputDialog( )

  • 7/30/2019 Computer Science 1301

    166/170

    166166

    To convert a string to numeric value, we can use a method from a Javawrapper class.

    There is a class calledDouble that has a static member method calledarseDouble( ), which converts a string to a double, and returns the

    double.

    We could write the following:

    String enteredWeight = JOptionPane.showInputDialog("Enter your weight in pounds.");

    double weightInPounds = Double.parseDouble(enteredWeight);

    DIALOG BOXES

    Wrapper Classes - Double, Float, Long, Integer,

  • 7/30/2019 Computer Science 1301

    167/170

    167167

    Short, and Byte

    *** See Table 2-18 of the text for information about other

    wrapper classes and their member methods for converting to

    other numeric types

    DIALOG BOXES

    JOptionPane

  • 7/30/2019 Computer Science 1301

    168/170

    168168

    When you use theJOptionPane class in your program you must usethe System.exit( ) method to end the program or a thread will continueto execute.

    System.exit(0);

    The argument, zero, is used to indicate that the program endednormally.

  • 7/30/2019 Computer Science 1301

    169/170

    PROGRAMMING STYLE

  • 7/30/2019 Computer Science 1301

    170/170

    *** Refer to the document,Elements of Good Programming Style,

    which is available on webct.