Title: COP3252 Advanced Java Programming
1COP3252Advanced Java Programming
- 15-Jan-08
- Lecture Set 3
- Variables, Math Operators, printf, The Java API,
Strings, User Input,
2Variables in Java
- All variables have a name, type, size, and a
value. - JAVA is a STRONGLY TYPED language
- You must declare a variables type before it can
be used. - JAVA contains 8 primitive variable types
- Primitive predefined by the language and is
named by a reserved keyword. - Do not share state (values) with other primitive
values.
3Primitive Data Types cont.
- byte 8-bit signed twos compliment integer.
- Min value -128
- Max value 127
- Used when you wish to save memory when using
small values in large arrays - short 16-bit signed twos compliment integer.
- Min value -32,768
- Max value 32,767
- Also used to save memory
4Primitive Data Types cont.
- int 32-bit signed twos compliment integer
- Min value -2,147,483,648
- Max value 2,147,483,647
- Most used variable type. Can handle most
numerical values in your programs. - long 64-bit signed twos compliment integer
- Min value -9,223,372,036,854,775,808
- Max value 9,223,372,036,854,775,807
- Used when the integer type is not big enough (low
level cryptographic functions may use this)
5Primitive Data Types cont.
- float double-precision 32-bit IEEE 754 floating
point number (a decimal value) - Min and Max values beyond the scope of this
class - Used to save memory when making large arrays of
decimal numbers - NOT SUITABLE FOR PRECISE CALCULATIONS (such as
currency) - double double-precision 64-bit IEEE 754
floating point number (a decimal value) - Min and Max values beyond the scope of this
class - Also should not be used for precise calculations
- Note Currency calculations should be done with
java.math.BigDecimal (discussed in a later class)
6Primitive Data Types cont.
- boolean One of two possible values true and
false - Used for simple flags or tracking conditional
statements - Represents one single bit of information (but is
actually more than one bit in size) - char 16-bit storage container representing a
Unicode (computer recognized) character.
7Primitive Data Type Default Values
- When you declare a variable, you dont have to
assign a value (initialize the variable). - Example int a double temp
- When a variable is not initialized, the compiler
will assign it a default value. - It is bad form to create a variable without
assigning an initial value.
8Primitive Data Type Default Values cont.
9Variables Naming Conventions
- Rules and conventions for naming a variable
- Variable names are case sensitive !
- TeSt is not the same as test
- Variable names can have unlimited length
- ..but it is not usually wise to name a variable
thisIsTheLongestVariableNameICanPossiblyThinkOf - If it is one word all lowercase
- If it is multiple words capitalize the first
letter of each subsequent word (
thisIsAMultiWordVariable) - Constant values (discussed later) should be in
ALL CAPS with underscores separating the words
- (example final int GRAVITY_VALUE)
10Variables Naming Conventions
- Variable names may only begin with a letter, a
dollar sign, or an underscore - but it is considered bad form to start a
variable name with anything other than a letter - Variable names CAN NOT start with a number!
- int 123variable is not a valid variable name!
11Variables Naming Conventions
- It must not be one of Javas reserved keywords.
(See Appendix C of the book for a complete list) - It must not be a boolean literal true or
false - It must not be the reserved word null
12Variables Example Integers
- One of the first variable types we will use will
be the primitive integer - Integers are declared with the keyword int
- Example int aNumber 12
- The example creates an integer called aNumber
and assigns the value 12 to it.
13Variables Example Integers
- You can change the value of a variable at any
time. - Example
- //Create an integer called number with value 5
- int number 5
- //Change the value of number to 10
- number 10
14Variables Example Integers
- Note After creating the variable, you simple
refer to it by name (no need to use the type and
name!) - Incorrect
- //Create an integer called number with value 5
- int number 5
- //Change the value of number to 10
- int number 10
- Correct
- //Create an integer called number with value 5
- int number 5
- //Change the value of number to 10
- number 10
15Variables Example Integers
- You can create multiple variables of the same
type on one line. - Example
- //Create several integers
- //Some will be assigned values, others will not
- int a, b10, c, d, e100
16Variables Example Integers
- You can assign one variable to be the value of
another variable - Example
- //Create two integers
- int a 100, b 200
- //Change the value of b to the value of a
- b a
- //The value of b is now 100
17Printing Variables
- We use the standard System.out statements to
print the values of our variables to the screen. - Example
- //Create an int called num and give it the value
5 - int num 5
- //Print the value of num to the screen
- System.out.println(num)
18Printing Variables
- We can print both text and the value of a
variable in the same print statement. - You separate your strings and your variables with
the plus () sign. This is a shorthand for String
concatenation. - You can have any combination of strings and
variables in a print statement.
19Printing Variables
- //Create an int
- int num 6
- //Print the value with text
- System.out.print(The value of num is num
.) - The above code would print the following to the
screen - The value of num is 6.
20Math Operators
- The following are a collection of common
arithmetic operators - Addition
- Subtraction -
- Multiplication
- Division /
- Remainder (mod division)
21Math and Variables
- You can perform math on all numerical primitive
variable types (int, long, double, etc.) - You can use parenthesis to separate operations
and determine order of precedence.
22Math Examples
- //Create some ints
- int a 5, b 5
- //create another int that is a b
- int c a b
- //Add 10 more to c
- c c 10
- //The value of c at the end of execution is 20.
23Math Operators - Examples
- See VariableAndMathExamples.java for examples of
creating and modifying variables, printing
variables, and arithmetic operations.
24Alternative Print Statements
- As of release 1.5, Java includes the classic
printf style of statement - The printf statement is Java is used exactly as
it is used in the C programming language. - All examples in class will use print and println
you will rarely see printf used in this class. - However, the book tends to make use of it
- If you would like to learn about Javas printf
statement, see - Page 45 of the 6th edition book, and chapter 28
- Page 48 of the 7th edition book, and chapter 29
25Formatting with printf(6th chap 28, 7th chap
29)
- Some format specifiers for the printf command
(all preceded by a sign) - (others will be discussed on Thursday)
26The JAVA API
- Many things you may want to do in your program
have already been written for you - API Application Programming Interface
- Used to describe how computer applications and
software developers can access sets of
pre-written functions without requiring access to
the source code of the functions or the library
(or without requiring a detailed understanding of
the functions internal workings). - Reference http//en.wikipedia.org/wiki/Applicati
on_programming_interface
27The JAVA API Cont.
- The primary JAVA API is maintained by Sun
MicroSystems - There are APIs for all JAVA versions (J2SE, J2EE,
J2ME) - Standard edition, enterprise edition, and mobile
edition - We are learning the Standard Edition, so you will
use the following API - http//java.sun.com/j2se/1.5.0/docs/api/
28The JAVA API Cont.
- The JAVA API will be used extensively in this
class - Not everything on the API may make sense at this
point in the class but you should be able to
use every available class in the API by the end
of this course.
29The String Variable
- Used to represent strings of characters
- Strings are objects created from the String class
(they are not a primitive variable type). - Since strings are a commonly used variable type,
JAVA has implemented some ways to make working
with Strings a little more like working with
primitives
30Creating a String
- Strings are delimited by a set of double quotes.
- Two ways to create a basic String
- //The primitive way
- String aString This is a string
- //The object or constructor way
- String bString new String(This is a string)
31Creating a String
- The String API http//java.sun.com/j2se/1.5.0/do
cs/api/java/lang/String.html - Contains the constructors, methods, etc. for the
object type String
32Using the String Constructors
- //Create a new string with a NULL value
- String aString new String()
- //Create a new string and give it a value
- String bString new String(A String!)
- //Create a string from the previous string
- String cString new String(bString)
33String Example
34String Methods (Functions)
- The available String methods can be found in the
API - String has built in methods for concatenation,
case switching, find the length, pulling out a
specific character, etc - These will be discussed in a later class
35User Input
- User input allows for interactive programs
- Most programs we will write will include at least
some section requiring user input - Input from a command line is simple in most
languages - scanf (C programming)
- cin ltlt (C programming)
36User Input
- Slightly more difficult in JAVA
- Two classes we can use to get user input from the
command line - BufferedReader
- Older method but the one I will use most often
in demonstrations - Scanner
- Newer method slightly easier to work with
37BufferedReader
- Link to API http//java.sun.com/j2se/1.5.0/docs/
api/java/io/BufferedReader.html - Reads text from a character-input stream (such as
the command line) and buffers characters as to
provide for efficient reading.
38User Input
- Using BufferedReaders
- //Create a BufferedReader named br
- BufferedReader br new BufferedReader(new
InputStreamReader(System.in)) - //Read in a single line from the user and store
it - String input br.readLine()
- //Read in another line from the user and store it
- //Note Dont need to declare the String type
again - input br.readLine()
39Importing Classes
- BufferedReader is part of the java.io. package
(see API) - JAVA does not automatically load all class
libraries on its own - We have to import this class into our programs.
- Import statements must be the very first line of
actual code in any program we write (put it
anywhere else and it will not work) - You can have comments before the statement ----
but the import statement must be at the top of
your .java file before any class or method
declaration.
40Importing
- We generally import all classes in a package
- Without the import statement, we would not be
able to use the classes that we find in the Java
API. - To import java.ios classes (which includes
BufferedReader) we would type - import java.io.
41Buffered Reader Exceptions
- All objects that deal with input and output have
the ability to throw an exception ( cause an
error) - When dealing with BufferedReader, we have to tell
JAVA that our main program has the ability to
throw an exception - This is done by adding throws Exception to the
end of the main method declaration - public static void main (String args) throws
Exception - We must do this in order for the code to properly
compile when using the BufferedReader - We will talk much much more about exceptions in a
later class --- for now we just need to know that
the throws Exception statement must be present
when working with BufferedReader.
42Example
- Using a BufferedReader for user input
- Importing the java.io class and subclasses
- Exception Throwing (will be discussed fully later
in the semester) - See UserInput.java example
43BufferedReader Converting Input
- The BufferedReader only reads in input as a
string - Even if the user types 12345 it is still
stored as a string - It is often necessary to convert the string to
other variable types (such as an integer) - There are functions available in JAVA to convert
variable types.
44Converting a String to an int
- A common conversion is from String to a primitive
integer. - We use the Integer class (object form of the
primitive int) to convert the string. - See Integer in API http//java.sun.com/j2se/1.5.
0/docs/api/java/lang/Integer.html
45Converting a String to an int
- We use the parseInt function of Integer.
- This function takes in a String and returns an
int. - Example
- String numbers 123456
- int a Integer.parseInt(numbers)
46Scanner
- Alternative to BufferedReader
- Available as of JAVA 1.5 (not in JAVA 1.4.2 or
earlier) - API Link http//java.sun.com/j2se/1.5.0/docs/api
/java/util/Scanner.html
47Scanner
- Scanner is contained in java.util.Scanner
- You will have to import that class if you wish to
use Scanner. - import java.util.Scanner
48Scanner
- You must first create a Scanner to obtain input
from command window. - This is done with the following command
- //Create a scanner object
- Scanner input new Scanner(System.in)
49Scanner
- Next, you must tell the scanner to read in from
the command line. The following line of code
tells the scanner that it should read from the
command line and parse it as an integer. - int num1 input.nextInt()
50Scanner Example
- import java.util.Scanner
- //Class and main declarations
- //Create the scanner
- Scanner input new Scanner( System.in )
- //Prompt user for input
- System.out.print(Enter digit )
- //Read input as an integer
- int num1 input.nextInt()
51Scanner Exceptions
- With Scanner, you do not need to throw any
Exceptions as you do with Buffered Readers. In
other words, you do not need the throws
Exception after declaring main. - Scanner does still throw exceptions (discussed
later)
52Scanner and Strings
- You have already see how to read in a String
using the BufferedReader - String input br.readLine()
- The above says to create a String variable called
input and place the input from the Buffered
Reader into it.
53Scanner Strings
- To grab a String using Scanner, just use the
following - Scanner input new Scanner(System.in)
- String name input.nextLine()
54Scanner Example
55On Thursday
- Shortcut operators
- Precedence
- prefix and postfix
- The Math Class
- Type conversions and casting
- Formatting with printf
- Control Structures
- Introduction to classes and objects