1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.

Slides:



Advertisements
Similar presentations
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
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.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
©2004 Brooks/Cole Chapter 2 Variables, Values and Operations.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
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
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
String Escape Sequences
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.
L EC. 02: D ATA T YPES AND O PERATORS (1/2) Fall Java Programming.
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.
Chapter 2: Introducing Data Types and Operators.  Know Java’s primitive types  Use literals  Initialize variables  Know the scope rules of variables.
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: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
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.)
JAVA Tokens. Introduction A token is an individual element in a program. More than one token can appear in a single line separated by white spaces.
Sahar Mosleh California State University San MarcosPage 1 A for loop can contain multiple initialization actions separated with commas Caution must be.
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.
Java Structure import java_packages; class JavaClass { member variables declarations; void otherMethod( ) { } public static void main(String[]
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Lec 6 Data types. Variable: Its data object that is defined and named by the programmer explicitly in a program. Data Types: It’s a class of Dos together.
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.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
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.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Copyright Curt Hill Variables What are they? Why do we need them?
Chapter 2 Variables.
Java Programming, Second Edition Chapter Two Using Data Within a Program.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CSI 3125, Preliminaries, page 1 Data Type, Variables.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
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.
© 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.
Chapter 2 Variables.
Chapter 4 Assignment Statement
Chapter 7: Expressions and Assignment Statements
Java Primer 1: Types, Classes and Operators
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Chapter 7: Expressions and Assignment Statements
Multiple variables can be created in one declaration
Chapter 3 Assignment Statement
Java Programming: From Problem Analysis to Program Design, 4e
Starting JavaProgramming
Chapter 2: Basic Elements of Java
Chapter 2 Variables.
Expressions and Assignment
Chap 2. Identifiers, Keywords, and Types
Chapter 2 Variables.
Chapter 2 Primitive Data Types and Operations
Review of Java Fundamentals
Presentation transcript:

1 Chapter 4 Language Fundamentals

2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers. Java, like all languages, has rules that govern identifiers. The compiler generates errors on invalid identifiers.

3 Identifiers A valid identifier must begin with a letter, an underscore ( _ ), or a dollar sign ( $ ). The remaining characters must be letters, numerals, underscores, or dollar signs. Because compiler-generated identifiers typically include the dollar sign, the programmer typically does not use this symbol.

4 Variables A variable is a named storage cell that can hold a value of a particular type. A variable must be declared before used. A declaration provides the name, which must be a valid identifier, and the data type together with any attributes such as public. A sample is int n; // n is the name, int the type

5 Variables Variables occur as class fields and as local variables in constructors and methods. Fields have default values. For example, integer fields default to 0, floating-point fields to 0.0, and Boolean fields to false. –Object references default to the special value null.

6 Local variables Local variables, unlike fields, do not have default values. A local variable’s value must be set before using the variable, for example, in a function call or as the source of an assignment operation. A variable can be declared final to mark the variable as a constant.

7 Constructors and methods All Java functions are encapsulated as either constructors or methods. A constructor has the same name as its encapsulating class and no return type or void in place of a return type. For instance, a Date constructor would have the name Date.

8 Constructors and methods Constructors are used with the new operator to construct instances of a class. The statement Date today = new Date(); illustrates. Constructors are typically overloaded; that is, a class typically has several constructors.

9 Constructors and methods A method does not have the same name as its encapsulating class and has either a return type or void in place of a return type. Methods define the operations appropriate to a class and its instances.

10 Constructors and methods A constructor cannot be static, but a method can be static. Constructors and methods can be parameterized. The parameter names and data types must be provided. Methods, like constructors, can be overloaded but must be distinguished by their names and/or parameter types.

11 Primitive types Java has standard class types such as Date and standard nonclass or primitive types such as int and double. Integer types have fixed bit sizes and ranges. For instance, a byte is 8 bits, its minimum value is -128, and its maximum value is +127.

12 Integer types The integer types (with bit sizes in parentheses) are byte (8), short (16), int (32), and long (64). All integer types are signed and have 2’s complement internal representation. An integer constant such as 12 is of type int, whereas 12L and 12l are of type long.

13 Integer types A decimal constant must not begin with a 0. An octal constant begins with a 0 and a hexadecimal constant begins with 0x or 0X. The java.math package has a BigInteger class for arbitrary-precision integer arithmetic.

14 Floating-point types The floating-point types are float (32 bits) and double (64 bits). A floating-point constant such as 3.14 is of type double, whereas 3.14F and 3.14f are of type float. The floating-point types follow the IEEE 754 floating-point standard.

15 Cast operations The code segment float f = 3.14; //*** ERROR is in error because it tries to assign a double value to a float variable. The problem can be corrected in several ways, including a cast operation float f = (float) 3.14; // ok

16 Cast operations In a cast operation, the target type is enclosed in parentheses. Java imposes restrictions on casts. For example, a boolean value such as true cannot be cast to any other type, and no nonboolean value can be cast to boolean. Casts should be used with great caution.

17 Arithmetic operators Java supports the usual arithmetic operations: addition ( + ), subtraction ( - ), multiplication ( * ), division ( / ), and remainder ( % ). The arithmetic operators apply to integer and floating-point operands. Java also provides bit and shift operators for integers.

18 Assignment operators The symbol = is the basic assignment operator. Java also provides special assignment operators such as +=, *=, and the like. –The code segment int x = 4; x *= 6; // x is 24 illustrates.

19 Character type The char is based on 16-bit Unicode characters. Character literals are placed in single quotes. For instance, ‘A’ is a character literal that could be assigned to a char variable. Special characters such as ‘\n’ (newline) begin with a backslash.

20 Character type Arithmetic and relational operations can be performed on characters. The code segment char c1 = ‘A’, char c2 = c1 + 1; // ‘B’ if ( c2 > c1 ) // true... illustrates.

21 Boolean type The boolean type has two values, true and false. Boolean values are not integer values. Boolean values cannot be cast. Boolean expressions are used in if statements, loops, and relational expressions.

22 Relational operators Java has the standard relational operators for comparing values: greater than ( > ), less than ( = ), less than or equal to ( <= ), equals ( == ), and not equals ( != ). The equality operator should be used with caution on floating-point values and object references.

23 Logical operators Java has the standard logical operators: and ( && ), inclusive-or ( || ), and not ( ! ). Evaluation of a logical-and expression terminates with a value of false at the first false subexpression. Evaluation of a logical-or expression terminates with a value of true at the first true subexpression.

24 Logical operators Logical expressions evaluate left to right. The bit operators & and | behave as logical operators if their operands are boolean s instead of integers.

25 instanceof operator This operator tests whether an object instantiates a class. The code segment Date d = new Date(); if ( d instanceof Object ) // false... else if ( d instanceof Date ) // true... illustrates.

26 Arrays Arrays of primitive and class types are supported. Arrays are fixed size. Arrays constructed with new int[ ] nums = new int[ 100 ]; have their elements initialized to the appropriate default value (e.g., 0 for numbers and false for Booleans).

27 Arrays Arrays can be initialized in their declarations. The code segment int[ ] nums = { 1, 2, 3 }; illustrates. “Multidimensional” arrays are supported: int[ ][ ] nums = new int[ 2 ][ 4 ];

28 Arrays All arrays have a convenient length member: int[ ] nums1 = new int[ 10 ]; int n1 = nums1.length; // 10 int[ ][ ] nums2 = new int[ 2 ][ 4 ]; int n2 = nums2.length; // 2 int n3 = nums2[ 0 ].length // 4

29 Arrays A “multidimensional” array is really an array of arrays. For instance, int[ ][ ] nums = new int[ 2 ][ 4 ]; is an array of two elements, each of which is an array of four int s.

30 Arrays The Java compiler does not perform bounds checking on array accesses: int[ ] nums = new int[ 10 ]; nums[ -1 ] = 999; // compiles The Java runtime throws an exception if an array index is out of bounds.

31 Blocks A block is sequence of instructions enclosed in curly braces. Variables declared inside a block have block scope; that is, such variables are visible only within their containing block. Name conflicts among local variables are not allowed; hence, local variables with the same name must occur in different blocks.

32 Loops Java provides three loop constructs: while, do while, and for. The while and do while are suited for conditional loops, and the for loop is suited for counted loops. Any loop construct can be rewritten in principle with one of the other loop constructs.

33 Loops The while loop int i = 0; final int n = 100; while ( i < n ){ System.out.println( i ); i = i + 1; } prints 0,1,…,99.

34 Loops The do while loop int i = 0; final int n = 100; do { System.out.println( i ); i = i + 1; } while ( i < n; } prints 0,1,…,99.

35 Loops The for loop final int n = 100; for ( int i = 0; i < n; i++ ) System.out.println( i ); prints 0,1,…,99. In a for loop, the three clauses are the initialization, the loop condition, and the post-body expression.

36 Exceptions An exception is an unexpected condition that arises during a program’s execution. –For instance, a program might inadvertently divide an integer by zero, which would cause or “throw” an exception. Exception handling is a mechanism for handling exceptions.

37 Exceptions The runtime environment implicitly throws an exception whenever a program violates some condition such as trying to open a nonexistent file or dividing an integer by zero. A program can explicitly throw an exception with the throw statement.

38 Exceptions Code that might throw exceptions is placed in a try block: try { FileInputStream in = new FileInputStream( “in.dat” ); //*** remaining code } catch( IOException e ) { /*...*/ }

39 Exceptions A try block is followed by one or more catch blocks, which represent the exception handlers, or by a finally block, whose code executes regardless of whether an exception is thrown in the corresponding try block.

40 Exceptions Exceptions provide a concise, disciplined mechanism for handling unexpected conditions during a program’s execution. Constructors and methods in the standard classes rely heavily upon exception handling.