Lecture 3 Java Basics Lecture3.ppt.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
Introduction to Programming with Java, for Beginners Primitive Types Expressions Statements Variables Strings.
Shlomo Hershkop1 Introduction to java Class 1 Fall 2003 Shlomo Hershkop.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
Some basic I/O.
Java Intro. Strings “This is a string.” –Enclosed in double quotes “This is “ + “another “ + “string” –+ concatenates strings “This is “ “ string”
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
CS 225 Java Review. Java Applications A java application consists of one or more classes –Each class is in a separate file –Use the main class to start.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Strings as objects Strings are objects. Each String is an instance of the class String They can be constructed thus: String s = new String("Hi mom!");
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
1 Course Lectures Available on line:
Conditional If Week 3. Lecture outcomes Boolean operators – == (equal ) – OR (||) – AND (&&) If statements User input vs command line arguments.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Java ProgrammingtMyn1 Java Programming Timo Mynttinen Mikkeli University of Applied Sciences.
JAVA Tokens. Introduction A token is an individual element in a program. More than one token can appear in a single line separated by white spaces.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 2 Basic Elements of Java.
F27SA1 Software Development 1 3. Java Programming 2 Greg Michaelson.
CompSci 100E 2.1 Java Basics - Expressions  Literals  A literal is a constant value also called a self-defining term  Possibilities: o Object: null,
1 Programming Java Java Basics. 2 Java Program Java Application Program Application Program written in general programming language Applet Program running.
Basic Java Syntax COMP 401, Spring 2014 Lecture 2 1/14/2014.
Apr, 2011 Dating with Java Larry Li. Objective Hello world program Setup development environment Data types and variables Operators and Expressions Control.
CSCI 3328 Object Oriented Programming in C# Chapter 4: C# Control Statement – Part I 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX.
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
1 Lecture 5 More Programming Constructs Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
A Sample Program public class Hello { public static void main(String[] args) { System.out.println( " Hello, world! " ); }
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Object Oriented Programming Lecture 2: BallWorld.
Introduction to programming in java
M105 - Week 2 Chapter 3 Numerical Data 1 Prepared by: M105 Team - AOU - SAB.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
CompSci 230 S Programming Techniques
Key Words / Reserved Words
CIS3931 – Intro to JAVA Lecture Note Set 2 17-May-05.
Programming in Java Sachin Malhotra, Chairperson, PGDM-IT, IMS Ghaziabad Saurabh Chaudhary, Dean, Academics, IMS Ghaziabad.
Yanal Alahmad Java Workshop Yanal Alahmad
Control Statements: Part 2
Chapter 3 Assignment Statement
User input We’ve seen how to use the standard output buffer
Java Programming: From Problem Analysis to Program Design, 4e
SELECTION STATEMENTS (1)
Introduction to Programming in Java
CET 3640 – Lecture 2 Java Syntax Chapters 2, 4, 5
Starting JavaProgramming
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Chapter 2: Basic Elements of Java
MSIS 655 Advanced Business Applications Programming
Java Tokens & Data types
IFS410 Advanced Analysis and Design
elementary programming
Primitive Types and Expressions
Presentation transcript:

Lecture 3 Java Basics Lecture3.ppt

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 ** http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html Lecture3.ppt

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

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

Literals boolean int long float double char 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 (“) 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

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”; http://java.sun.com/j2se/1.5.0/docs/api/ 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); } What happened to the String “Java is hot!” 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; int I = (int)d; int j = 4; d = j; double e = (double)i/(double)j; Code demonstration 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 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

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

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

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

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

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