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

Similar documents
AP Computer Science Static Methods, Strings, User Input

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Sample CSE8A midterm Multiple Choice (circle one)

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Chapter 3. Input and output. 3.1 The System class

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Introduction to Programming

Install Java Development Kit (JDK) 1.8

J a v a Quiz (Unit 3, Test 0 Practice)

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Chapter 2: Elements of Java

Introduction to Java

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Introduction to Java. CS 3: Computer Programming in Java

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

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

CS 106 Introduction to Computer Science I

Some Scanner Class Methods

Java Basics: Data Types, Variables, and Loops

Variables, Constants, and Data Types

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

CS106A, Stanford Handout #38. Strings and Chars

Object-Oriented Programming in Java

Chapter 2 Introduction to Java programming

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

AP Computer Science Java Mr. Clausen Program 9A, 9B

Java CPD (I) Frans Coenen Department of Computer Science

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

Building Java Programs

Using Files as Input/Output in Java 5.0 Applications

Chapter 1 Java Program Design and Development

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Lecture 5: Java Fundamentals III

6.1. Example: A Tip Calculator 6-1

ECE 122. Engineering Problem Solving with Java

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

D06 PROGRAMMING with JAVA

LOOPS CHAPTER CHAPTER GOALS

Comp 248 Introduction to Programming

Part I. Multiple Choice Questions (2 points each):

Building Java Programs

Chapter 2 Elementary Programming

LAB4 Making Classes and Objects

Introduction to Python

Introduction to Python

Computer Programming I

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

VB.NET Programming Fundamentals

Lecture 1 Introduction to Java

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Pemrograman Dasar. Basic Elements Of Java

Java Crash Course Part I

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

Informatica e Sistemi in Tempo Reale

Programmierpraktikum

Carron Shankland. Content. String manipula3on in Java The use of files in Java The use of the command line arguments References:

AP Computer Science Java Subset

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

Programming in Java Course Technology, a part of Cengage Learning.

Outline Basic concepts of Python language

Week 1: Review of Java Programming Basics

1 Introduction. 2 An Interpreter. 2.1 Handling Source Code

Exercise 1: Python Language Basics

Python Lists and Loops

Topic 11 Scanner object, conditional execution

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Chapter One Introduction to Programming

Programming Fundamentals I CS 110, Central Washington University. November 2015

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Software Engineering Techniques

Unit 6. Loop statements

Programming Languages CIS 443

Moving from CS 61A Scheme to CS 61B Java

Programming and Data Structures with Java and JUnit. Rick Mercer

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Sources: On the Web: Slides will be available on:

While and Do-While Loops Summer 2010 Margaret Reid-Miller

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Programming in Java. What is in This Chapter? Chapter 1

Introduction to Java Lecture Notes. Ryan Dougherty

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

JAVA ARRAY EXAMPLE PDF

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

In this Chapter you ll learn:

The following program is aiming to extract from a simple text file an analysis of the content such as:

Chapter 2 Basics of Scanning and Conventional Programming in Java

Chapter 8. Living with Java. 8.1 Standard Output

Understanding class definitions

Arrays. Introduction. Chapter 7

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 EggBasket { public static void main(string[] args) { int numberofbaskets, eggsperbasket, totaleggs; Scanner keyboard = new Scanner(System.in); System.out.print( "Enter the number of eggs in each basket: "); eggsperbasket = keyboard.nextint(); System.out.print("Enter the number of baskets: "); numberofbaskets = keyboard.nextint(); 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, eggsperbasket, totaleggs; This is a declaration of three integer variables A variable is a named location to store data, i.e., a container for data 4

type What Is a Program Variable? int numberofbaskets, eggsperbasket, totaleggs; This is a declaration of three integer variables variable names 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 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? eggsperbasket = keyboard.nextint(); 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.nextint() Expressions can also be the result of evaluating something known as a function The above is an example of this 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 an integer value: int i = in.nextint(); Declare and input a real value: double x = in.nextdouble(); Declare and input a whole line (a string of characters): String s = in.nextline(); Input of a single character with the Scanner class is trickier; we ll see it later. 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? 16 25

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 26

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 27

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 28

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 29

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! 30

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 Scanner does NOT provide a way to get a single character of input. 31

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\""); 32

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); } } 33

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

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 35

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 36

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 37

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. 38

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

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 40

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! 41

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) 42

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 43

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! 44