Title: Introduction to Programming
1Introduction to Programming
CIS 202September 14, 2007
- David Goldschmidt, Ph.D.
- Computer Science
- The College of Saint Rose
2Representing Characters in Java
- Characters (e.g. letters, digits, symbols) are
represented using the char data type
char c, d, e c 4 d u e
! System.out.print(c) System.out.print(d) Sy
stem.out.print(e)
3ASCII Unicode Characters
- Character data types are encoded as numbers
- Java uses two
bytes to store
characters as
Unicode
4Character Strings (i)
- A group of characters is called a character
string - String literals are enclosed in double quotation
marks - The String class in Java allows you to create
character string variables
System.out.print("This is a string")
String s1 "This is a string"
5Character Strings (ii)
- In Java, String objects are similar to variables
String s1 "This is a string"
6Character Strings (iii)
- We can use print and println to display String
objects in Java
String firstName "Dave" String lastName
"Goldschmidt" System.out.print("Hello,
") System.out.println(firstName) System.out.pri
nt("Bye Dr. ") System.out.println(lastName)
7The String Class Methods (i)
- Once we have a String object created, we can use
various methods of the String class - Determine the length of a String
String firstName "Dave" String lastName
"Goldschmidt" int len lastName.length() Syste
m.out.print("Your name has ") System.out.println(
len " letters.")
8The String Class Methods (ii)
- Once we have a String object created, we can use
various methods of the String class - Convert a String to uppercase or lowercase
String s "Java is cool" System.out.println(s.to
UpperCase()) String lower s.toLowerCase() Sys
tem.out.println(lower)
9The String Class Methods (iii)
- Once we have a String object created, we can use
various methods of the String class - Obtain individual characters from the String
String s "Java is cool" char firstLetter
s.charAt(0) char thirdLetter
s.charAt(2) System.out.print(firstLetter) Syste
m.out.println(thirdLetter)
10Reading Keyboard Input (i)
- A running Java program can have both output
(System.out) and input (System.in)
Java Program Execution
11Reading Keyboard Input (ii)
- To read input from the keyboard, we use Javas
Scanner class - Create a Scanner object associated with System.in
Scanner keyboard new Scanner(System.in)
12Reading Keyboard Input (iii)
- Once created, use the Scanner object to read
keyboard input
Scanner keyboard new Scanner(System.in) System
.out.println("Whats your name?") String name
keyboard.nextLine() System.out.println("How old
are you?") int age keyboard.nextInt()
13Reading Keyboard Input (iv)
- To use the Scanner class, we need to import in
the class from the java.util package
import java.util.Scanner public class
NameGame public static void main(String
args) ...
14Move on to Chapter 3
- Were done with Chapters 1 and 2
- Start reading Chapter 3
- And dont forget tocomplete Homework 1