Java Overview CS2336: Computer Science II1. First Program public class HelloWorld { public static void main(String args[]) { System.out.println("Hello.

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Advertisements

L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Chapter 2 Elementary Programming
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4: Selections.
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,
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 3 Control Statements.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 2 Primitive Data.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 1 Chapter 2 Primitive.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 Primitive Data.
Introduction to Java Programming, 4E Y. Daniel Liang.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 Primitive Data.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 2 Elementary Programming.
Introduction to Java Programming, 4E Y. Daniel Liang.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 2 Elementary Programming.
1. 2 Chapter 1 Introduction to Computers, Programs, and Java.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 2 Elementary Programming.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Chapter 2 Elementary Programming 1. Introducing Programming with an Example Listing 2.1 Computing the Area of a Circle This program computes the area.
Primitive Data Types and Operations Identifiers, Variables, and Constants Primitive Data Types Byte, short, int, long, float, double, char, boolean Casting.
Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
Programming Style and Documentation Objective(s) F To become familiar with Java Style and Documentation Guidelines.
Simple Programs from Chapter 2 Putting the Building Blocks All Together (corresponds with Chapter 2)
1 Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 2 Primitive Data Types.
VARIABLES Introduction to Computer Science 1- COMP 1005, 1405 Instructor : Behnam Hajian
INF120 Basics in JAVA Programming AUBG, COS dept Lecture 05 Title: Decision/Selection Control Structures Reference: MalikFarrell, chap 1, Liang Ch 3.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
1 Chapter 2 Elementary Programming. 2 Objectives  To write Java programs to perform simple calculations  To obtain input from the console using the.
Programming Fundamentals I (COSC- 1336), Lecture 2 (prepared after Chapter 2 of Liang’s 2011 textbook) Stefan Andrei 10/17/20151 COSC-1336, Lecture 2.
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Chapter 2 Elementary Programming
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.
Liang, Introduction to Java Programming1 Primitive Data Types and Operations Gang Qian Department of Computer Science University of Central Oklahoma.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 Primitive Data.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 2 Elementary Programming.
©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.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 2 Elementary Programming.
1 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 1 Introduction to Computers, Programs,
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 2 Elementary Programming.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Elementary Programming.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
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.
Introduction to Control Statements IT108 George Mason University.
1.  Algorithm: 1. Read in the radius 2. Compute the area using the following formula: area = radius x radius x PI 3. Display the area 2.
Chapter 2 Elementary Programming 1. Motivations 2 In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Chapter 1 Introduction to Computers, Programs, and Java
Elementary Programming
Lecture 3: Operators, Expressions and Type Conversion
Selections Java.
Chapter 2 Elementary Programming
Chapter 2 Elementary Programming
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 2 Elementary Programming
Chapter 2 Elementary Programming
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Anatomy of a Java Program
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Chapter 2 Primitive Data Types and Operations
Presentation transcript:

Java Overview CS2336: Computer Science II1

First Program public class HelloWorld { public static void main(String args[]) { System.out.println("Hello World"); } CS2336: Computer Science II2

Compiling and Running HelloWorld.java javac HelloWorld.java java HelloWorld HelloWorld.class compile run bytecode source code CS2336: Computer Science II3

Java bytecode and interpreter bytecode is an intermediate representation of the program (class). The Java interpreter starts up a new “ Virtual Machine ”. The VM starts executing the users class by running it ’ s main() method. CS2336: Computer Science II4

Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * ; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } no value radius allocate memory for radius animation CS2336: Computer Science II5

Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * ; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } no value radius memory no value area allocate memory for area animation CS2336: Computer Science II6

Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * ; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } 20 radius no value area assign 20 to radius animation CS2336: Computer Science II7

Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * ; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } 20 radius memory area compute area and assign it to variable area animation CS2336: Computer Science II8

Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * ; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } 20 radius memory area print a message to the console animation CS2336: Computer Science II9

Reading Input from the Console Create a Scanner object – Scanner input = new Scanner(System.in); 2. Use the methods next(), nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble(), or nextBoolean() to obtain to a string, byte, short, int, long, float, double, or boolean value. For example, – System.out.print("Enter a double value: "); – Scanner input = new Scanner(System.in); – double d = input.nextDouble(); CS2336: Computer Science II10

