220 likes | 339 Views
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.
E N D
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 • 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
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’ ‘\’’
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
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”;
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); } }
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)
Assignment Operators int c = 3, d = 5, e = 4, f = 6, g = 12;
Casting • Automatic promotion works in Java, but not demotion…need explicit cast to demote: • double d = 3.2; • int I = (int)d; • int j = 4; • d = j; double e = (double)i/(double)j;
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
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 switchstatement • Identical to C++ switch statement
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
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 aFile object to read from a text file…more on this later.
Keyboard input with Scanner • Instantiate a Scanner Scanner myScanner = new Scanner(System.in); • Read an entire line of text String input = myScanner.nextLine(); • Read an individual token, i.e., int int i = scanner.nextInt(); • What if next input isn’t an int?
Scanner Example import 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); } }
Scanner Example import 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); } }
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 it or • Read the input and handle the resulting error
Look Ahead • 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… if (myScanner.hasNextInt()) { age = myScanner.nextInt(); } else { age = 30; String junk = myScanner.next(); }
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 InputMismatchExceptionis part of the java.util library so we must import java.util.InputMismatchException or java.util.* in order to catch the exception.