Programming Languages Machine language Assembly language High-level languages The Java language.

Slides:



Advertisements
Similar presentations
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Advertisements

Primitive Data Types There are a number of common objects we encounter and are treated specially by almost any programming language These are called basic.
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.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
CMT Programming Software Applications
Data types and variables
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Chapter 2 Data Types, Declarations, and Displays
JavaScript, Third Edition
Introduction to C Programming
String Escape Sequences
CSE 1301 J Lecture 2 Intro to Java Programming Richard Gesick.
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Chapter 2 Programming Building Blocks — Java Basics.
Objectives You should be able to describe: Data Types
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)
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.
1 Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
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.
2440: 211 Interactive Web Programming Expressions & Operators.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
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?
CSE 1301 Lecture 2 Data Types Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Input, Output, and Processing
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 2 Basic Elements of Java.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
CHAPTER 4 GC 101 Data types. DATA TYPES  For all data, assign a name (identifier) and a data type  Data type tells compiler:  How much memory to allocate.
© 2004 Pearson Addison-Wesley. All rights reserved ComS 207: Programming I Instructor: Alexander Stoytchev
Chapter 2 Variables.
CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
C++ for Engineers and Scientists Second Edition
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
CHAPTER 4 GC 101 Identifiers and Data types. 2 IDENTIFIERS  identifier: A name given to a piece of data, method, etc.  Identifiers allow us to refer.
1Object-Oriented Program Development Using C++ Built-in Data Types Data type –Range of values –Set of operations on those values Literal: refers to acceptable.
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.  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.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
Lecture 2A Data Types Richard Gesick
Chapter 2 Variables.
Identifiers - symbolic names
Lecture 2 Data Types Richard Gesick.
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
OBJECT ORIENTED PROGRAMMING I LECTURE 3 GEORGE KOUTSOGIANNAKIS
Multiple variables can be created in one declaration
Identifiers - symbolic names
Java Programming: From Problem Analysis to Program Design, 4e
Escape Sequences What if we wanted to print the quote character?
IDENTIFIERS CSC 111.
Introduction to C++ Programming
Chapter 2 Variables.
elementary programming
Programming Building Blocks Java Basics
Chapter 2: Introduction to C++.
Introduction to Java Applications
Java Basics Data Types in Java.
Unit 3: Variables in Java
Chapter 2 Variables.
Chapter 2 Primitive Data Types and Operations
Instructor: Alexander Stoytchev
Presentation transcript:

Programming Languages Machine language Assembly language High-level languages The Java language

Machine & Assembly Languages Machine language –Written using CPU instruction set –Difficult to write, and not portable Assembly language –Written using mnemonics for instructions and symbolic names for variables –Assembler converts code to machine language –Easier to write, but still not portable

High-Level Languages Examples: Fortran, Perl, COBOL, C++, Java Highly symbolic Portable among CPU architectures Languages can be designed for specific uses: –Perl: Internet applications –Fortran: scientific applications –COBOL: business applications

High-Level Languages Compiled –Compiler converts source code (instructions and data) into machine language, then program is executed Interpreted –Interpreter converts instructions into machine language at run time as instructions are executed –Usually executes more slowly than compiled program

Java Combination of compiler and interpreter Compiler converts source code into byte codes (an instruction set for a virtual, machine-independent processor) At run time, the Java Virtual Machine (JVM) interprets the byte codes and converts them into the machine language on which the program is running.

Object-oriented Programming (OOP) Class –tool for encapsulating data and operations (methods) into one package –defines a template or model for creating and manipulating objects Objects –data created using the class and its methods –an object is an instance of the class –creating an object is instantiation

The Java Language Created by Sun Microsystems in 1995 Syntax based on C++ Object-oriented Support for Internet applications Extensive library of prewritten classes Portability among platforms Built-in networking

Java Basics Java Application Structure Data Types, Variables, and Constants Expressions and Arithmetic Operators

