IT 114: Introduction to Java
Class 17
Topics
Tips and Examples
Review
New Material
Homework 6
Homework 6 is due this Sunday at 11:59 PM.
You will find the assignment here.
If you have a problem or a question, make a post on the Class Discussion Area.
Homework 6
I have posted homework 6 here.
It is due this coming Sunday at 11:59 PM.
Mid-term
The mid-term exam will be given on Monday, March 23rd.
It will consist of questions like those on the quizzes along with questions
asking you to write short segments of Java code.
60% of the points on this exam will consist of questions from the Ungraded Class Quizzes.
The other 40% will come from four questions that ask you to write a short segment of code.
The last class before the exam, Friday, March 13th, will be a review session.
You will only be responsible for the material in the Class Notes for that class on the exam.
The Mid-term is a closed book exam.
Due Date for Homework Assignments 2 - 6
The due date for homework assignments 2 - 6
is Friday, March 20th at 11:59 PM.
It is also the due date for Class Exercises 2 - 17
That is the Friday of the Spring Break.
Any of these assignments submitted after that date
will receive a score of 0.
Tips and Examples
Never Assume Your Code Works
- In the American justice system a defendant is presumed innocent
- Until he or she is proven guilty
- In other words you are innocent until you have been shown to be guilty
- With code the opposite is true
- You should always assume your code is not working
- Until you can test it to prove otherwise
- This means your work is not done once you have written the code
- It is only finished when you can prove it works
Review
Objects
- Objects
are sections of RAM that can contain more than one value
- They can also contain methods
that act upon there values
- These values are called
attributes or
fields or
properties
- Objects do not have a name, just a position in RAM
- When you create an object its position must be stored in a variable
- Otherwise you will not be able to use the object
- The values and methods an object contains are defined by
a class
- Classes serve as the template or blueprints used to create an object
- Java is an object-oriented language
- A program in Java consists of one or more files
- Each of these files contain at least one class
Strings
- Strings are objects because they contain many values
- The format for
declaring and
initializing an array is
String VARIABLE_NAME = STRING_LITERAL;
- A
is a sequence of letters written out inside a Java program
- String literals must be enclosed in double quotes, "
String greeting = "Hello";
- Two strings can be joined to form a third string using
concatenation
- This is done using the concatenation
operator,
+
System.out.println(greeting + "John");
We Have Been Defining Unusual Classes
- All the Java programs you have seen so far are unusual
- Because they cannot be used to create an object of their class
- We will talk more about this in a future class
- All other Java classes can be used to create an object of their class
Two Kinds of Methods
- A method is a collection of statements that perform a specific task
- All methods are defined inside a class
- In Java you can define two kinds of methods
- Methods that work with the values inside an object
- Methods that do not work with values inside an object
- Methods of the first type can only be used on an object that you create from the class
- These are the most common type of Java methods
- The second type are called
static methods
- When we created programs to turn scores into grades we called a method
to convert string values into integers
number = Integer.parseInt(input);
- parseInt is a method of the
Integer class
- We did not have to create an Integer object
to use this method
- Similarly when we created the rand_int
method for our dice games, we did not have to create an object
- The method declaration
looked like this
public static int rand_int(int max, int min){
double value = Math.random() * (max - min) + min;
return (int) value;
}
- The keyword
static
means an object does not have to be created
to use this method
- In a certain sense, static methods live inside a class
- While all other methods live inside their objects
Dot Notation
- When we are calling a method defined inside the current class
we just use the name of the method
- When we call a method outside the current class
we have to use dot notation
- Dot notation has the following format
CLASS_NAME_OR_OBJECT_NAME.METHOD_NAME(PARAMETER_LIST
- When we are calling a static method we use the name of the class before the dot
int score = Integer.parseInt(input);
- For all other method calls we use the name of the variable pointing to the object
String name = "John Smith"
System.out.println(name + " is " name.length() + " long");
String Methods
- Here is a list of some of the more useful String methods
Method |
Description |
Return Type |
charAt(index) |
Returns the character at a specific position |
char |
contains(text) |
Returns true if the string contains the text |
boolean |
endsWith(text) |
Returns true if the last characters in the string are text |
boolean |
equals(string) |
Returns true if the two strings are equal |
boolean |
length() |
Returns the number of characters in the string |
int |
replace(text_1, text_2) |
Returns a new string where all the occurrences of text_1
are replaced by text_2
|
String |
split(text) |
Returns an array of strings. The text is used to mark off
each string from the next
|
String [] |
startsWith(test) |
Returns true if the the first characters of the string are text |
boolean |
substring(start_index, stop_index) |
Returns a string starting at the position of start_index and ending
just before stop_index
|
String |
toLowerCase() |
Returns a new string will all characters lowercase |
String |
toUpperCase() |
Returns a new string will all characters UPPERCASE |
String |
charAt(index)
- A string is like an array of characters
- But you can't use the [] operator with strings
- You use the charAt method instead
- As with arrays you use zero-based indexing
- So the index of the first character is 0
equals(string)
- The equals method compares two strings
and returns true if they are equal
contains(text)
- contains returns true if its argument
is contained within the string
length()
replace(text_1, text_2)
- replace takes two strings as it arguments
- It returns a new string where every occurence of the first string is
replaced by the second string
split(text)
- split splits a string into an array of strings
- In order to spilt the string into small sub-strings we need to
know characters to use as the border between adjacent sub_strings
- The string that serves as the boundary is called a
delimiter
- For example say we had the following string
"John, Smith, 0124353"
- Here the delimiter is ", "
- The code below shows split in action
public class SplitString {
public static void main (String[] args){
String string = args[0];
String delimiter = args[1];
String [] fields = string.split(delimiter);
for (int i = 0; i fields.length; i++){
System.out.println(fields[i]);
}
}
}
$ java SplitString "John, Smith, 0124353" ", "
John
Smith
0124353
$ java SplitString "2020-01-10" "-"
2020
01
10
startsWith(text) and endsWith(text)
- startsWith returns true if its argument
is the first few characters in the string
- endsWith returns true if its argument matches
the last few characters in the string
substring(start_index, stop_index
- A substring
is a string contained within another string
- The substring method returns a part of another string
- It takes two integer arguments
- The first argument is the position where the substring you want begins
- The second argument is one more than the position where the
substring you want ends
toLowerCase() and toUpperCase()
- toLowerCase returns a new string where all the letters
in the string a turned lowercase
- It does does not change characters that are not letters
- toUpperCase returns a string where all the
lowercase letters are uppercase
- And does not change any characters that are not letters
trim()
- trim returns a new string with
whitespace
characters from the beginning and end of the string removed
- The whitespace characters are
Space | ' ' |
Tab | '\t' |
Newline | '\n' |
New Material
The Empty String
- The empty string
is a string with nothing in it
public class EmptyString {
public static void main (String[] args){
String empty = "";
System.out.println("---" + empty + "+++");
System.out.println("empty.length(): " + empty.length());
}
}
$ java EmptyString
---+++
empty.length(): 0
- The empty string acts like zero for strings
- If you add a number to zero the result is the number you added
- This is also true for the empty string
public class AddToEmpty {
public static void main (String[] args){
String empty = "";
String word = "hello";
show_string("empty", empty);
show_string("word", word);
show_string("empty + word", empty + word);
}
public static void show_string(String name, String s){
System.out.print(name + ": ---" + s + "---");
System.out.println(", Length: " + s.length());
}
}
$ java AddToEmpty
empty: ------, Length: 0
word: ---hello---, Length: 5
empty + word: ---hello---, Length: 5
- This Means you assemble a string bit by bit from other strings
public class BuildString {
public static void main (String[] args){
String str = "";
show_string(str);
for (int i = 0; i < args.length; i++){
str = str + args[i];
show_string(str);
}
}
public static void show_string(String s){
System.out.print("str: ---" + s + "---");
System.out.println(", Length: " + s.length());
}
}
$ java BuildString foo bar bletch
str: ------, Length: 0
str: ---foo---, Length: 3
str: ---foobar---, Length: 6
str: ---foobarbletch---, Length: 12
Strings Cannot Be Changed
- String objects are
immutable
- That means they cannot be changed
- This was a design decision made by the the creators of the Java language
- Every time a string is created while running a Java program it is
put in a special place called a string pool
- So when we write
s1 = "dog"
- This is the picture in memory
- But if the program creates another string with the same characters
a new String object will not be created
- Instead a new variable will point to an existing string
with the same characters
s2 = "dog"
- This is done to save memory space
- What happens when you assign a new string to the
variable s1?
- In that case the a new string object is created
- But the old one remains in memory
s1 = "cat"
- What happens when you use one string to create another
by concatenation?
- Again a new string is created
s1 = s1 + "food"
Garbage Collection
- What if you were writing code that created a lot of strings?
- Wouldn't that use up a lot of memory?
- Indeed it would
- There is a type of program error called a "memory leak"
that can happen when too many objects are created
- Each program gets a certain amount of RAM to do it's work
- If you use up too much memory for objects, the program will crash
- But Java a many other languages have a solution to this problem
- Every time an object is created, Java keeps track of the
number of variables that point to it
- This information is kept in a table
- And it updated as variables come and go
- Periodically, the Java interpreter does something called
garbage collection
- The interpreter looks through the table and removes any
object from memory that has no variable pointing to it
- If no variable points to an object there is no way
it can be used in the program
- So it is safe to delete it so the RAM can be used
for other things
Strings in Memory
- All programs run and do their work in RAM
- And RAM only hold binary numbers
- Every value in a computer thus must be stored as a
binary number
- Binary number are written in powers of 2
and are written using 1s and 0s
- Strings are a collection of characters in a given order
- To store characters in a RAM we need a table that assigns a number
to each character we want to use
- Over the years different tables have been used for this purpose
ASCII
- In the early days of computing in this country the most frequently used
character table was something called ASCII
- ASCII stands for American Standard Code for Information Interchange
- It was developed by the telegraph industry
- You will find the table for ASCII here
- ASCII was developed in the United States for use with teletype machines
- ASCII has 128 characters which stood for 95 characters
- And 33 control codes
- Each character can be stored in 7
bits of memory
Unicode
- ASCII was good enough for English but lacks characters used in many European languages
- Let alone Asian and African languages
- Nowadays we use an new character table called Unicode
- Unicode represents all the characters in most world languages
- The first 128 Unicode characters are the ASCII characters
- so ASCII is included in Unicode
- The latest version of Unicode contains 128,237 characters covering 135 modern and ancient writing system
- Most of the major world writing systems are contained in Unicode
- But Chinese characters pose a challenge
- Altogether there are over 50,000 Chinese characters though a good modern dictionary will rarely list over 20,000
- An educated Chinese person will know about 8,000 characters
- But you only need to know about 2-3,000 to read a newspaper
- Unicode currently has 74,605 CJK characters which are used in writing Chinese
- But also in Japanese Kanji Korean Hanja and Vietnamese Chu Nom
Representing Unicode Values
- With close to 130,000 characters you cannot represent all Unicode characters in only 7 bits as you can in ASCII
- Some characters would require 17 bits
- If you used 17 bits to represent every character text documents would be extremely large
- But the number values that represent different Unicode characters
can be represented inside the computer in different ways
- Each of these schemes is called an encoding
- The most commonly used Unicode encoding is UTF-8
- This is the encoding Python uses by default
- UTF-8 uses a variable number of bytes to represent each Unicode character
- Either 1, 2, 3 or 4 bytes
- If you stick to English each character is one byte long
- You will find a listing on Unicode characters represented in UTF-8
here
Comparing Strings
The String compareTo()Method
- The String (text) method is used
to compare two strings
- It returns an integer which is positive, negative or zero
Positive |
The first string comes after the second string in dictionary order |
Zero |
The two strings are the same |
Negative |
The first string comes beforethe second string in dictionary order |
- Here is an example
public class StringCompare {
public static void main (String[] args){
print_compare("car", "cab");
print_compare("car", "car");
print_compare("cab", "car");
print_compare("car", "cabbage");
print_compare("a", "A");
print_compare("A", "a");
}
public static void print_compare(String s1, String s2){
System.out.println("\"" + s1 + "\".comparteTo(\"" + s2 + "\"" + ") -> " + s1.compareTo(s2));
}
}
$ java StringCompare
"car".comparteTo("cab") -> 16
"car".comparteTo("car") -> 0
"cab".comparteTo("car") -> -16
"car".comparteTo("cabbage") -> 16
"a".comparteTo("A") -> 32
"A".comparteTo("a") -> -32
Packages
Using Java Packages
- There are hundreds of Java packages
- To use a class in a program its package must be
brought into the RAM of a running program
- Bringing a package into RAM is called
importing
- There are so many packages that it is impossible to import them all
- Instead the Java interpreter automatically imports a package
with many classes useful for a broad range of task
- The name of this package is java.lang
- It includes a number of basic Java classes
Importing Packages
Interactive Programs
- Program often need information from the user when they are run
- This can be done from the command line
- But the user has to remember what command line arguments are needed
- It is often better to have the program ask the user for input
- Programs that do this are called
interactive programs
- Nowadays, Java programs usually ask for input using a
Graphical User Interface
- Writing Java programs that work with a
GUI
is beyond the scope of this course
- But there is a simpler way
- You can create a Scanner object
Using a Scanner Objects
- A Scanner object allows a Java program to
ask the user input from the command line
- You first create a Scanner object like this
Scanner SCANNER_VARIABLE = new Scanner(System.in);
- Of course you need to tell the user what kind of information the program needs
- You do this by printing a prompt
- A prompt is a short message that tells the user that input is needed
- It is best to use System.out.print to print the prompt
- That way the user will enter data on the same line as the prompt
- You then call one of a number of methods on the Scanner
object to get what the user enters
- Here is an example
import java.util.Scanner;
public class HiThere {
public static void main (String[] args){
Scanner console = new Scanner(System.in);
System.out.print("What is your name? ");
String name = console.next();
System.out.println("Hi " + name + "!");
}
}
$ java HiThere
What is your name? John
Hi John!
- Notice that the
import
statement is at the top of the file
- When the Java interpreter gets to the other red
statement it waits
- When the user types something at the command line the program resumes
- And the string entered by the user is assigned to name
Scanner Methods
- In the code above we used the next method
of the Scanner object to return a string
- That the user entered on the command line
- But what if the value you wanted was an integer or a decimal?
- The Scannerobject provides different methods to do this
to return data of different types
Method | Description |
next() |
Reads and returns the next
token
as a String
|
nextDouble() |
reads and returns a double value |
nextInt() |
reads and returns an int value |
nextLine() |
reads and returns the next line of input as a
String
|
- Whenever you call one of these Scannermethods, it
- Waits for the user to type in some data and hit Enter or Return
- Takes in the data entered at the keyboard as a string
- Converts that data into a value of the right data type
- Returns that data to the statement that called it
Sample Interactive Program
- Here is a program that asks the user for three pieces of information
- Amount of loan
- Number of years
- Interest rate
import java.util.Scanner;
public class Mortgage {
// class driver
public static void main(String[] args) {
Scanner console = new Scanner(System.in) ;
System.out.println("This program computes monthly mortgage payments." ) ;
System.out.print("Loan amount : " ) ;
double loan = console.nextDouble() ;
System.out.print("Number of years : " ) ;
int years = console.nextInt() ;
System.out.print("Interest rate : " ) ;
double rate = console.nextDouble() ;
System.out.println() ;
int n = 12 * years;
double c = rate / 12.0 / 100.0;
double payment = loan * c * Math.pow( 1 + c, n) / (Math.pow( 1 + c, n) - 1) ;
System.out.println("payment = $" + Math.round(payment));
}
}
$ java Mortgage
This program computes monthly mortgage payments.
Loan amount : 200000
Number of years : 30
Interest rate : 4
payment = $955
- User input appears in blue
Class Quiz
Attendance
Class Exercise