import java.util.Scanner; // Scanner is in the java.util package public class ComputeAreaWithConsoleInput { public static void main(String[] args) { // Create a Scanner object Scanner input = new Scanner(System.in); // Prompt the user to enter a radius System.out.print("Enter a number for radius: "); double radius = input.nextDouble(); // Compute area double area = radius * radius * ; // Display result System.out.println("The area for the circle of radius " + radius + " is " + area); } CS2336: Computer Science II11

Declaring Variables int x; // Declare x to be an // integer variable; double radius; // Declare radius to // be a double variable; char a; // Declare a to be a // character variable; CS2336: Computer Science II12

Assignment Statements x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a; CS2336: Computer Science II13

Declaring and Initializing in One Step int x = 1; double d = 1.4; CS2336: Computer Science II14

Constants final datatype CONSTANTNAME = VALUE; final double PI = ; final int SIZE = 3; CS2336: Computer Science II15

Numeric Operators CS2336: Computer Science II16

Integer Division +, -, *, /, and % 5 / 2 yields an integer / 2 yields a double value % 2 yields 1 (the remainder of the division) CS2336: Computer Science II17

Quiz1-1 Suppose today is Saturday and you and your friends are going to meet in 10 days. What day is in 10 days? CS2336: Computer Science II18

Answer CS2336: Computer Science II19

Quiz1-2 Write a program that obtains hours and minutes from seconds. CS2336: Computer Science II20

Shortcut Assignment Operators OperatorExampleEquivalent +=i += 8i = i + 8 -=f -= 8.0f = f *=i *= 8i = i * 8 /=i /= 8i = i / 8 %=i %= 8i = i % 8 CS2336: Computer Science II21

Increment and Decrement Operators OperatorNameDescription ++varpreincrementThe expression (++var) increments var by 1 and evaluates to the new value in var after the increment. var++postincrementThe expression (var++) evaluates to the original value in var and increments var by 1. --varpredecrementThe expression (--var) decrements var by 1 and evaluates to the new value in var after the decrement. var--postdecrement The expression (var--) evaluates to the original value in var and decrements var by 1. CS2336: Computer Science II22

Increment and Decrement Operators, cont. CS2336: Computer Science II23

Increment and Decrement Operators, cont. Using increment and decrement operators makes expressions short, but it also makes them complex and difficult to read. Avoid using these operators in expressions that modify multiple variables, or the same variable for multiple times such as this: int k = ++i + i. CS2336: Computer Science II 24

The String Type The char type only represents one character. To represent a string of characters, use the data type called String. For example, String message = "Welcome to Java"; String is actually a predefined class in the Java library. The String type is not a primitive type. It is known as a reference type. Any Java class can be used as a reference type for a variable. Reference data types will be thoroughly discussed in Chapter 7, “Objects and Classes.” CS2336: Computer Science II25

String Concatenation // Three strings are concatenated String message = "Welcome " + "to " + "Java"; // String Chapter is concatenated with number 2 String s = "Chapter" + 2; // s becomes Chapter2 // String Supplement is concatenated with character B String s1 = "Supplement" + 'B'; // s1 becomes SupplementB CS2336: Computer Science II26

Programming Style and Documentation Appropriate Comments Naming Conventions Proper Indentation and Spacing Lines Block Styles CS2336: Computer Science II27

Appropriate Comments Include a summary at the beginning of the program to explain what the program does, its key features, its supporting data structures, and any unique techniques it uses. Include your name, class section, instructor, date, and a brief description at the beginning of the program. CS2336: Computer Science II28

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. CS2336: Computer Science II29

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, and use underscores to connect words. For example, the constant PI and MAX_VALUE CS2336: Computer Science II30

Proper Indentation and Spacing Indentation – Indent two spaces. Spacing – Use blank line to separate segments of the code. CS2336: Computer Science II31

Block Styles Use end-of-line style for braces. CS2336: Computer Science II32

Programming Errors Syntax Errors – Detected by the compiler Runtime Errors – Causes the program to abort Logic Errors – Produces incorrect result CS2336: Computer Science II33

