Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Similar documents
Chapter 2 Primitive Data Types and Operations. Objectives

CONDITIONAL EXECUTION

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

Chapter 3 Selection Statements

Chapter 2 Primitive Data Types and Operations

CS 231 Data Structures and Algorithms, Fall 2016

Java Bytecode (binary file)

Chapter 2 Elementary Programming

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Program Fundamentals

Lecture 1: Overview of Java

Chapter 3. Selections

Lecture 1 Java SE Programming

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

History of Java. Java was originally developed by Sun Microsystems star:ng in This language was ini:ally called Oak Renamed Java in 1995

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

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

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

Index. Course Outline. Grading Policy. Lab Time Distribution. Important Instructions

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

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

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

Object-Oriented Programming

Chapter 2 Primitive Data Types and Operations

Selections. CSE 114, Computer Science 1 Stony Brook University

Software and Programming 1

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Lec 3. Compilers, Debugging, Hello World, and Variables

Java Basic Programming Constructs

3chapter C ONTROL S TATEMENTS. Objectives

Introduction to Java

CS171:Introduction to Computer Science II

COMP 202 Java in one week

JAVA Programming Concepts

Motivations. Chapter 3: Selections and Conditionals. Relational Operators 8/31/18. Objectives. Problem: A Simple Math Learning Tool

Zheng-Liang Lu Java Programming 45 / 79

Java Language. Programs. Computer programs, known as software, are instructions to the computer. You tell a computer what to do through programs.

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

Goals. Java - An Introduction. Java is Compiled and Interpreted. Architecture Neutral & Portable. Compiled Languages. Introduction to Java

PROGRAMMING FUNDAMENTALS

Pace University. Fundamental Concepts of CS121 1

Introduction to Programming Using Java (98-388)

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

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

4 WORKING WITH DATA TYPES AND OPERATIONS

Chapter 1 Introduction to java

CCHAPTER SELECTION STATEMENTS HAPTER 3. Objectives

Learning objectives. The Java Environment. Java timeline (cont d) Java timeline. Understand the basic features of Java

Course Outline. Introduction to java

CS 11 java track: lecture 1

COMP 202 Java in one week

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

Full file at

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

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. and Java. Chapter 2 Primitive Data Types and Operations

Software and Programming 1

The Basic Parts of Java

An overview of Java, Data types and variables

JAVA OPERATORS GENERAL

Chapter 1 Introduction to Computers, Programs, and Java

Expanded Guidelines on Programming Style and Documentation

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

4 Programming Fundamentals. Introduction to Programming 1 1

Chapter 2 Elementary Programming

Topics. Chapter 5. Equality Operators

Introduction to Computers and Java

Introduction. C provides two styles of flow control:

Datatypes, Variables, and Operations

Elementary Programming

Introduction to Computers and Java. Objectives. Outline. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich.

CompSci 125 Lecture 02

Introduction to Computers and Java. Objectives. Outline. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich.

Introduction to Computers and Java

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Chapter 2 ELEMENTARY PROGRAMMING

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Full file at

2 rd class Department of Programming. OOP with Java Programming

3. Java - Language Constructs I

Lecture Set 2: Starting Java

Lab # 2. For today s lab:

CEN 414 Java Programming

Date: Dr. Essam Halim

Fall 2017 CISC124 9/16/2017

CS313D: ADVANCED PROGRAMMING LANGUAGE

Lecture Set 2: Starting Java

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

