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

Slides:



Advertisements
Similar presentations
 2005 Pearson Education, Inc. All rights reserved Introduction.
Advertisements

Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 1 Chapter 2 Primitive.
Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example F Identifiers, Variables, and Constants F Primitive Data Types –byte,
1 Java Basics. 2 Compiling A “compiler” is a program that translates from one language to another Typically from easy-to-read to fast-to-run e.g. from.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Shlomo Hershkop1 Introduction to java Class 1 Fall 2003 Shlomo Hershkop.
Introduction to Java Programming, 4E Y. Daniel Liang.
Outline Java program structure Basic program elements
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Introduction to Java Programming, 4E Y. Daniel Liang.
Chapter 3 Control Statements F Selection Statements –Using if and if...else –Nested if Statements –Using switch Statements –Conditional Operator F Repetition.
1. 2 Chapter 1 Introduction to Computers, Programs, and Java.
Java Overview CS2336: Computer Science II1. First Program public class HelloWorld { public static void main(String args[]) { System.out.println("Hello.
Lecture 1: Overview of Java. What is java? Developed by Sun Microsystems (James Gosling) A general-purpose object-oriented language Based on C/C++ Designed.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Java Building Elements Lecture 2 Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung University
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
DAT602 Database Application Development Lecture 5 JAVA Review.
Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
1 Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
1 Module Objective & Outline Module Objective: After completing this Module, you will be able to, appreciate java as a programming language, write java.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Basics of Java IMPORTANT: Read Chap 1-6 of How to think like a… Lecture 3.
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
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.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
CHAPTER 3 GC Java Fundamentals. 2 BASICS OF JAVA ENVIRONMENT  The environment  The language  Java applications programming Interface API  Various.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Introduction to Java Java Translation Program Structure
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Java Basics 1 Brief History of Java and Overview of Langauge.
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
By Mr. Muhammad Pervez Akhtar
Decision Statements, Short- Circuit Evaluation, Errors.
1 Chapter 5 Control Statements. 2 Objectives F To understand the flow of control in selection and loop statements. F To use Boolean expressions to control.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
Agenda  Brief History of Java and overview of language  Solve a problem to demonstrate Java syntax  Discuss coding issues and style via example.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Elementary Programming.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Terms: Software  Set of instructions  aka programs  Operating System:  Special software whose job it is to translateinstructions into hardware instructions.
Primitive Data Types and Operations F Introduce Programming with an Example F Identifiers, Variables, and Constants F Primitive Data Types –byte, short,
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.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Information and Computer Sciences University of Hawaii, Manoa
GC101 Introduction to computer and program
Selections Java.
Yanal Alahmad Java Workshop Yanal Alahmad
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Introduction to Programming in Java
Chapter 5 Control Statements
Units with – James tedder
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Object Oriented Programming in java
Chapter 2 Primitive Data Types and Operations
Presentation transcript:

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

3 A brief history of Java §Oak l “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 l The first Java-enabled Web browser (1994) §Java, May 23, 1995, Sun World

4 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

5 The advantage of Java §Java is platform independent l an application written for one computer is very likely to run unchanged on another computer. l “write once, run anywhere” §Java is simple l has a simpler syntax than C and C++. l 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 l encapsulation, inheritance, and polymorphism l all code must be contained in a class l no free functions (functions that do not belong to some class) like C++ §Java is free l can be downloaded free from

6 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!"); }

7 Compile programs §On command line javac file.java §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.

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

9 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 l set CLASSPATH=c:\packages §For Unix systems running C shell l setenv CLASSPATH $HOME/packages

10 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 l no more C++ const & or & §Garbage Collection is used l No need for destructors l 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 l Java uses the term Exceptions for runtime errors

11 Data Types §Primitive Data Types l byte short int long float double boolean char l stick with int for integers, double for real numbers §Classes and Objects l pre defined or user defined data types consisting of constructors, methods, and fields (constants and variables which may be primitives or objects.) int x; int y = 10; int z, zz; double a = 12.0; boolean done = false, prime = true; char mi = 'D';

12 Java Primitive Data Types 16 bit, Unicode true or false 64 bit floating point number 32 bit floating point number 64 bit signed integer 32 bit signed integer 16 bit signed integer 8 bit signed integer Characteristics Unicode character, \u0000 to \uFFFFchar NA, note Java booleans cannot be converted to or from other types boolean + 4.9E-324 to E+308 double + 1.4E-45 to E+38 float -9,223,372,036,854,775,808 to- 9,223,372,036,854,775,808 long -2,147,483,648 to 2,147,483,648 int to short -128 to 127 byte Range Data Type

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

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

15 Naming Conventions, cont.  Class names: 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. l 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.

16 Indention in Statement Block §Usually indent the statements in a block so that l Easier to identify the block properly & enhance the readability In all block like function body l Use tab rather than space

17 Increment and Decrement Operators Always keep expressions increment and decrement operators simple and easy to understand.

18 Programming Errors §Syntax Errors l Detected by the compiler §Runtime Errors l Causes the program to abort §Logic Errors l Produces incorrect result

19 Compilation Errors public class ShowSyntaxErrors { public static void main(String[] args) { i = 30; System.out.println(i+4); }

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

21 Runtime Errors public class ShowRuntimeErrors { public static void main(String[] args) { int i = 1 / 0; } Integer division often gives unexpected results.

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

23 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 l part of style guide

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

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

26 If Statement

27 if Statements -- Caution Adding a semicolon at the end of an if clause is a common mistake. if (radius >= 0); { 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. Wrong

28 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");

29 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");

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

31 switch/case Statement §Sometimes, it is necessary to test the content of a variable against a list of possible values l Can use a number of if..else if..else l 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.

32 switch/case Statement §“default” is optional l Recommend to use even just logging l Let you know unexpected value §“break” means end of execution for the case l If no, the following will be executed l Recommend to use

33 switch/case vs if/else §switch/case can support expression of type: byte, short, char or int l can check the equality for byte, short, char or int l only supports equality checking §if/else can support boolean type only l with proper relational operators, can support all primitive type and non-primitive type l can check the equality for long, float, double, boolean and non-primitive types l can use any relational operator.

34 switch/case vs if/else §Although switch/case is more restricted, l Its structure is more elegant and easier to read l Faster l Use it whenever possible

35 Looping T F while structure do/while structure T F Java’s single-entry/single-exit control structures. F T for structure

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

37 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); } Always use integer variables as for loop indexes, and never modify their values inside the loop. Wrong

38 Caution, cont. Similarly, the following loop is also 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); Wrong Correct

39 The break Keyword

40 The continue Keyword

41 §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. Unit 6: Break Vs Continue

42 §Example: 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? } Unit 6: Break Vs Continue

43 §Example: 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"); } Unit 6: Break Vs Continue

44 Introducing Methods Method Structure A method is a collection of statements that are grouped together to perform an operation.

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