Syntax Errors public class ShowSyntaxErrors { public static void main(String[] args) { i = 30; System.out.println(i + 4); } CS2336: Computer Science II34

Runtime Errors public class ShowRuntimeErrors { public static void main(String[] args) { int i = 1 / 0; } CS2336: Computer Science II35

Debugging Logic errors are called bugs. The process of finding and correcting errors is called debugging. A common approach to debugging is to use a combination of methods to narrow down to the part of the program where the bug is located. You can hand-trace the program (i.e., catch errors by reading the program), or you can insert print statements in order to show the values of the variables or the execution flow of the program. This approach might work for a short, simple program. But for a large, complex program, the most effective approach for debugging is to use a debugger utility. CS2336: Computer Science II36

Debugger Debugger is a program that facilitates debugging. You can use a debugger to Execute a single statement at a time. Trace into or stepping over a method. Set breakpoints. Display variables. Display call stack. Modify variables. CS2336: Computer Science II37

Converting Strings to Integers The input returned from the input dialog box is a string. If you enter a numeric value such as 123, it returns “123”. To obtain the input as a number, you have to convert a string into a number. To convert a string into an int value, you can use the static parseInt method in the Integer class as follows: int intValue = Integer.parseInt(intString); where intString is a numeric string such as “123”. CS2336: Computer Science II38

Converting Strings to Doubles To convert a string into a double value, you can use the static parseDouble method in the Double class as follows: double doubleValue =Double.parseDouble(doubleString); where doubleString is a numeric string such as “123.45”. CS2336: Computer Science II39

Motivations If you assigned a negative value for radius in ComputeArea.java, the program would print an invalid result. If the radius is negative, you don't want the program to compute the area. How can you deal with this situation? CS2336: Computer Science II40

import java.util.Scanner; // Scanner is in the java.util package public class ComputeAreaWithConsoleInput { public static void main(String[] args) { // Create a Scanner object Scanner input = new Scanner(System.in); // Prompt the user to enter a radius System.out.print("Enter a number for radius: "); double radius = input.nextDouble(); // Compute area double area = radius * radius * ; // Display result System.out.println("The area for the circle of radius " + radius + " is " + area); } CS2336: Computer Science II41

Comparison Operators The boolean Type and Operators Operator Name < less than <= less than or equal to > greater than >= greater than or equal to == equal to != not equal to boolean b = (1 > 2); CS2336: Computer Science II42

Control Structures More of what you expect: conditional: if, if else, switch loop: while, for, do break and continue (but a little different than with C/C++). CS2336: Computer Science II43

One-way if Statements if (boolean-expression) { statement(s); } if (radius >= 0) { area = radius * radius * PI; System.out.println("The area" + " for the circle of radius " + radius + " is " + area); } CS2336: Computer Science II44

Note CS2336: Computer Science II45

Problem: Guessing Birthday The program can guess your birth date. Run to see how it works. CS2336: Computer Science II46

The Two-way if Statement if (boolean-expression) { statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case; } CS2336: Computer Science II47

if...else Example if (radius >= 0) { area = radius * radius * ; System.out.println("The area for the “ + “ circle of radius " + radius + " is " + area); } else { System.out.println("Negative input"); } CS2336: Computer Science II48

Multiple Alternative if Statements CS2336: Computer Science II49

Trace if-else statement if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; Suppose score is 70.0The condition is false animation CS2336: Computer Science II50

Trace if-else statement if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; Suppose score is 70.0The condition is false animation CS2336: Computer Science II51

Trace if-else statement if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; Suppose score is 70.0The condition is true animation CS2336: Computer Science II52

Trace if-else statement if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; Suppose score is 70.0grade is C animation CS2336: Computer Science II53

Trace if-else statement if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; Suppose score is 70.0Exit the if statement animation CS2336: Computer Science II54

Note The else clause matches the most recent if clause in the same block. CS2336: Computer Science II55

Note, 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. CS2336: Computer Science II56

Common Errors 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 CS2336: Computer Science II57

TIP CS2336: Computer Science II58

CAUTION CS2336: Computer Science II59

Acknowledgement The original authors of these slides are the authors of the textbook. The instructor made necessary modifications, with permissions from the authors. CS2336: Computer Science II