Lecture Set 2: Starting Java

Similar documents
Lecture Set 2: Starting Java

CMSC131. Introduction to your Introduction to Java. Why Java?

Full file at

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

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

Chapter 2 Elementary Programming

Section 2: Introduction to Java. Historical note

COMP 202 Java in one week

Chapter 2 ELEMENTARY PROGRAMMING

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

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

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

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

Elementary Programming

Chapter 2 Primitive Data Types and Operations. Objectives

Programming with Java

Full file at

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Introduction to Java Applications; Input/Output and Operators

Chapter 2: Data and Expressions

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

Primitive Data Types: Intro

B.V. Patel Institute of BMC & IT, UTU 2014

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

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

Chapter 2 Primitive Data Types and Operations

Chapter 2: Data and Expressions

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

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

Introduction to Java Applications

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

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

Computational Expression

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Program Fundamentals

Visual C# Instructor s Manual Table of Contents

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Getting started with Java

Computer Components. Software{ User Programs. Operating System. Hardware

Course Outline. Introduction to java

4 Programming Fundamentals. Introduction to Programming 1 1

Programming Language Basics

COMP 202 Java in one week

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

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

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

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Using Java Classes Fall 2018 Margaret Reid-Miller

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

CHAPTER 2 Java Fundamentals

A Quick and Dirty Overview of Java and. Java Programming

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

AP Computer Science A

IT 374 C# and Applications/ IT695 C# Data Structures

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

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Important Java terminology

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

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

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

CIS 110: Introduction to Computer Programming

Java Identifiers. Java Language Essentials. Java Keywords. Java Applications have Class. Slide Set 2: Java Essentials. Copyright 2012 R.M.

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Chapter 2: Using Data

Computer Components. Software{ User Programs. Operating System. Hardware

CS313D: ADVANCED PROGRAMMING LANGUAGE

Basic Computation. Chapter 2

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Pace University. Fundamental Concepts of CS121 1

Chapter 2 Elementary Programming

Introduction to Java & Fundamental Data Types

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

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

Section 2.2 Your First Program in Java: Printing a Line of Text

Program Elements -- Introduction

Java Bytecode (binary file)

Chapter 2. Elementary Programming

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

CS 106 Introduction to Computer Science I

Basics of Java Programming

Motivations 9/14/2010. Introducing Programming with an Example. Chapter 2 Elementary Programming. Objectives

CEN 414 Java Programming

Chapter 02: Using Data

Chapter 2: Introduction to C++

ing execution. That way, new results can be computed each time the Class The Scanner

4. Inputting data or messages to a function is called passing data to the function.

What did we talk about last time? Examples switch statements

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

LECTURE 02 INTRODUCTION TO C++

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

COMP Primitive and Class Types. Yi Hong May 14, 2015

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Chapter. Let's explore some other fundamental programming concepts

Transcription:

Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural Programming using Java Why Java? Popular modern language Used in web, business, telecom applications Developed in 1990s, incorporates many features from earlier languages Object-orientation Garbage collection Portability of object code 1 Portability of Object Code? Object code is 2GL (assembly) / 1GL (machine code) Last time we said that 2GL / 1GL is architecture-specific How can Java have portable object code? Answer: Java Virtual Machine (JVM) 2 1

Java Virtual Machine Java includes definition of Java bytecode = fake machine code for Java Java compilers produce Java bytecode To run Java bytecode, must have bytecode interpreter ( Java Virtual Machine ) on client machine source code object code JVM client.java Java compiler.class JVM client 3 Facts about JVMs For efficiency, JVMs often compile bytecode into native machine code There are also native Java compilers (these compile Java directly to machine code) 4 Method Headers main is a method = operation Operations require operands = data to work on Operations return new data (result) Header gives information on form of operands, result for methods For main: Operand is collection of Strings Result is void (= unimportant) More later on public, static Every program must have exactly one main method (where execution begins) 5 2

Output and Comments Output to console System.out.println System.out.print String Literals always use quotation marks Comments: explanations added by programmer ignored by the compiler read by other people looking at the code Two styles /* */ // to end of line Comments are essential for good programming! 6 Objects Bundles of data ( instance variables ) and methods ( functions ) Created using classes as templates We ll learn more later this semester 7 Java Program Organization Class Structure around which all Java programs are based A typical Java program consists of many classes Each class resides in its own file, whose name is based on the class s name The class is delimited by curly braces { }. File name: Example1a.java: public class Example1a { (contents of the class go here) } A class consist of data (variables) and operations (methods) 8 3

Holding and calculating values variables declaration initialization assignment value use mathematical expressions calculated to take on a value based on values of literals and variables 9 Java Program Organization Methods Where most computation takes place Each method has a name, a list of arguments enclosed in ( ), and body (collection of statements) in { } public static void main( String[ ] args ) { (contents of the main method go here) } Variables Storage locations that program can operate on Variables can store data of different forms (integers, for example) int secondsperminute = 60; int minutesperlecture = 50; 10 Java Program Organization Statements: Many different types Declarations specify variable types (and optionally initialize) int x, y, z; // three integer variables String s = Howdy ; // a character string variable boolean isvalid = true; // a boolean (true/false) variable Assignments assign variables new values x = 13; Method invocation call other methods System.out.println( Print this message ); Control flow determine the order of statement execution. (These include if-then-else, while, do-while, for. More later.) Built-in Operators: For manipulating values (+, -, *, /, etc.) i.e. String Concatenation for output 11 4

Built-in (Primitive) Types Integers Reals Other Type name Size (bytes) byte 1 short 2 int 4 long 8 float 4 double 8 char 2 boolean 1 Jan Plane and Ben Bederson (adapted from Bonnie Dorr) 12 String Type Elements of String type are sequences of characters abc Call me Ishmael etc. String type is not built-in We will use it a lot Useful operation: concatenation (+) abc + def is equivalent to abcdef 13 Writing Programs in Java 1. EXPRESSIONS: computations that carry a value 2. OPERATORS: symbols like +, *, -, etc. 3. Statements end with a semicolon 4. Types of statements: a) DECLARATION (where a variable is created) b) ASSIGNMENT (where a variable is given a value) c) METHOD INVOCATIONS (where another method is called) d) others - later 5. You can put blank lines in almost anytime you want 1. except not in the middle of an identifier or a keyword 2. and except not in a set of quotation marks 6. Proper indenting helps readability 14 5