Java Application Structure All programs consist of at least one class. The Java source code file must have same name as class with.java extension. public class Hello { public static void main(String [] args) { System.out.println("Hello World"); }

Identifiers - symbolic names Identifiers are used to name classes, variables, and methods Identifier Rules: –Must start with a "Java letter" A - Z, a - z, _, $, and Unicode letters –Can contain essentially any number of Java letters and digits, but no spaces –Case sensitive!! Number1 and number1 are different! –Cannot be keywords or reserved words See Appendix A

Program Building Blocks The Statement –Performs some action –Terminates with a semicolon (;) –Can span multiple lines

Building Blocks - The Block The Block –0, 1, or more statements –Begins and ends with curly braces { } –Can be used anywhere a statement is allowed.

Building Blocks - White Space Space, tab, newline are white space characters At least one white space character is required between a keyword and identifier Any amount of white space characters are permitted between identifiers, keywords, operators, and literals

To increase readability of your code, surround operators and operands with white space and skip lines between logical sections of program

Building Blocks - Comments Comments explain the program to yourself and others Block comments –Can span several lines –Begin with /* –End with */ –Compiler ignores all text between /* and */ Line comments –Start with // –Compiler ignores text from // to end of line

Include a block comment at the beginning of each source file –identify the author of the program –briefly describe the function of the program

Data Types, Variables, and Constants Declaring Variables Primitive Data Types Initial Values and Literals String Literals and Escape Sequences Constants

Data Types For all data, assign a name (identifier) and a data type Data type tells compiler: –How much memory to allocate –Format in which to store data –Types of operations you will perform on data Compiler monitors use of data – Java is a "strongly typed" language Java "primitive data types" byte, short, int, long, float, double, char, boolean

Declaring Variables Variables hold one value at a time, but that value can change Syntax: dataType identifier; or dataType identifier1, identifier2, …; Naming convention for variable names: –first letter is lowercase –embedded words begin with uppercase letter

Names of variables should be meaningful and reflect the data they will store –(“self-documenting variable names”) –This makes the logic of the program clearer Don't skimp on characters, but avoid extremely long names Avoid names similar to Java keywords

Integer Types - Whole Numbers Type Size Minimum Value Maximum Value in Bytes byte short 2 -32,768 32,767 int 4 -2, 147, 483, 648 2, 147, 483, 647 long 8 -9,223,372,036,854,775,808 9,223,372,036,854,775,807 Example declarations: int testGrade; int numPlayers, highScore, diceRoll; short xCoordinate, yCoordinate; byte ageInYears; long cityPopulation;

Floating-Point Data Types Numbers with fractional parts Type Size Minimum Value Maximum Value in Bytes float 4 1.4E E38 double 8 4.9E E308 Example declarations: float salesTax; double interestRate; double paycheck, sumSalaries;

char Data Type One Unicode character (16 bits - 2 bytes) Type Size in Bytes char 2 Example declarations: char finalGrade; char newline, tab, doubleQuotes;

boolean Data Type Two values only: true false Used for decision making or as "flag" variables Example declarations: boolean isEmpty; boolean passed, failed;

Assigning Values to Variables Assignment operator = –Value on the right of the operator is assigned to the variable on the left –Value on the right can be a literal (text representing a specific value), another variable, or an expression (explained later) Syntax: dataType variableName = initialValue; Or dataType variable1 = initialValue1, variable2 = initialValue2, …;

Literals int, short, byte Optional initial sign (+ or -) followed by digits 0 – 9 in any combination. long Optional initial sign (+ or -) followed by digits 0–9 in any combination, terminated with an L or l. ***Use the capital L because the lowercase l can be confused with the number 1.

Floating-Point Literals float Optional initial sign (+ or -) followed by a floating-point number in fixed or scientific format, terminated by an F or f. double Optional initial sign (+ or -) followed by a floating-point number in fixed or scientific format.

Commas, dollar signs, and percent signs (%) cannot be used in integer or floating- point literals

char and boolean Literals char –Any printable character enclosed in single quotes –A decimal value from 0 – – '\m', where \m is an escape sequence. For example, '\n' represents a newline, and '\t' represents a tab character. boolean true or false See Example 2.2 Variables.java

Assigning the Values of Other Variables Syntax: dataType variable2 = variable1; Rules: 1. variable1 needs to be defined before this statement appears in the source code 2. variable1 and variable2 need to be compatible data types; in other words, the precision of variable1 must be lower than or equal to that of variable2.

Sample Assignments This is a valid assignment: float salesTax =.05f; double taxRate = salesTax; This is invalid because the float data type is lower in precision than the double data type: double taxRate =.05; float salesTax = taxRate;

String Literals String is actually a class, not a basic data type; String variables are objects String literal: text contained within double quotes. Example of String literals: "Hello" "Hello world" "The value of x is "

String Concatenation Operator (+) Combines String literals with other data types for printing Example: String hello = "Hello"; String there = "there"; String greeting = hello + ' ' + there; System.out.println( greeting ); Output is: Hello there

Common Error Trap String literals must start and end on the same line. This statement: System.out.println( "Never pass a water fountain without taking a drink" ); generates these compiler errors: unclosed string literal ')' expected Break long Strings into shorter Strings and use the concatenation operator: System.out.println( "Never pass a water fountain" + " without taking a drink" );

Escape Sequences To include a special character in a String, use an escape sequence Character Escape Sequence Newline \n Tab \t Double quotes \" Single quote \' Backslash \\ Backspace \b Carriage return \r Form feed \f See Example 2.3 Literals.java

Declare a variable only once Once a variable is declared, its data type cannot be changed. These statements: double twoCents; double twoCents =.02; generate this compiler error: twoCents is already defined

Once a variable is declared, its data type cannot be changed. These statements: double cashInHand; int cashInHand; generate this compiler error: cashInHand is already defined

Constants Value cannot change during program execution Syntax: final dataType constantIdentifier = assignedValue; Note: assigning a value when the constant is declared is optional. But a value must be assigned before the constant is used. See Example 2.4 Constants.java

Use all capital letters for constants and separate words with an underscore: Example: final double TAX_RATE =.05; Declare constants at the top of the program so their values can easily be seen Declare as a constant any data that should not change during program execution

Expressions and Arithmetic Operators The Assignment Operator and Expressions Arithmetic Operators Operator Precedence Integer Division and Modulus Shortcut Operators

Assignment Operator Syntax: target = expression; expression: operators and operands that evaluate to a single value --value is then assigned to target --target must be a variable (or constant) --value must be compatible with target's data type

Examples: int numPlayers = 10; // numPlayers holds 10 numPlayers = 8; // numPlayers now holds 8 int legalAge = 18; int voterAge = legalAge; The next statement is illegal int height = weight * 2; // weight is not defined int weight = 20; and generates the following compiler error: illegal forward reference

Arithmetic Operators OperatorOperation +addition -subtraction *multiplication /division %modulus (remainder after division)

Operator Precedence OperatorOrder of evaluation Operation ( )left - rightparenthesis for explicit grouping * / %left - rightmultiplication, division, modulus + -left - rightaddition, subtraction =right - leftassignment

Example You have 2 quarters, 3 dimes, and 2 nickels. How many pennies are these coins worth? int pennies = 2 * * * 5; = = 90

Another Example Translate x into Java: 2y // incorrect! double result = x / 2 * y; => x * y 2 // correct double result = x / ( 2 * y );

Integer Division & Modulus When dividing two integers: –the quotient is an integer –the remainder is truncated (discarded) To get the remainder, use the modulus operator with the same operands

Shortcut Operators ++ increment by 1 -- decrement by 1 Example: count++; // count = count + 1; count--; // count = count - 1; Postfix version ( var++, var-- ): use value of var in expression, then increment or decrement. Prefix version ( ++var, --var ): increment or decrement var, then use value in expression

More Shortcut Operators OperatorExampleEquivalent +=a += 3;a = a + 3; -=a -= 10;a = a - 10; *=a *= 4;a = a * 4; /=a /= 7;a = a / 7; %=a %= 10;a = a % 10;

Common Error Trap No spaces are allowed between the arithmetic operator and the equals sign Note that the correct sequence is +=, not =+ Example: add 2 to a // incorrect a =+ 2; // a = +2; assigns 2 to 2 // correct a += 2; // a = a + 2;