( &% class MyClass { }

A very simple program. Week 2: variables & expressions. Declaring variables. Assignments: examples. Initialising variables. Assignments: pattern

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Getting started with Java

STRUCTURING OF PROGRAM

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Java Primer 1: Types, Classes and Operators

Simple Java Reference

Elementary Programming. CSE 114, Computer Science 1 Stony Brook University

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Assignment Marking Criteria

Transcription:

Outline Overview history and advantage how to: program, compile and execute 8 data types 3 types of errors Control statements Selection and repetition statements Classes and methods methods... 2

Oak A brief history of Java Java, whose original name was Oak, was developed as a part of the Green project at Sun. It was started in December '90 by Patrick Naughton, Mike Sheridan and James Gosling and was chartered to spend time (and money!) trying to figure out what would be the "next wave" of computing and how we might catch it. They quickly came to the conclusion that at least one of the waves was going to be the convergence of digitally controlled consumer devices and computers. HotJava The first Java-enabled Web browser (1994) Java, May 23, 1995, Sun World 3 How Java Works Java's platform independence is achieved by the use of the Java Virtual Machine A Java program consists of one or more files with a.java extension When a Java program is compiled the.java files are fed to a compiler which produces a.class file for each class definition The.class file contains Java bytecode. Bytecode is like machine language, but it is intended for the Java Virtual Machine not a specific chip 4

The advantage of Java Java is platform independent an application written for one computer is very likely to run unchanged on another computer. write once, run anywhere Java is simple has a simpler syntax than C and C++. Most of the trickiest and error-prone portions (such as pointer manipulation) of the C languages do not exist in Java. Java is object-oriented encapsulation, inheritance, and polymorphism all code must be contained in a class no free functions (functions that do not belong to some class) like C++ Java is free can be downloaded free from http://java.sun.com 5 A start program: HelloWorld.java //This program prints Hello World! public class HelloWorld { //main method begins execution of Java //application public static void main(string[] args) { System.out.println("Hello World!"); 6

On command line javac file.java Compile programs A program in Java consists of one or more class definitions, each compiled into its own.class file of Java Virtual Machine object code. One of these classes must define a method main(), which is where the program starts running. 7 Execute Programs On command line java classname To invoke a Java program, you run the Java interpreter, java, and specify the name of the class that contains the main() method. 8

Set the CLASSPATH The programmer must first set the CLASSPATH environment variable on the computer to tell the Java compiler where to look for the package. For Windows set CLASSPATH=c:\packages For Unix systems running C shell setenv CLASSPATH $HOME/packages 9 Preview to Java Language Basic syntax the same as C++ Programmers do not need to deal with pointers as in C language. All parameters are pass by value. Pass by reference is not possible no more C++ const & or & Garbage Collection is used No need for destructors Not as many memory management issues (memory is still managed, but by the run time system instead of the programmer.) Array index out of bounds causes a runtime error Java uses the term Exceptions for runtime errors 10

Primitive Data Types Data Types byte short int long float double boolean char int x; int y = 10; int z, zz; double a = 12.0; boolean done = false, prime = true; char mi = 'D'; stick with int for integers, double for real numbers Classes and Objects pre defined or user defined data types consisting of constructors, methods, and fields (constants and variables which may be primitives or objects.) 11 Java Primitive Data Types Data Type Characteristics Range byte short int long float double boolean char 8 bit signed integer 16 bit signed integer 32 bit signed integer 64 bit signed integer 32 bit floating point number 64 bit floating point number true or false 16 bit, Unicode -128 to 127-32768 to 32767-2,147,483,648 to 2,147,483,648-9,223,372,036,854,775,808 to- 9,223,372,036,854,775,808 + 1.4E-45 to + 3.4028235E+38 + 4.9E-324 to + 1.7976931348623157E+308 NA, note Java booleans cannot be converted to or from other types Unicode character, \u0000 to \uffff 12

Programming advice Be sure that the name of file containing a class is exactly the same as the name of the class being defined. Always begin every program with comments describing the purpose of the program. Use comments liberally throughout the program to explain how each portion of the code works. 13 Naming Conventions Choose meaningful and descriptive names. Variables and method names: Use lowercase. If the name consists of several words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name. For example, the variables radius and area, and the method computearea. 14

Class names: Naming Conventions, cont. Capitalize the first letter of each word in the name. For example, the class name ComputeArea. Constants: Capitalize all letters in constants. For example, the constant PI. To improve the consistency and understandability of your code, assign a name to any important constants, and refer to them by that name in the program. 15 Indention in Statement Block Usually indent the statements in a block so that Easier to identify the block properly & enhance the readability In all block like function body Use tab rather than space 16

Increment and Decrement Operators int i=10; int newnum = 10*i++; Equivalent to int newnum = 10*i; i = i + 1; int i=10; int newnum = 10*(++i); Equivalent to i = i + 1; int newnum = 10*i; Always keep expressions increment and decrement operators simple and easy to understand. 17 Programming Errors Syntax Errors Detected by the compiler Runtime Errors Causes the program to abort Logic Errors Produces incorrect result 18

Compilation Errors public class ShowSyntaxErrors { public static void main(string[] args) { i = 30; System.out.println(i+4); 19 Compilation Errors, cont. int i; public class ShowSyntaxErrors { public static void main(string[] args) { i = 30; System.out.println(i+4); 20

Runtime Errors public class ShowRuntimeErrors { public static void main(string[] args) { int i = 1 / 0; Integer division often gives unexpected results. 21 Logic Errors import javax.swing.*; public class ShowLogicErrors { // Determine if a number is between 1 and 100 inclusively public static void main(string[] args) { // Prompt the user to enter a number String input = JOptionPane.showInputDialog(null, "Please enter an integer:", "ShowLogicErrors", JOptionPane.QUESTION_MESSAGE); int number = Integer.parseInt(input); // Display the result System.out.println("The number is between 1 and 100, " + "inclusively? " + ((1 < number) && (number < 100))); System.exit(0); 22

Assertions Assertions have the form assert boolean expression : what to output if assertion is false Example if ( (x < 0) (y < 0) ) { // we know either x or y is < 0 assert x < 0 y < 0 : x + " " + y; x += y; else { // we know both x and y are not less than zero assert x >= 0 && y >= 0 : x + " " + y; y += x; Use assertion liberally in your code part of style guide 23 Assertions Uncover Errors in Your Logic if ( a < b ) { // we a is less than b assert a < b : a + " " + b; System.out.println(a + " is smaller than " + b); else { // we know b is less than a assert b < a : a + " " + b; System.out.println(b + " is smaller than " + a); Use assertions in code that other programmers are going to use. 24

Control Statements Selection Statements Using if and if...else Using switch Statements Conditional Operator Repetition Statements Looping: while, do-while, and for Using break and continue If Statement 26

if Statements -- Caution Adding a semicolon at the end of an if clause is a common mistake. if (radius >= 0); { Wrong area = radius*radius*pi; System.out.println( "The area for the circle of radius " + radius + " is " + area); This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error. This error often occurs when you use the next-line block style. 27 Any output? int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); else System.out.println("B"); 28

Match else with if, cont. The else clause matches the most recent if clause in the same block. For example, the following statement int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); else System.out.println("B"); is equivalent to int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); else System.out.println("B"); 29 Match else with if, cont. Nothing is printed from the preceding statement. To force the else clause to match the first if clause, you must add a pair of braces: int i = 1; int j = 2; int k = 3; if (i > j) { if (i > k) System.out.println("A"); else System.out.println("B"); This statement prints B. 30

switch/case Statement Sometimes, it is necessary to test the content of a variable against a list of possible values Can use a number of if..else if..else But coding is tedious Java provides a faster and more readable flow of control statement: switch/case The switch structure may be used to select among mutually exclusive options based on the results of a single integer or character expression. 31 switch/case Statement default is optional Recommend to use even just logging Let you know unexpected value break means end of execution for the case If no, the following will be executed Recommend to use 32

switch/case vs if/else switch/case can support expression of type: byte, short, char or int can check the equality for byte, short, char or int only supports equality checking if/else can support boolean type only with proper relational operators, can support all primitive type and non-primitive type can check the equality for long, float, double, boolean and non-primitive types can use any relational operator. 33 switch/case vs if/else Although switch/case is more restricted, Its structure is more elegant and easier to read Faster Use it whenever possible 34

Looping while structure do/while structure T F T for structure F T F Java s single-entry/single-exit control structures. 35 Which Loop to Use? The three forms of loop statements, while, do, and for, are expressively equivalent; that is, you can write a loop in any of these three forms. Use the one that is most intuitive and comfortable for you. In general, a for loop may be used if the number of repetitions is known, as, for example, when you need to print a message 100 times. A while loop may be used if the number of repetitions is not known, as in the case of reading the numbers until the input is 0. A do-while loop can be used to replace a while loop if the loop body has to be executed before testing the continuation condition. 36

Caution Adding a semicolon at the end of the for clause before the loop body is a common mistake, as shown below: for (int i=0; i<10; i++); { System.out.println("i is " + i); Wrong Always use integer variables as for loop indexes, and never modify their values inside the loop. 37 Caution, cont. Similarly, the following loop is also wrong: Wrong int i=0; while (i<10); { System.out.println("i is " + i); i++; In the case of the do loop, the following semicolon is needed to end the loop. int i=0; do { System.out.println("i is " + i); i++; while (i<10); Correct 38

The break Keyword Continuation condition? false true Statement(s) break Statement(s) Next Statement 39 The continue Keyword Continue condition? false true Statement(s) continue Statement(s) Next Statement 40

Unit 6: Break Vs Continue The break statement, which is used in the switch statement, can be used in the loop body. When the break statement is executed, the program control jumps to the statement after the loop body, i.e. break the loop. The continue statement causes the program control jumps to the end of the loop and then go back to the condition checking and then continues. 41 Example: Unit 6: Break Vs Continue class ContinueAndBreak { public static void main (String args[]) { int num; for (num=1; num<=10; num++){ if (num==5) { break; System.out.println("num is "+num); //What s the output? for (num=1; num<=10; num++){ if (num==5) { continue; System.out.println("num is "+num); //What s the output? 42

Example: Unit 6: Break Vs Continue class ContinueAndBreak { public static void main (String args[]) { int num; for (num=1; num<=10; num++) { if (num==5) { break; System.out.println("num is "+num); System.out.println("The break makes the system to print the number to 4"); for (num=1; num<=10; num++) { if (num==5) { continue; System.out.println("num is "+num); System.out.println("The continue makes the system to skip the number 5"); 43 Introducing Methods A method is a collection of statements that are grouped together to perform an operation. Method Structure 44

Introducing Methods, cont. parameter profile refers to the type, order, and number of the parameters of a method. method signature is the combination of the method name and the parameter profiles. The parameters defined in the method header are known as formal parameters. When a method is invoked, its formal parameters are replaced by variables or data, which are referred to as actual parameters. 45