Variables are named storage locations Variable x 5 Value Recall that memory is a sequence of bits Question: How much memory to allocate for a variable s value? Answer: A variable must have a type specifying how much storage to allocate. 15 Primitive Data Types In Detail Integer Types: byte 1 byte Range: -128 to +127 short 2 bytes Range: -32,000 to +32,000 int 4 bytes Range: -2 billion to +2 billion long 8 bytes Range: -9 quintillion to +9 quintillion Floating-Point Types: float 4 bytes -3.4x10 38 to 3.4x10 38, 7 digits of precision double 8 bytes -1.7x10 308 to 1.7x10 308, 15 digits of prec. Other types: boolean 1 byte true, false char 2 bytes A single (Unicode) character 17 Primitive-Type Literals Constants are also called literals Integer types: byte short optional sign and digits (0-9): 12-1 +234 0 1234567 int long Same as above, but followed by L or l : -1394382953L Floating-point types: double Two allowable forms: Avoid this lowercase L. It looks too much like the digit 1 Decimal notation: 3.14159-234.421 0.0042-43.0 Scientific notation: (use E or e for base 10 exponent) 3.145E5 = 3.145 x 10 5 = 314500.0 1834.23e-6 = 1834.23 x 10-6 = 0.00183423 float Same as double, but followed by f or F : 3.14159F -43.2f Note: By default, integer constants are int, unless L / l is used to indicate they are long. Floating constants are double, CMSC unless 131 Spring F / f is 2010 used to indicate they are float. 18 6

Character and String Literals Char literals: Single character in single quotes ( ) including: Letters and digits: A, B, C,, a, b, c,, 0, 1,, 9 Punctuation symbols: *, #, @, $ (except and backslash \ ) Escape sequences: (see below) String literals: 0 or more characters in double quotes ( ) Escape sequences: Allows inclusion of special characters: \ double quote \n new-line character (start a new line) \ single quote \t tab character \\ backslash Examples: char x = \ ; (x contains a single quote) String s1= \ Hi there!\ ; s1 contains Hi there! String s2= C:\\WINDOWS ; s2 contains C:\WINDOWS 19 Common Numeric Operators Arithmetic operators: Unary negation: -x Addition/subtraction: x+y x-y Multiplication/division: x*y x/y Division between integer types truncates to integer: 23/4 5 x%y returns the remainder of x divided by y: 23%4 3 Division with real types yields a real result: 23.0/4.0 5.75 Comparison operators: Equality/inequality: x == y x!= y Less than/greater than: x < y x > y Less than or equal/greater than or equal: x <= y x >= y These comparison operators return a boolean value: true or false. 20 Common String Operators String Concatenation: The + operator concatenates (joins) two strings. Go + Terps GoTerps Note: Concatenation does not add any space When a string is concatenated with another type, the other type is first evaluated and converted into its string representation. (8 * 4) + degrees 32degrees (1 + 2) + 5 35 String Comparison: Strings have special comparison functions. s.equals(t) : returns true if s and t have the same characters. s.compareto(t) : compares strings lexicographically (dictionary order) result < 0 if s precedes t result == 0 if s is equal to t result > 0 if s follows t dilbert.compareto( dogbert ) -1 (which is < 0) Both functions are case-sensitive. 21 7

User Input in Java We've done output (System.out); what about input? Java 5.0 includes the Scanner class feature Can use Scanner to create scanner objects Scanner objects convert user input into data To use Scannner need to import a library: import java.util.scanner; 22 Scanner Class Details To create a scanner object: new Scanner(input_source); Input source can be keyboard (System.in), files, etc. Object must be assigned to a variable (e.g. sc) Operations nextboolean() nextbyte() nextdouble() nextfloat() nextint() nextlong() nextshort() Returns value of indicated type (reports error if type mismatch next() Returns sequence of characters up to next whitespace (space, carriage return, tab, etc.) nextline() Returns sequence of characters up to next carriage return 23 Objects From Example 5: Scanner sc = new Scanner(System.in); sc is a variable Its type is Scanner? What s going on? Scanner is a class defined in java.util.scanner System.in is a predefined object for keyboard input new Scanner(System.in) creates a new object in the Scanner class and assigns it to sc Object? A bundle of data (instance variables) and operations (methods) A class defines both instance variables and methods for objects A class is also a type for objects new creates new objects in the given class We will learn (much) more about objects later 24 8

Debugging Java Programs Types of errors Compile time : caught by Eclipse / Java compiler Syntax errors disobeys the rules of the language; violates language s grammar Type errors: misuse of variables Run time : appear during program execution Semantic errors obeys the rules of the language but does not express them meaning you intended; division by 0 crash or hang or wrong outputs (because of mistakes in programming) Eclipse helps catch compile time errors Red: error Yellow: warning Debugging process of finding and fixing problems to minimize debugging frustration use unit testing write a small part, thoroughly test it, cycle back 25 Uninitialized Variables Caution Local variables Primitives vs Object References public static void main(string[] args){ int val1, val2=10; int val3 = val1+val2; } 26 9