Upload
lel
View
28
Download
0
Embed Size (px)
DESCRIPTION
Lecture 3 Java Basics. Keywords. ** http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html. Identifiers. Can’t be keywords Case-sensitive Begin with and consist of: Letters (a... Z) Numbers (0…9) Underscore (_) Dollar sign ($). Same as C++. Primitive Types. - PowerPoint PPT Presentation
Citation preview
Lecture3.ppt
Lecture 3Java Basics
Lecture3.ppt
Keywordsabstract continue for new switch
assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while
** http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html
Lecture3.ppt
Identifiers
• Can’t be keywords• Case-sensitive• Begin with and consist of:
– Letters (a... Z)– Numbers (0…9)– Underscore (_)– Dollar sign ($)
Same as C++
Lecture3.ppt
Primitive Types
• boolean 8 bits• char 16 bits • byte 8 bits • short 16 bits • int 32 bits • long 64 bits• float 32 bits • double 64 bits
Guaranteed to occupy same number of bits regardless of platform
boolean – zero and non-zero DO NOT equate to true/false respectively
Lecture3.ppt
Literals• boolean
– true or false– zero and non-zero do NOT equate to true/false
• int– 14 796 2147361
• long– ends with “L”
• 65L 23412396432L
• float– ends with “f” or “F”
• 6.23f 5.96F 1e-32f
• double– 2.0146e123 3.1415926
• char– Contained in single quotes
• ‘b’ ‘&’ ‘*’– Escape sequences (similar to c++)
• ‘\”’ ‘\n’ ‘\t’ ‘\’’
Lecture3.ppt
String Literals
• Enclosed in double quotes (“)– “USNA” “This is a string literal” “A”
• Concatenating Strings– “United” + “ States” + “ Naval” + “ Academy”
• Like C++, String is class not a primitive data type
Lecture3.ppt
Strings
• Java defines the String class to handle strings• A String is a collection of characters treated as a single unit• It is not an array of char variables• Multiple String constructors
String s1 = new String(“Hello World”);String s2 = “Hello World”;
Lecture3.ppt
String Example
public class Strings { public static void main (String[] args) { String m = "was a Roman"; String c = "Cicero " + m; System.out.println(c); String s = "Java is hot!"; s = 'L' + s.substring(1); System.out.println(s); }}
Lecture3.ppt
Basic Operators• Arithmetic Operations in Java
– Addition, subtraction, multiplication, division, modulus: (+, -, *, /, %)• Equality and Relational Operators
– Equality, not equals, greater than, greater than or equal, less than, less than or equal: (==, !=, >, >=, <, <=)
• Logical Operators– Binary operators
• logical AND: && (two boolean operands w/ short circuit)• logical AND: & (two boolean operands no short circuit)• bitwise AND: & (two integer operands)• logical OR: || (two boolean operands w/ short circuit)• logical OR: | (two boolean operands no short circuit)• bitwise OR: | (two integer operands)• logical exclusive OR: ^ (two boolean operands)• bitwise exclusive OR: ^ (two integer operands)
• Unary operator• logical NOT: ! (single boolean operand)• bitwise NOT: ~ (single integer operand)
Lecture3.ppt
Assignment Operators
+= c += 7 c = c + 7 10 to c
-= d -=4 d = d – 4 1 to d
*= e *= 5 e = e * 5 20 to e
/= f /= 3 f = f / 3 2 to f
%= g %= 9 g = g % 9 3 to g
int c = 3, d = 5, e = 4, f = 6, g = 12;
Lecture3.ppt
Increment and Decrement Operators
++ preincrement ++a Increment a by 1 then use the new value
++ postincrement a++ Use the current value of a then increment by 1
-- predecrement --b Decrement b by 1 then use the new value
-- postdecrement b-- Use the current value of b then decrement by 1
Lecture3.ppt
Casting
• Automatic promotion works in Java, but not demotion…need explicit cast to demote:
double d = 3.2;
double e = (double)i/(double)j;d = j; int j = 4;
int I = (int)d;
Lecture3.ppt
Control Structures
• Sequential execution is the default (like C++)• Control structures can be used to alter this sequential flow of execution
(same as C++)– Selection structures – if/switch statements– Repetition structures – while/for/do-while statements
Lecture3.ppt
Selection Structures• Generally the same as C++• The if selection structure
– Only difference with C++ is that the condition must be a Boolean expression evaluating to true or false
– Zero/non-zero can NOT be used for Java conditions– The following is illegal
int flag = 10;if (flag) { //illegal condition System.out.println("Flag was non-zero");}
• The if/else selection structure– Same as C++ with the above restriction on the condition portion
• The conditional operator (?:)– Same as C++, but must be a Boolean expression System.out.println(grade >= 60 ? "Passed" : "Failed");
• The switch statement– Identical to C++ switch statement
Lecture3.ppt
Repetition Structures
• The while repetition structure– Same as C++ with similar restriction to if statement regarding the condition
portion (i.e. must evaluate to either true or false)• The do/while structure
– Same as C++, but condition must be a true or false expression• The break and continue Statements
– Same basic meaning as C++– break
• Can only occur within the body of a loop, or a switch statement• Execution exits the innermost enclosing loop or switch block and continues with the
next statement following the block– continue
• Can only occur within the body of a loop• Terminates the current iteration of the loop without exiting the loop body
Lecture3.ppt
Console I/O• Three standard streams in Java included as part of java.lang
– System.in – InputStream defaults from the keyboard– System.out – PrintStream defaults to the screen– System.err – PrintStream defaults to the screen
• Scanner– A simple text scanner which can parse primitive types and strings– A Scanner breaks its input into tokens using a delimiter pattern, which by
default matches whitespace– The resulting tokens may then be converted into values of different types
using the various next methods– Resides in the java.util package
• Wrap a Scanner around an InputStream, i.e., System.in to read console input (keyboard) by Scanner input = new Scanner(System.in);
• A Scanner can also be wrapped around a File object to read from a text file…more on this later.
Lecture3.ppt
Keyboard input with Scanner
• Instantiate a ScannerScanner myScanner = new Scanner(System.in);
• Read an entire line of textString input = myScanner.nextLine();
• Read an individual token, i.e., intint i = scanner.nextInt();
• What if next input isn’t an int?
Lecture3.ppt
Scanner Exampleimport java.util.*;public class ScannerDemo { public static void main(String[] args) { int age; String name; Scanner myScanner = new Scanner(System.in); System.out.println("Enter first and last name: "); name = myScanner.nextLine(); System.out.println("How old are you? "); age = myScanner.nextInt(); System.out.println(name + '\t' + age); }}
Lecture3.ppt
Scanner Exampleimport java.util.*;public class ScannerDemo { public static void main(String[] args) { int age; String first; String last; Scanner myScanner = new Scanner(System.in); System.out.println("Enter first and last name: "); first = myScanner.next(); last = myScanner.next(); System.out.println("How old are you? "); age = myScanner.nextInt(); System.out.println(last +", " + first + '\t' + age); }}
Lecture3.ppt
Input Errors
• What happens if the user doesn’t enter an integer when asked for the age?
• There are a couple of ways to handle it– Look ahead to see if the user entered an integer before we read itor– Read the input and handle the resulting error
Lecture3.ppt
Look Ahead
if (myScanner.hasNextInt()) { age = myScanner.nextInt(); } else { age = 30; String junk = myScanner.next(); }
• Scanner provide the ability to look at the next token in the input stream before we actually read it into our program– hasNextInt()– hasNextDouble()– hasNext()– etc…
Lecture3.ppt
Input Exceptions (errors)
• What happens when we try to read an integer (myScanner.nextInt()) and the user enters something different?
• Java “throws” and exception, i.e., issues and error message.• We can “catch” the errors and handle them, thereby preventing the program from
crashing
try{ age = myScanner.nextInt();}catch(InputMismatchException e){ age = 30;}
The InputMismatchException is part of the java.util library so we must import java.util.InputMismatchException or java.util.* in order to catch the exception.