Welcome to Lesson 6!

Learning Objectives
By the end of today's class, you should know...
  • How do you do more complex mathematical calculations than +, -, *, /, and % ?
  • What is Unicode?
  • What is a String?
  • What is the difference between a char and a String?
  • What is String concatenation?
  • What are two ways to do console input with a String?


  • Quiz 2 after our break!
  • Midterm 1 postponed by one class due to cancelled class

Review Activities

Q1: What Gets Printed to the Screen?

//assume below statement are part of a main function

int oranges = 5;

int apples = 3;

int numFruit = apples + oranges;

System.out.println("Total Fruit: " + numFruit);

apples = apples - 2;

oranges = apples;

System.out.println("Apples: " + apples);

    System.out.println("Oranges: " + oranges);

Q2: Write a complete user interaction as follows (3-4 lines of code only!):
  • Declare a new Scanner variable named input, and connect it to the console keyboard.
  • Declare a double variable named height.
  • Prompt the user to enter his or her height with a message like Enter your height:
  • Read in the user input and store it as the height variable

Q3: Write one statement to import the class to use Scanner in your program

Q4: What will the following statements output to the console

1. System.out.println(7 / 2.0);

2. System.out.println(7 / 2);

3. System.out.println(7 % 2);

4. System.out.println(9 + 3 * 5 / 2 - 3);

Mathematical Methods

  • Operators provide only the simplest mathematical operations
  • For more complex mathematical operations, we use methods defined in the Math class.
  • java.lang.Math class contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.
  • A Java method is like a math function that takes an argument ("input") and produces ("returns") a value
  • For example:
    double square_root = Math.sqrt(9.0);
  • In the above example, the input is 9.0 and the Math.sqrt() method returns the square root of the argument
  • Java has a class named Math that contains many such methods.
  • Math is part of the java.lang package which is automatically imported into your program.
  • Therefore, to use the Math class, all you need to do is to append the word Math in front of your mathematical methods.
  • Some of the functions are listed below
  • Note that many of these functions are designed to work with floating-point date types like double

expexponential (ex)Math.exp(1.0)2.71828
lognatural logMath.log(10.0)3.10259
powpowers (xy)Math.pow(2.0, 3.0)8
sqrtsquare rootMath.sqrt(4.0)2
  • In addition, the Math class includes two similar functions: ceil, and floor
ceilceiling: round upMath.ceil(3.0001)
floorfloor: round downMath.floor(3.3)
  • Both return whole numbers, although they are of type double
  • Why might this be the case?

Using Mathematical Methods

  • How are mathematical methods evaluated?
  • Whatever is within the parenthesis of the function call is evaluated first
  • Thus, in the following example, we get the square root of 9.0
    double square_root = Math.sqrt(3.0 * 3);
  • If the method is used in an arithmetic expression, they are handled just like a number of the type returned
  • For example, in the following, the value 4.0 is stored in the double variable num:
    double num = 1 + Math.sqrt(3.0 * 3.0);
  • Note that the method evaluates the Math.sqrt(3.0 * 3) before adding it to 1.0
  • Thus methods have a higher precedence than arithmetic operators.

