Download presentation
1
Lecture 3 Java Basics Lecture3.ppt
2
Keywords abstract 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 ** Lecture3.ppt
3
Identifiers Same as C++ 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
4
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 unicode.org Lecture3.ppt
5
Literals boolean int long float double char true or false
zero and non-zero do NOT equate to true/false int long ends with “L” 65L L float ends with “f” or “F” 6.23f F 1e-32f double 2.0146e char Contained in single quotes ‘b’ ‘&’ ‘*’ Escape sequences (similar to c++) ‘\”’ ‘\n’ ‘\t’ ‘\’’ Lecture3.ppt
6
String Literals Enclosed in double quotes (“) Concatenating Strings
“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
7
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
8
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); } What happened to the String “Java is hot!” Lecture3.ppt
9
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
10
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
11
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
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; Code demonstration Lecture3.ppt
13
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
14
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
15
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
16
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
17
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? Draw a scanner using a keyboard. Lecture3.ppt
18
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); } Run with basic code * Don’t open more than one Scanner with System.in as it’s inputStream…will cause problems Lecture3.ppt
19
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); } Change nextLine() to next() Lecture3.ppt
20
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 Show error if age not entered as an int (double or string) Lecture3.ppt
21
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(); Lecture3.ppt
22
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; Show error in java docs!! 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. Lecture3.ppt
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.