A Sample Program public class Hello { public static void main(String[] args) { System.out.println( " Hello, world! " ); }

Slides:



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

Introduction to C Programming
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Introduction to C Programming
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
CMT Programming Software Applications
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
JavaScript, Third Edition
Introduction to C Programming
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Basic Elements of C++ Chapter 2.
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Primitive Types, Strings, and Console I/O Chapter 2.1 Variables and Values Declaration of Variables Primitive Types Assignment Statement Arithmetic Operators.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Chapter 2: Using Data.
CPS120: Introduction to Computer Science
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.
Chapter 2 Elementary Programming
Chapter 2: Java Fundamentals
C++ Programming: Basic Elements of C++.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
A First Look at Java Chapter 2 1/29 & 2/2 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
November 1, 2015ICS102: Expressions & Assignment 1 Expressions and Assignment.
Chapter 2 Variables.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Literals A literal (sometimes called a constant) is a symbol which evaluates to itself, i.e., it is what it appears to be. Examples: 5 int literal
Java-02 Basic Concepts Review concepts and examine how java handles them.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
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.
A Sample Program #include using namespace std; int main(void) { cout
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
CSE 110: Programming Language I Matin Saad Abdullah UB 1222.
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.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Bill Tucker Austin Community College COSC 1315
Chapter 2 Variables.
Chapter Topics The Basics of a C++ Program Data Types
Basic Elements of C++.
Multiple variables can be created in one declaration
Java Programming: From Problem Analysis to Program Design, 4e
Basic Elements of C++ Chapter 2.
IDENTIFIERS CSC 111.
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Chapter 2 Edited by JJ Shepherd
MSIS 655 Advanced Business Applications Programming
Chapter 2 Variables.
Expressions and Assignment
elementary programming
Chapter 2: Introduction to C++.
Introduction to Java Applications
In this class, we will cover:
Primitive Types and Expressions
Unit 3: Variables in Java
Chapter 2 Variables.
Presentation transcript:

A Sample Program public class Hello { public static void main(String[] args) { System.out.println( " Hello, world! " ); }

Program Outline public class { public static void main(String args[]) { } }

Another Simple Program import java.util.Scanner; public class AddNumbers { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print( " Enter two numbers > " ); int a = sc.nextInt(); int b = sc.nextInt(); System.out.println( " Total = " + (a+b)); }

Elements of the Program import java.util.Scanner; This allows the program to use the Scanner class for easy inputting of data. Other packages may be imported as well.

Elements of the Program public class HelloWorld { } All field and method declarations must be in some class. Usually, classes are stored in a file with the same name as the class with the extension.java. The public keyword indicates that any other class may reference this class.

Elements of the Program public static void main(String[] args) This is the standard function heading for the main function. Every program needs a main function. This function takes an array of strings as arguments ( String[] args ) and does not return a value (void). It is a public method (public), so anyone can call it, and it is a method that is common to the entire class (static).

Elements of the Program { } The brackets surround the actual code of the main function.

Elements of the Program System.out.println( " Hello, World! " ) This prints out the text Hello, world! in a console window and then starts a new line. System.out is the standard output, in this case, the console window on the display. println is a method for printing strings followed by a new line.

Data Objects Data objects are boxes in memory that hold values. Each box can hold exactly one value. Values can be integers, floating point numbers (similar to real numbers), characters, strings, and so on. Each data object has a specific type of object it can hold. So, a data object for an integer is different than a data object for a floating point number.

Identifiers and Variables To use a data object, we give it a name. Many things in a Java program have names – data objects, functions (e.g., “main”), packages (e.g., “util”). The name of a data object is called a variable.

Rules for Identifiers There are rules for valid identifiers. In Java, an identifier must start with either a letter (a-z, A-Z) the underscore character (_) (usually reserved for system stuff), or the dollar sign ($) (but never use $). The rest of the character can be letters, digits, or underscore, or the dollar sign. case-sensitive. FOOBEAR is different from foobear and different from FooBear Identifiers are case-sensitive. FOOBEAR is different from foobear and different from FooBear

Examples of Identifiers Valid Identifiers:  x  x1  x13bc  George  abc_def  myStudent Invalid Identifiers  12  hello.cpp  data-1  change/3

Identifier Conventions In addition to the rules, there are also conventions about identifiers that are commonly used: Variables start with lower-case letters Classes start with upper-case letters Literals are all upper-case If a variable is more than one word, the first word starts with a lower-case letter, other words begin with upper-case letters, e.g., myFirstVariable Underscores are mostly in system names

Keywords Certain identifiers are reserved keywords and should not be used. Examples are: final, class, public, int, char,...

Variables Variables are identifiers which are names for data objects. They are used for storing values in data objects and for accessing those values. Think of the data object as a box and the variable as the label on the box. (A box can have more than one label on it – we will get to that later.)

Definitions and Declarations Before a data object can be used it must be created and given a type (what kind of thing can be stored in it). This is called a definition. Before a variable can be used it must be given a type as well. This is called a declaration. In Java, we may combine a declaration with a definition or they may occur separately.

Declarations and Definitions - Exs. int a; This creates a new data object that can hold an integer, and assigns the name a to that data object. a is an integer variable (works for primitive types). char foobear; This creates a data object that can hold a character and assigns the name foobear to it. foobear is a character variable.

Primitive Types The are several common types of data objects: integers ( int ), floating point – similar to reals ( float, double ), characters, ( char ), Boolean – true/false ( boolean ). There are also other primitive types, long and short.

Sizes of Types TypeSize Size Range boolean 1 bit Not Applicable char 16 bits all Unicode characters byte 8 bits -128 to 127 short 16 bits -32,768 to 32,767

Sizes of Types TypeSize Size Range int32 bits -2,147,483,648 to 2,147,483,647 long64 bits -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 float32 bits ± ∗ to ± ∗ double64 bits ± ∗ to ± ∗

Assignment Statements An assignment statement is a way to change the value stored in a data object. The left-hand side of an assignment statement is the name of the data object (a variable), and the right-hand side is the value that will replace the contents of the data object. The right-hand side may be an expression whose value is put into the data object.

Assignment Statement - Example The syntax for an assignment statement is Variable = Expression; For example, x = x + y; is an an assignment statement. The variable on the left-hand side indicates where to put the value. Any variables on the right-hand side are used to retrieve values stored in their data objects.

Assignment Statement - Example x = x + 1; means to take the old value of the data object (box) labeled x, add 1 to that value, and store that value back in the data object labeled x.

Variable Initialization Be sure to put a value into a data object before trying to use that value, i.e., all variables should be initialized before being used. Initialization can be done at the same time as declaration/definition. For example, int a = 5; creates a new int data object, labels it with the variable a, and sets its initial value to 5.

Expressions Simple expressions combine operators, variables, and literals in a meaningful way. Java uses common symbols for arithmetic operators, + (plus), - (minus), * (times), / (divides), and also % for remainder. The order of evaluation is the one used in mathematics: *, /, % (done first) +, - (done next) Parentheses may be used to change the order.

Expressions - Examples a + b * c / 2 – 5 (a + b) * c / (2 – 5) frodo + samwise + gandalf + strider 7.2 / 5.0 – 6

Exercise Write a short program that calculate and prints out the area of a circle of radius 7. Create a double, called PI, to store the value of PI. Create a int, r, for the radius 7. Have an output statement to calculate and print out the area.

Literals A literal (sometimes called a constant) is a symbol which evaluates to itself, i.e., it is what it appears to be. Examples: 5 int literal floating point literal 6.0 floating point literal 6E7 floating point literal 'a' character literal " Simon " String literal true boolean literal

Constants It is often useful to name literals, that is, to use symbolic names rather than the literals directly. The final modifier is used to declare a data object whose value cannot be changed once it is initialized (and so it must be initialized to set the original value) final double PI = ;

String Literals String literals are sequences of characters enclosed in double quotes ( " ). This is different from a char literal which consists of a single character enclosed in single quotes ('). You can put a double quote inside of a string by using an escape sequence, that is, preceding the double quote by a backslash. Example: "T his is a double quote \ ". "

Assignment Compatibility A data object can only hold one type of object (int, float, double, char, string), but sometimes you can convert an object of one type to another type before storing it. For example, double a = 4; is perfectly fine. 4 is converted to a double, 4.0, before being stored in a. int b = 3.6; is not okay.

Shorthand Assignment Statements In Java. you can abbreviate an assignment statement which modifies the variable on the left hand side. For example, a += 5; is shorthand for a = a + 5; Similarly, *=, -=, /= are shorthand for their respective operations

Integer Division One thing to watch out for is integer division. If you divide two ints, the result is another int, not a floating point number. So, 19/4 is 4, not If you divide two floating point numbers, the result is a floating point number: 19.0/4.0 is If you divide an int by a floating point number, the int is converted to floating point first.

Increment and Decrement Java provides shorthand operators for incrementing and decrementing values. n++; increments the value of n by 1 and the value is n before the increment ++n; increments the value of n by 1 and the value is n after the increment n-- and --n are similar, but decrement the value.

String Class The String class provides literals and variables: " Hello, world! " // string literal String word = " abracadabra " ; // string variable There is also an operator, +, for string concatenation: String name = " Simon " ; System.out.println( " Hello, " + name);

Output The variable System.out represents the output stream, that is, normally the terminal. You can send strings to the output stream by using the print or println methods. If print (or println) has a non- string argument, that value is converted to a string before printing. The concatenation operation, '+' can be used to put strings together, e.g. System.out.println( " The total of " + a + " and " + b + " is " + (a + b)); Note that the parenthesis around " a+b " are necessary, otherwise a and b are each converted to strings.

Input The variable System.in represents standard input, that is, normally the keyboard. You can use the a Scanner object to read in and set variables easily. To create a Scanner object, you must specify where to read the input from. For example, to read in two ints from standard input: import java.util.Scanner; // inside main method: Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); will read in two int s and store them in a and b.

Exercise Write a Java program that will prompt the user for a temperature (in Fahrenheit) and then convert that temperature to Celsius and print out the new temperature along with a text message. You will need: A double variable, f, to represent the Fahrenheit temperature A double variable, c, to represent the Celsius temperature

Exercise (cont'd) An output line to print out the prompt message An input line to read in the Fahrenheit temperature A line to calculate and store the Celsius temperature c = (f ­ 32) * 5/9. A line to print out the result.

Printing Numbers Floating point numbers are printed out in some default format, which is usually not how you want them to print out. For example, if you want to print out dollars and cents: double price = 78.50; System.out.println( " Price is $ " + price); You might see Price is $78.5

Formatting Numbers If that's not what you want, you can use the DecimalFormat class. The following commands tell the computer to use a fixed format (rather than scientific notation), to always show the decimal point, and to show two digits to the right of the decimal point: import java.text.DecimalFormat; public static void main(String args[]) { DecimalFormat myFormat = new DecimalFormat( " ###.## " ); System.out.println(myFormat.format(price)); }

Formatting Patterns ###,###.###123, The pound sign (#) denotes a digit, the comma is a placeholder for the grouping separator, and the period is a placeholder for the decimal separator ###.## The value has three digits to the right of the decimal point, but the pattern has only two. The format method handles this by rounding up The pattern specifies leading and trailing zeros, because the 0 character is used instead of the pound sign (#) $###,###.###$12, The first character in the pattern is the dollar sign ($). Note that it immediately precedes the leftmost digit in the formatted output.

Comments Comments are human-readable lines of text which can be used to document your program. The computer ignores comments. There are two ways to indicate a comment. Two slashes ( " // " ) indicate that everything that follows them until the end of the line is a comment. A block of text is treated as a comment if it begins with " /* " and ends with " */ ".

Example Comments /* This program was written by Don Simon on 01/15/2010 for the COSC 160 class */ import java.util.Scanner; //scanner

Documentation Standards For this class, each program should have the following documentation: Author's name, date, name of program Short program description Description of each variable (if not obvious) Each function and method should have a short description, including the inputs and outputs Description of major sections of code Details of any tricky (non-obvious) code

Documentation Standards (cont'd) The idea is that some one who reads the code should understand what is going on. The comments should not mimic the code, that is, restate the code in English, but should provide the gist of what each major section of code does. For example: a = a + 1; // add 1 to a. is not an appropriate comment, but /* Read in the students' test scores and find the average */ is.

Libraries The Java system is divided into a core language and a set of APIs (application programming interface). The APIs provide additional functionality. One of the commonly used APIs contains the Scanner class. Another, DecimalFormat has functions for manipulating how things are printed out. To use an API, you must have an import line near the top of your program to load the API classes: import java.util.Scanner; import java.text.DecimalFormat;

Arithmetic Expressions As noted before, you can use arithmetic operators in expressions to manipulate numeric values: a + b * 7 – (b + 3) There is an order of precedence which determines which operators are done first: First *, /, and % are performed, and then + and -. Two arithmetic operators of the same precedence are done from left to right. Parentheses can be used to change the order.

Relational Operators There are also operators which compare values and return true or false. For example “ a < b ” returns true if a is less than b and false otherwise. These are called relational operators:  == equals  != not equal to  < less than  > greater than  <= less than or equal to  >= greater than or equal to

Boolean Expressions We can combine simple relational tests together into more complex expressions using Boolean operators. Boolean operators work on logical (or Boolean) values ( true, false ) and return true and false. The common operators are:  && and  || or  ! not Example: 0 <= a && a <= 10 // a is between 0 and 10 incl.

Boolean Expressions (cont'd) More examples: 0 < a || 0 < b // a is greater than 0 // or b is greater than 0. !(a > 5) // a is not greater than 5. Note that 0 <= a <= 10 is not a valid expression.

Truth Tables

Order of Precedence

Order of Precedence (cont'd)

Short-Circuit Evaluation The Boolean operators && and || are evaluated using short-circuit evaluation. That is, if you have the expression (a > b) && (b > c), and it turns out that a is not greater than b (so a > b is false), then there is no need to evaluate b > c (since the whole expression is going to be false anyway). Similarly, if you evaluate (a > b) || (b > c) and a is greater than b, then the expression is true, so b > c is not evaluated.

If-Else Statements An If-Else statements allows the program to execute one section of the program if a Boolean expression is true, and a different section, if that Boolean expression is false. This is called conditional evaluation and allows the program to do different things given different inputs.

If-Else Example if (a > b) System.out.println(a); else System.out.println(b); If a is greater than b, then then first line is executed and the value of a is printed out. Otherwise, the second line is executed and the value of b is printed.

If-Else Statement Syntax The syntax for an If-Else statement is: if ( ) else

Compound Statements If you want to do more than one statement if an IF- else case, you can form a block of statements, or compound statement, by enclosing the list of statements in curly braces ({ }). The statements in side of the braces will be executed sequentially, and the block counts as one statement.

Compound Statement Example if (a > b) { c = a; System.out.println(a); } else { c = b; System.out.println(b); }

Exercise Write a program that reads in two integers and then prints out the smaller of the two followed by the larger of the two. You will need to: Prompt the user to type in two ints Read in the two ints Compare the two ints, and then depending on which is larger, print them out in the right order.