CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Similar documents
CSE 1223: Introduction to Computer Programming in Java Chapter 1 Computer Basics

Basic Computation. Chapter 2

Basic Computation. Chapter 2

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Full file at

Objectives. Primitive Types, Strings, and Console I/O. Variables and Values. Outline. Naming and Declaring Variables. Variables and Values

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Introduction to Computer Programming

Chapter 2: Data and Expressions

Oct Decision Structures cont d

Chapter 2 Part 2 Edited by JJ Shepherd, James O Reilly

CIS 110: Introduction to Computer Programming

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Chapter 2: Data and Expressions

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

double float char In a method: final typename variablename = expression ;

A variable is a name for a location in memory A variable must be declared

Introduction to Software Development (ISD) David Weston and Igor Razgon

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Hello World. n Variables store information. n You can think of them like boxes. n They hold values. n The value of a variable is its current contents

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

FUNDAMENTAL DATA TYPES

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

Example Program. public class ComputeArea {

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

2.8. Decision Making: Equality and Relational Operators

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

Faculty of Science Midterm. COMP-202B - Introduction to Computing I (Winter 2008)

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

2/9/2012. Chapter Four: Fundamental Data Types. Chapter Goals

Using Java Classes Fall 2018 Margaret Reid-Miller

Program Fundamentals

STUDENT LESSON A10 The String Class

when you call the method, you do not have to know exactly what those instructions are, or even how the object is organized internally

Starting Out with Java: From Control Structures through Data Structures 3e (Gaddis and Muganda) Chapter 2 Java Fundamentals

CMPT 125: Lecture 3 Data and Expressions

Lecture Set 2: Starting Java

What did we talk about last time? Examples switch statements

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

MODULE 02: BASIC COMPUTATION IN JAVA

Lecture Set 2: Starting Java

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

Gaddis: Starting Out with Java: From Control Structures through Objects, 6/e

Java Basic Programming Constructs

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

CEN 414 Java Programming

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Section 2: Introduction to Java. Historical note

Chapter 5 Lab Methods

Introduction to Java Applications

More on variables and methods

Selected Questions from by Nageshwara Rao

DATA TYPES AND EXPRESSIONS

Object-Oriented Programming

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

We now start exploring some key elements of the Java programming language and ways of performing I/O

Chapter 2: Programming Concepts

COMP 110 Project 1 Programming Project Warm-Up Exercise

Loops. CSE 114, Computer Science 1 Stony Brook University

Programming with Java

Building Java Programs

CS112 Lecture: Primitive Types, Operators, Strings

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Basic Computation. Chapter 2

First Java Program - Output to the Screen

McGill University School of Computer Science COMP-202A Introduction to Computing 1

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Primitive Data, Variables, and Expressions; Simple Conditional Execution

COMP String and Console I/O. Yi Hong May 18, 2015

CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Recap: Java Static Methods. Recap: Decomposition Example. Recap: Static Method Example

Full file at

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Building Java Programs

Building Java Programs

Zheng-Liang Lu Java Programming 45 / 79

appreciate the difference between a char and a string understand and use the String class methods

Chapter 3. Selections

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Chapter 2 Elementary Programming

Introduction to Java Applications; Input/Output and Operators

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

C: How to Program. Week /Mar/05

Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections

Course Outline. Introduction to java

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Introduction to C# Applications

Elementary Programming

Transcription:

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1

Recall From Last Time: Java Program import java.util.scanner; public class EggBasketEnhanced { public static void main(string[] args) { Scanner keyboard = new Scanner(System.in); System.out.print( "Enter the number of eggs in each basket: "); String eggsstr = keyboard.nextline(); int eggsperbasket = Integer.parseInt(eggsStr); System.out.print("Enter the number of baskets: "); String basketstr = keyboard.nextline(); int numberofbaskets = Integer.parseInt(basketStr); int totaleggs = numberofbaskets * eggsperbasket; } } System.out.println(eggsPerBasket + " eggs per basket."); System.out.println(numberOfBaskets + " baskets."); System.out.println("Total number of eggs is " + totaleggs); 2

What Does EggBasketEnhanced Do? Take a look at the program and see if you can figure out what it does. There are some things in here we haven t talked about yet. Can you guess what they re doing based on their names and how we re using them? 3

What Is a Program Variable? int numberofbaskets; This is a declaration of an integer variable A variable is a named location to store data, i.e., a container for data 4

type What Is a Program Variable? int numberofbaskets; This is a declaration of an integer variable variable name A variable is a named location to store data, i.e., a container for data Each variable can hold only one type of data; for example only integers, only floating point (real) numbers, or only characters All program variables must be declared with a type before being used 5

What Is a Program Type? A variable s type determines the kind of values that a variable can hold and what operations can be applied to it. Java has two different types primitive types and reference types We ll discuss reference types later Some Java primitive types: int (integer, whole values, e.g., 0, 1, -13, 231) double (real values, e.g., 0.0, 3.1415, -2.72) char (single character values, e.g., a, 3, $ ) boolean (only one of two values: true, false) 6

How Do We Assign/Change the Value of a Variable? String eggsstr = keyboard.nextline(); totaleggs = numberofbaskets * eggsperbasket; Assignment statement: variable = expression; Assigns the value of the expression on the right side of = to the variable on the left side It does not mean equal like in math! These expressions look different, but they re both doing the same thing! 7

What Is an Expression? numberofbaskets * eggsperbasket Program expressions are very much like arithmetic expressions you are familiar with (usual operators, parenthesis, precedence rules, etc.) Expressions can be evaluated to produce a value and they have a type (the type of the value of the expression) 8

What Is an Expression? keyboard.nextline() Integer.parseInt(eggStr) Expressions can also be the result of evaluating something known as a function The above are an examples of functions Program functions are very similar to mathematical functions Take inputs, produce outputs from those inputs Such as y = f(x) f(x) is a function where x is the input, f(x) is the output More on this later! 9

Numeric Operators Some common integer operators: + (obvious) - (obvious) * (obvious) / (integer division, e.g., 6/2=3, 5/2=2, 19/5=?) % (mod operator, i.e., remainder of integer division, e.g., 6%2=0, 5%2=1, 19%5=?) Some common real operators: +, -, *, / (real division) Note that real division is approximate Sometimes the results you get will be surprising! 10

Integer arithmetic For integers, it is important to understand the / and % operators / is integer division. It is not exactly the same as division for real numbers 4 / 2 = 2 But 5 / 2 = 2 also Rule is divide, then round closer to zero Not round down round toward zero So -5/2 = -2 11

Integer arithmetic For integers, it is important to understand the / and % operators % is integer remainder Works much like you might remember long division working when you were in grade school 5 % 2 = 1 Because 5/2=2 with 1 remaining 4 % 2 = 0 Because 4/2=2 with 0 remaining 19 % 5 = 4 Because 19/5 = 3 with 4 remaining etc. 12

Integer arithmetic For integers, it is important to understand the / and % operators / and % work together (x / y) * y + (x % y) = x 19 / 5 = 3 19 % 5 = 4 5 * 3 = 15 15 + 4 = 19 Use % to check whether a number is even or not 10 % 2 = 0 11 % 2 = 1 13

Some Expressions: What Are Their Values? int i = 12, j = 5, k = -3; double x = 2.1, y = -1.5, z = 3.0; (i + j + k) / 3 (i / j) * j + (i % j) x * x + y * y (x + y + z) / (x y z) 2.0 * z (x + y) 14

Output Statements System.out.println(output1 + output2 +... + outputn); System.out.print(output1 + output2 +... + outputn); Concatenates the various outputs (quoted strings, variables, constants/numbers) and prints them to the screen (println adds a newline). What do the following statements output? int day = 19; System.out.print("January " + day + ", " + 2004 + " is Martin Luther King s Day! "); 15

Input Statements Given the import: import java.util.scanner; and the declaration: Scanner in = new Scanner(System.in); Declare and input a whole line (a string of characters): String s = in.nextline(); You can convert input to integer or double values with special functions: int val = Integer.parseInt(s); double dval = Double.parseDouble(s); 16

To Sum Up... So far, we have seen how to input values from the keyboard how to output messages/values to the screen how to create variables to store values how to store values in variables and compute new values with expressions 17

It s Your Turn! Now let s put it all together: Write a Java program called ComputeArea, which asks the user for the width and height of a rectangle and computes and prints the area of the rectangle. 18

The char Type A variable of the char data type stores a single printable character A char constant or literal is a character in single quotes, e.g., y For example: char answer = y ; System.out.println(answer); prints (displays) the letter y 19

The String Type A string is a sequence of characters The String type is used to declare variables that store strings The String type is not a primitive type: it is known as a class or reference type A String constant is one or more characters in double quotes, e.g., string constant Examples: char charvariable = a ;//single quotes String stringvariable = "a";//double quotes String sentence = "Hello, world"; 20

String Variables Declare a String variable: String greeting; Assign a value to the variable: greeting = "Hello!"; Use the variable as a String argument in a method call: System.out.println(greeting); causes the string Hello! to be displayed on the screen 21

Indexing Characters Within a String The index of a character within a string is an integer starting at 0 for the first character and gives the position of the character For example: String str = This is a string"; T h i s i s a s t r i n g 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 22

Methods A method is an operation with a name and a list of arguments (possibly empty) A method can simply perform an action or it can return a value A call to a method that does not return a value is a statement, e.g, System.out.println( Hi there! ); A call to a method that returns a value is called a function and can be used as an expression, e.g., int i = keyboard.nextint(); 23

Some String Methods The String type has many methods that allow us to manipulate String values/variables For now, this is the main distinction between primitive types and reference types Variables of reference types have methods that can be invoked with the syntax below. Variables of primitive types do not! String methods are called/invoked with the following syntax: stringvar.methodname(arguments) 24

Some String Methods int length() returns the number of characters in the given string, e.g., String str = This is a string ; System.out.println(str.length()); What s the output? 25

Some String Methods int length() returns the number of characters in the given string, e.g., String str = This is a string ; System.out.println(str.length()); What s the output? 16 26

String Methods cont. char charat(int pos) returns the character at position pos in the given string, e.g., String str = This is a string ; System.out.println(str.charAt(0)); System.out.println(str.charAt(1)); System.out.println(str.charAt(15)); What s the output? 27

String Methods cont. char charat(int pos) returns the character at position pos in the given string, e.g., String str = This is a string ; System.out.println(str.charAt(0)); System.out.println(str.charAt(1)); System.out.println(str.charAt(15)); What s the output? T h g 28

Some String Methods cont. String substring(int start, int end) returns the string starting at position start and ending at position (end-1) in the given string, e.g., String str = This is a string ; System.out.println(str.substring(0,4)); System.out.println(str.substring(5,7)); System.out.println(str.substring(0,16)); What s the output? 29

Some String Methods cont. String substring(int start, int end) returns the string starting at position start and ending at position (end-1) in the given string, e.g., String str = This is a string ; System.out.println(str.substring(0,4)); System.out.println(str.substring(5,7)); System.out.println(str.substring(0,16)); What s the output? This is This is a string 30

Some String Methods cont. int indexof(string astring) returns the position of the first occurrence of string astring in the given string (or -1 if not found), e.g., String str = This is a string ; System.out.println(str.indexOf( This )); System.out.println(str.indexOf( is )); System.out.println(str.indexOf( yoh )); What s the output? 31

Some String Methods cont. int indexof(string astring) returns the position of the first occurrence of string astring in the given string (or -1 if not found), e.g., String str = This is a string ; System.out.println(str.indexOf( This )); System.out.println(str.indexOf( is )); System.out.println(str.indexOf( yoh )); What s the output? 0 2-1 32

Some String Methods cont. boolean equals(string astring) returns true if the string astring is the same as the given string, false otherwise, e.g., String str = test ; System.out.println(str.equals( test )); System.out.println(str.equals( fish )); System.out.println(str.equals( TEST )); What s the output? 33

Some String Methods cont. boolean equals(string astring) returns true if the string astring is the same as the given string, false otherwise, e.g., String str = test ; System.out.println(str.equals( test )); System.out.println(str.equals( fish )); System.out.println(str.equals( TEST )); What s the output? true false false 34

Concatenating (Appending) Strings As we have seen before the + operator can be used to concatenate string values, e.g., String name = Cindy ; String greeting = Hi, + name +! ; System.out.println(greeting); What is the output? 35

Concatenating (Appending) Strings As we have seen before the + operator can be used to concatenate string values, e.g., String name = Cindy ; String greeting = Hi, + name +! ; System.out.println(greeting); What is the output? Hi, Cindy! 36

Single Character Input Given the import: import java.util.scanner; and the declaration: Scanner in = new Scanner(System.in); Declare and input a single character: String s = in.nextline(); char c = s.charat(0); Note that input here is actually the whole line, we re just ignoring the rest of the line 37

Escape Characters How do you print the following string? The word "hard" Would this do it? System.out.println("The word "hard""); No, it would give a compiler error - it sees the string The word between the first set of double quotes and is confused by what comes after Use the backslash character, \, to escape the special meaning of the internal double quotes: System.out.println("The word \"hard\""); 38

String Program public class StringTest { public static void main(string[] args) { String greeting = "Hello!"; int len = greeting.length(); char ch = greeting.charat(3); String sub = greeting.substring(1, 3); int index1 = greeting.indexof("lo"); int index2 = greeting.indexof("low"); System.out.println( Length is: +len); System.out.println( Char at 3 is: +ch); System.out.println( Substring is: +sub); System.out.println( Index of \ lo\ is: +index1); System.out.println( Index of \ low\ is: +index2); } } 39

What Is The Output Of StringTest? Trace through the statements of StringTest and determine the output produced by the program. 40

Program Line String greeting = "Hello"; Program state greeting = Hello int len = greeting.length(); greeting = Hello len = 5 char ch = greeting.charat(3); greeting = Hello len = 5 ch = l String sub = greeting.substring(1, 3); greeting = Hello len = 5 ch = l sub = el 41

Program Line int index1 = greeting.indexof("lo"); int index2 = greeting.indexof("low"); Program state greeting = Hello len = 5 ch = l sub = el greeting = Hello len = 5 ch = l sub = el index1 = 3 greeting = Hello len = 5 ch = l sub = el index1 = 3 Index2 = -1 42

Program State Note how program variables are represented in the program state Program variables carry through until they fall out of scope scope describes where in the program the variable has a value More on this later For now, it s enough to realize that variables keep their values from one line to the next 43

Your Turn, Again! Write a Java program called BreakName, which asks the user for his/her name in the form First M. Last, and outputs First, M., and Last on three different lines. In other words, after the name is read from input, the program needs to break it up in the three pieces (First, M., and Last) and output those one line at a time. 44

BreakName import java.util.scanner; public class BreakName { public static void main(string[] args) { } } 45

Documentation and Style Program source code is primarily for human beings Remember the compiler is needed to turn source code (readable by humans) into object code (understandable to the machine) It is important to write program source in ways that make it readable for other programmers Code re-use is an important part of modern software development 46

Documentation and Style It is important to write program source in ways that make it readable for other programmers Programmers should use good style when writing their programs to make their code easier to read by other programmers Using a standard style for naming variables, formatting indentation and line breaks ( white space ) and other formatting issues improves the readability of code. Programmers should provide comments in their code to indicate what the code is supposed to be doing Always remember you can read source code to see what a program does, but that doesn t tell you what the programmer intended for the code to do. If the code is broken, the actual operation may differ dramatically from the intent! 47

Documentation and Style Use meaningful names for variables, programs, etc. Use indentation and line spacing as shown in the examples in the text Always include a comment that describes what the program is supposed to do at the top of the program file This comment should also include the name of the programmer who wrote the program Use all lower case for variables, except capitalize internal words (eggsperbasket) 48

Comments Comment text in a program that the compiler ignores Does not change what the program does, only explains the program Write meaningful and useful comments Comment the non-obvious Assume a reasonably knowledgeable reader // for single-line comments /* */ for multi-line comments 49

Documentation and Style Pay attention to your programming style and commenting practices! Full credit on assignments can only be earned by programs that practice good style and are well documented! 50