Activity 6.1: Imagine All the People (10 pts)

  • Worldwide population continues to grow every year [1]. One model for projecting the growth is given by the equation:
    population = 7.35 · e 0.0071 (Year - 2016)
  • which reports the results in billions.
  • The letter e in the above formula is the mathematical symbol for Euler's number, the base of the natural logarithms.
  • To calculate this exponent in Java, you will need to use the Math.exp() method from java.lang.Math.
  • Find a partner for pair programming and open a new Java project named PopGrowth in Eclipse
  • Add a block comment at the top of your program with your names and section information.
    * Name of partner 1
    * Name of partner 2
    * Section info
  • With your partner, write a program that requests a year from a user and displays the estimated population for that year as shown in the Example Run below.
  • You must name the source code file PopGrowth.java.
  • Create a new Scanner variable at the top of your program, named input.
  • Then, declare a new integer variable called year.
  • Prompt the user to enter the year for which they wish to calculate the world population.
  • Calculate the population for the year using the formula for population shown above.
  • Use the Math.exp() method from java.lang.Math  to calculate the power of e (Euler's number).
  • Example Run: The outputs of the program must look like the following for you to receive full credit. For the input shown (2020) you must get the same output. However, the output numbers must change if the inputs are different.
    Enter the year: 2020
    Estimated worldwide population in 2020: 7.561732368586969 billion
  • Use the default formatting and precision for the numbers -- do NOT add any numerical formatting statements to the code.
  • When your program works identically to the example output above, submit PopGrowth.java to Canvas.

Review of Char

  • In addition to numbers, computers can manipulate text and other non-numerical types
  • Values of type char (short for character) are a single letter, number or special symbol
  • You specify a character by enclosing it in single quotes (')
    • The quote marks are not part of the data
  • For example:
    'a'   'b'   'Z'   '3'   'q'   '$'   '*'
  • When you use a char data type, you store the character using a Unicode code.

Java and Unicode

  • Unicode is a coding method that assigns a number to every character in every language in the world.
  • Unicode assigns a numeric value to 1,112,064 different characters.
  • Java's char type was designed to work with Unicode.
  • However, Java uses only 2 bytes to store each character - which is not sufficient to store the Unicode value for all characters. Any additional characters that Java cannot store as a char are known as supplementary characters.

Char Variables - Declaring and Assigning

  • As with other data types, you must declare char variables before use:
    char letter;
  • You assign values to a char variable using the equals sign:
    letter = 'A';
  • Just like numerical types, you can combine declaration and assignment into one statement:
    char letter = 'A';
  • Also like numerical types, you can declare multiple variables on one line:
    char letter, letterA = 'A', letterB = 'B';

Introduction to Strings

  • In addition to single characters, computers can work with text strings
  • For example, in the following the characters between the double quotes are displayed as text:
    System.out.println("Hello World!");
  • Programmers refer to text like this as a String because it is composed of a sequence of characters that we string together
  • Java provides the String type so we can work with text
  • Strings are enclosed in double quotes, which are not part of the String
  • For example:
    "Hello"  "b"  "3.14159"  "$3.95"  "My name is Fred"
  • Notice that the String "3.14159" could be expressed as a double by removing the quotes
  • However, a computer stores these two values very differently and we must use them in different ways
  • For instance, we cannot multiply the "3.14159" by 2, but we can when it is expressed as a double:
    "3.14159" * 2; // NO!
    3.14159 * 2; // allowed 

String Variables and Simple I/O

  • We declare and assign values to String variables like numeric types
  • For example:
    String firstName;             // declaration
    firstName = "Jennifer";       // assignment
    String lastName = "Parrish";  // declaration + assignment
    System.out.println(firstName + " " + lastName);

Simple I/O with Strings Using next():

  • Like numbers, you can output type String using System.out.println()
  • To read in a String value we can use the next() method:

    firstName = input.next(); //note that this is not nextString()!

  • For example:
    String firstName;
    System.out.print("Enter your name: ");
    firstName = input.next();
    System.out.println("You entered: " + firstName);
  • The input.next() statement assigns the user input to the String variable fname
  • Note that only a single word can be entered using input.next()
  • This is because input.next() works as follows:
    1. Skips whitespace
    2. Reads non-whitespace characters into the variable
    3. Stops reading when whitespace is found

Reading Data Line-By-Line Using nextLine():

  • Another Scanner method called nextLine() allows us to read an entire line of text into a String variable.
  • For example, if we want to take in the user's whole name, we would choose nextLine() instead of next().
  • For example:
    String fullName;
    System.out.print("Enter your name: ");
    fullName = input.nextLine();
    System.out.println("You entered: " + fullName);
  • input.nextLine() works differently from input.next() 
    • It reads until it finds a newline character.

The Problem with Newlines

  • When you press the Enter key, a newline character ('\n') is inserted as part of the input
  • The newline character can cause problems when you mix input.next(), input.nextInt() or input.nextDouble() with input.nexLine()
  • Recall that input.next(), as well as nextInt() and nextDouble():
    1. Skips whitespace
    2. Reads non-whitespace characters into the variable
    3. Stops reading when whitespace is found
  • Since whitespace includes newline characters, using input.next() will leave a newline character in the input stream
  • However, input.nextLine() just stops reading when it first finds a newline character
  • This can lead to mysterious results in code like the following:
    System.out.print("Enter your age: ");
    int age = input.nextInt();
    System.out.print("Enter your full name: ");
    String name = input.nextLine();
    System.out.println("Your age: " + age + "\n"
         + "Your full name: " + name);
  • To correct this problem we add an additional input.nextLine() just before input.nextLine()

System.out.print("Enter your full name: "); 
input.nextLine(); //clear out the \n
String name = input.nextLine();

  • We can see how to use this fix in the following example

Example Using an additional input.nextLine()

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    System.out.print("Enter your age: ");
    int age = input.nextInt();

    System.out.print("Enter your full name: ");
    input.nextLine(); //clear out the \n
    String name = input.nextLine();     System.out.println("Your age: " + age + "\n"     + "Your full name: " + name);

Joining Strings (Concatenation)

  • You can join two Strings together using the '+' operator
  • The join operation is called concatenation
  • We have seen concatenation before in our System.out.print statements:

System.out.println("Your age is: " + age);

  • Another concatenation example:
    String s1 = "Hello", s2 = "World!";
    String s3 = s1 + s2;
  • The String s3 now has the contents of both s1 and s2
  • You can also mix String variables and literal Strings:
    String s1 = "Hello", s2 = "World!";
    String s3 = s1 + ", " + s2;
  • We can also join numbers and Strings using concatenation.
  • Note that concatenation between a number and a String will cause the number to be converted automatically to a String.
  • For instance:
String address = 124 + " East Ave";
  • In addition, we can concatenate Strings and characters:
    char letter = 'A';
    String s1 = "BC";
    s1 = letter + s1 + 'D';

Activity 6.2
: Working with Strings (10 pts)

  • Find a partner for pair programming and open a new Java project named MyName in Eclipse
  • We will create a program to greet the user by name.
  • Add a block comment at the top of your program with your names and section information.
* Name of partner 1
* Name of partner 2
* Section info
  • At the top of the main method, let's declare our first String variable - to store the first name of our user:
String first_name;
  • Declare a second String variable to store the last name of our user in the same _ style.
  • Declare a third String variable to store the user's full name:
String full_name;
  • Finally, declare a new Scanner variable named input and connect it to the console keyboard.
  • Welcome the user with a statement like this one:
System.out.println("Hi! I want to learn your name!");
  • Now, prompt the user to enter their first name.
System.out.print("Please enter your first name: ");
  • Follow this prompt with a input.next() statement to capture the user input.
first_name = input.next();
  • Now prompt the user to enter his or her last name and store the input in the last_name variable.
  • We want to assign the full_name variable the value of the user's first and last name combined. Let's do so now using concatenation:
full_name = first_name + " " + last_name;
  • Finally, let's greet the user by his or her full name.
System.out.println("Nice to meet you " + full_name + "!");

  • Lastly, close your Scanner
  • Run your program to ensure it is giving you the output you expect.
  • Then, hold onto it as we are going to use complete this program in the next activity.

Wrap up
  • Answer the questions from today's learning objectives
Assignment 6 due Tuesday at 11:20am
Lab 4 due Friday at Midnight
~See You Thursday!~