The Java Language Rules And Tools 3

Similar documents
Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

2 rd class Department of Programming. OOP with Java Programming

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Programming Lecture 3

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Full file at

Program Fundamentals

CMPT 125: Lecture 3 Data and Expressions

Computer Components. Software{ User Programs. Operating System. Hardware

CS112 Lecture: Primitive Types, Operators, Strings

The Java Language The Java Language Reference (2 nd ed.) is the defining document for the Java language. Most beginning programming students expect

JOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Basics of Java Programming

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Lecture 2 Tao Wang 1

Computer Components. Software{ User Programs. Operating System. Hardware

The MaSH Programming Language At the Statements Level

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

Lexical Considerations

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Visual C# Instructor s Manual Table of Contents

3. Java - Language Constructs I

Java Identifiers. Java Language Essentials. Java Keywords. Java Applications have Class. Slide Set 2: Java Essentials. Copyright 2012 R.M.

COMP 202 Java in one week

Getting started with Java

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

1 Lexical Considerations

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Lexical Considerations

Data Types and Variables in C language

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Maciej Sobieraj. Lecture 1

Chapter 2 Basic Elements of C++

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

For the course, we will be using JCreator as the IDE (Integrated Development Environment).

UNIT- 3 Introduction to C++

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

INTRODUCTION 1 AND REVIEW

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

The C++ Language. Arizona State University 1

Standard 11. Lesson 9. Introduction to C++( Up to Operators) 2. List any two benefits of learning C++?(Any two points)

Exercise: Using Numbers

printf( Please enter another number: ); scanf( %d, &num2);

CPS122 Lecture: From Python to Java

Accelerating Information Technology Innovation

Variables. Data Types.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Language Fundamentals Summary

LECTURE 02 INTRODUCTION TO C++

An overview of Java, Data types and variables

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

BASIC ELEMENTS OF A COMPUTER PROGRAM

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

Java Notes. 10th ICSE. Saravanan Ganesh

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Basic data types. Building blocks of computation

Programming in C++ 4. The lexical basis of C++

IT 374 C# and Applications/ IT695 C# Data Structures

FRAC: Language Reference Manual

Language Reference Manual

ARG! Language Reference Manual

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

Basic Types, Variables, Literals, Constants

REVIEW. The C++ Programming Language. CS 151 Review #2

Decaf Language Reference Manual

CS112 Lecture: Working with Numbers

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

C: How to Program. Week /Mar/05

Full file at

CSc Introduction to Computing

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types

Lesson 2A Data. Data Types, Variables, Constants, Naming Rules, Limits. A Lesson in Java Programming

Chapter 2: Introduction to C++

Program Elements -- Introduction

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Objectives. In this chapter, you will:

Java Basic Datatypees

4 Programming Fundamentals. Introduction to Programming 1 1

Full file at C How to Program, 6/e Multiple Choice Test Bank

Sprite an animation manipulation language Language Reference Manual

Creating a C++ Program

Chapter 2: Programming Concepts

2 nd Week Lecture Notes

COMP6700/2140 Data and Types

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Chapter. Focus of the Course. Object-Oriented Software Development. program design, implementation, and testing

3. Simple Types, Variables, and Constants

Transcription:

The Java Language Rules And Tools 3 Course Map This module presents the language and syntax rules of the Java programming language. You will learn more about the structure of the Java program, how to insert comments into your code, and how to use various data storage types. Introduction Computer Principles and Components Software Development Language Rules and Constructs The Java Language Rules and Tools Simple Java Programming Constructs Advanced Java Programming Constructs Objects, Arrays, and Methods Object Orientation Methods Arrays Advanced Object Orientation 3-1

Relevance Present the following questions to stimulate the students and get them thinking about the issues and topics presented in this module. They are not expected to know the answers to these questions. The answers to these questions should be of interest to the students and inspire them to learn the contents of this module. Discussion The following questions highlight the areas that will be covered in this module: How do you store values in your programs? What sort of values can you store? Are objects the only things you can use? 3-2 Java Programming for Non-Programmers

Objectives Upon completion of this module, you should be able to: Use comments to document your code Use the Java technology primitive data storage types Use primitive literal values The Java Language Rules And Tools 3-3

The Primary Components of a Java Program Recap As was stated in Module 2, Java programs consist of the following: Classes A class is the programming structure used to group variables and methods together. Classes are written in source-code files. The Java runtime environment uses them to build objects while the program is executing. Those objects are used at runtime to store and manipulate data. Classes are the templates used to build objects. The variables and methods in classes, model ideas or concepts within the problem. You write and use as many classes within a program as there are concepts within the problem. You try to make them represent those concepts that are relevant to your world or paradigm, such as Cat, Door, Table, and so on. The classes you write will depend on the problem you want to solve and on your world (that is, the extents within which the problem lies). 3-4 Java Programming for Non-Programmers

The Primary Components of a Java Program Recap Objects Objects are the entities you build when you run your programs. Use them to store and manipulate the data required to solve your problem. The data is stored in variables within the objects and is manipulated by methods. Variables You use variables to store data values inside objects. Each time you build an object you put values into the data variables to represent that individual object. The variables are called attributes or members of that object. If the class models a cat then one variable may be a text string to store the cat s name. One object built from that class may have a name value of Kevin and another object a value of Duncan, representing the different cats Kevin and Duncan respectively. Methods Methods are sequences of Java technology statements ( Java statements ) that perform a discrete task on (or service of) the class. Withdrawing money from an Account object, for example, could be a method. The Java Language Rules And Tools 3-5

Programming Rules And Tools Before you can learn much more of the actual structure of the Java programming language, or of the art of programming, there are certain rules and tools you must understand. These are listed here and will be explained in more detail throughout the rest of this module. The Java programming language is case sensitive. supports comments for documenting your programs. is a free-format language, so you can lay out the code within your program file any way that is appropriate or logical. allows you to give various elements of your code names (also known as identifiers ) so you can refer to them appropriately and logically. 3-6 Java Programming for Non-Programmers

Programming Rules And Tools has certain words (called keywords or reserved words ) that have meaning and so cannot be used as identifiers. allows you to store values within your programs as variables (which can be changed) and constants (which cannot). has variables and constants that must be given a type, either one of a series of primitive types or a reference to an object. has data type rules governing usage and how you must enter values. has naming conventions for variables, classes, and so on, so you can recognize from the name what it represents. The Java Language Rules And Tools 3-7

Case Sensitivity Case sensitivity means distinguishing between the upper- and lowercase representations of each alphabetical character. Java technology source-code files ( Java source-code files ) are, like those of all languages, written using actual words and numbers. You cannot use just any words you want from the language when you program the compiler only understands a few of them (keywords) and it is your responsibility to use those few correctly. The Java programming language demands that all keywords are written entirely in lower case. For example, one of the few keywords we have seen so far is class. The compiler would not understand this if you wrote Class or CLASS or any other representation. A complete list of keywords appears in Table 3-1 on page 3-16. The case sensitivity of the Java programming language also applies to identifiers. If you create a variable called cat then you cannot refer to it later as Cat. 3-8 Java Programming for Non-Programmers

Java Components This section covers the main components of the Java programming language ( Java components ). Comments You now know that the Java programming language understands only certain words, known as keywords. Anything else you wish to include in your source code must be marked for humans only so that the compiler will ignore it. The sorts of things we would want to insert into the files are descriptions of a concept, reasons and explanations for doing something, meta-data such as update history, and so on. This ability for the compiler to ignore certain text is achieved by delimiting those lines with certain character combinations: Single-line comments A // marker tells the compiler to ignore everything to the end of the current line. For example: // This is a single-line comment. The Java Language Rules And Tools 3-9

Java Components Comments (Continued) Multiple-line comments A /* character combination tells the compiler to ignore everything on all lines up to, and including, a comment termination marker ( */ ). For example: /* This comment spans across more than one line. */ 3-10 Java Programming for Non-Programmers

Java Components Statements, Codeblocks, and Whitespace Java programs are composed of classes, attributes and methods. Methods are a series of statements, each statement being a small, logical action taken towards the overall action of the method. In the Java programming language statements always end with a semicolon ( ; ). The extent of a code structure (a class or method, for example) is marked with braces ( { and } ). Groups of Java statements placed between such braces are called code blocks. Some of the Java programming language commands ( Java commands ) used to control the flow of a program from one statement to another can be enhanced using such code blocks. A code block is syntactically equivalent to a single statement. You can put a code block anywhere you can put a statement. Braces are needed to enclose classes and methods. The Java Language Rules And Tools 3-11

Java Components Statements, Codeblocks, and Whitespace (Continued) Whitespace is the term used to describe those characters included within source code that do not influence the program at all but simply enhance its appearance. Because Java is a free-format programming language you could put all the statements of a program onto a single line, or spread one statement over several. Both of these techniques make the code difficult to read and understand, and therefore to maintain. A well structured code block has its braces lined up vertically on lines of their own, and each statement within it indented by a consistent number of spaces. For example: 1 { 2 i = 6 + 9; 3 j = i - 3; 4 } 3-12 Java Programming for Non-Programmers

Java Components Identifiers Identifier refers to the names of variables, methods, and so on. Each class has an identifier, as do methods and variables. The following rules dictate the content and structure of identifiers: The first character of an identifier must be one of the following: An uppercase letter (A-Z) A lowercase letter (a-z) The underscore character (_) The dollar character ($) The Java Language Rules And Tools 3-13

Java Components Identifiers (Continued) The second and subsequent characters of an identifier must be Any character from the above list Numeric characters (0-9) It is not permitted under any circumstances to use a Java keyword or reserved word as an identifier. These are listed in Table 3-1 on page 3-16. Note There are other characters that can be added to the second list above, including any accented characters from other languages. These are dictated by the Java programming language. Later in this module you will see some naming conventions that you should adhere to in order to control the look of identifiers. These conventions have been developed for and are used throughout the Java programming language itself. 3-14 Java Programming for Non-Programmers

Java Components Keywords and Reserved Words All languages have keywords, including the languages we use to communicate with each other, and in all cases there are certain words which are not allowed as names. For example, naming children The, Because, and Often would cause a great deal of confusion, not just for the children but also for the people they met throughout their lives. Keywords make sense to the compiler when they are used in the correct order (called the syntax of the language) and cause confusion when used incorrectly. The fact that computer languages have a much smaller set of keywords than natural languages makes them less flexible and the parsers in compilers therefore enforce the rules much more strictly than people do. The Java Language Rules And Tools 3-15

Java Components Keywords and Reserved Words (Continued) Natural languages also have reserved words. These are terms which are not truly part of the language but do get used in some places and cannot be used for names. In our language we refer to them as slang. There are some surprising members in this group, common words that we use without thinking. Hello, for example, is a word that was invented just a few years after the telephone it was deemed important to have a neutral word that could act as a greeting before you actually knew to whom you were talking. It is officially slang, but is also a good example of how these words can make their way into the accepted part of the language. Table 3-1 contains all the Java programming language keywords ( Java keywords ) and reserved words. While only a few of these will be described during this course, they must not be used as identifiers for classes, methods, variables, and so on. Table 3-1 Java Keywords and Reserved Words abstract default goto null synchronized boolean do if package this break double implements private throw byte else import protected throws case extends instanceof public transient catch false int return true char final interface short try class finally long static void const float native super volatile continue for new switch while 3-16 Java Programming for Non-Programmers

Java Components Variables and Constants The CPU and associated support chips are considered the workforce of the computer. These chips have a series of storage places (called registers ) in which they can store and manipulate the values that make up the program. There are not many of these registers in any computer, certainly not enough to provide one for each piece of information you will ever need. You therefore need to be able to store your values somewhere else and retrieve them as quickly as possible. The RAM fulfills this purpose. Each statement that manipulates a value within a program starts by transferring that information to a register and ends by putting it back into RAM. The Java Language Rules And Tools 3-17

Java Components Variables and Constants (Continued) There are two ways to treat the values stored in RAM: Variables The values put into variables can be changed at any time. Constants The values put into constants cannot be changed (values such as pi, for example). Registers are numbered by the CPU. Bytes within the RAM area are also numbered or addressed. You can give variables and constants identifiers to make them more meaningful and memorable in code, rather than using numeric addresses everywhere. 3-18 Java Programming for Non-Programmers

Java Components Java Primitive And Reference Types This section covers Java technology primitive types ( Java primitive types ) and Java technology reference types ( Java reference types ). The Java programming language rules dictate that you give each variable and constant a type. A variable s type restricts the values you can put into that variable. Some can only store whole numbers (integers) while others can store decimal places as well (floating point numbers). There are others for storing character information and true/false logical values. These are all primitives and make up the simple data parts of the Java programming language. When you create objects you store them in a separate part of memory, but you need to remember the address of where they were created. Reference variables are used to hold the addresses of objects. The Java Language Rules And Tools 3-19

Java Components Java Primitive And Reference Types (Continued) The eight primitive types (plus the reference type) are listed below and are explained in the rest of this module: byte short int long float double char boolean reference The reference type will be explained in more detail in References on page 29 in this module. To assign a type to a variable you declare the variable. A declaration statement has the form: int myfirstvariable; You can put a value into the variable using the = (assignment) operator: myfirstvariable = 27; Now you can use the variable name anywhere that you need to use the value you have stored there. 3-20 Java Programming for Non-Programmers

Java Primitive Types Integral Types There are four integral Java programming language types ( Java types ), with the corresponding keywords byte, short, int and long. The characteristics of each are as follows: Each type comprises a whole numbers of bytes; a byte is one byte long, a short is two bytes long, int is four bytes long, and a long is eight bytes long. That means that a short can hold numbers twice as long as a byte, anint can hold numbers twice as long as a short, and so on. Whole numbers can be either positive or negative. The sign of a value is held in the left-most bit; a 1 in this bit suggests a negative number while a 0 suggests a positive value. The Java Language Rules And Tools 3-21

Java Primitive Types Integral Types Continued) This explains why there isn t a number range of +/- 128. There is more to making a number negative than putting a 1 in the leftmost bit; the computer uses a format called 2 s-complement that permits simple arithmetic of positive and negative values. With seven bits for the number there are 2 to the power of 7 (128) values in the range for both positive and negative numbers. Zero is counted as positive so the range is -128 through +127. So, if you need to count up to 100, for example, a variable of type byte would suffice because we know from the specification that it can cope with values in that range. Table 3-2 lists all the integral types, their sizes and the range of possible values Table 3-2 Integral Types Integer Length Name or Type Range 8 bits byte -2 7... 2 7-1 16 bits short -2 15... 2 15-1 32 bits int -2 31... 2 31-1 64 bits long -2 63... 2 63-1 Note The most efficient of these is the int. This will be explained better in the section in this module titled Literal Values on page 32. You should use int for integer types during this course. 3-22 Java Programming for Non-Programmers

Java Primitive Types Floating Point Types There are two types for floating point numbers, float and double. As with the different integer types, these share functionality but differ in size. Table 3-3 Floating Point Types Float Length Name or Type 32 bits float 64 bits double The Java Language Rules And Tools 3-23

Java Primitive Types Floating Point Types (Continued) It is not possible to state the largest or smallest value that each of these can hold as they conform to a standard that allows variable accuracy depending on the magnitude of the number. The Java programming language has two pre-defined constants to denote the extents of the types, called POSITIVE_INFINITY and NEGATIVE_INFINITY. You can create floating point variables by using the type name in a declaration: double myfirstfloatingpoint; Now you can store values in this variable using the assignment operator again: myfirstfloatingpoint = 27.999; You can also use the engineering notation for very large numbers, where the E can be either upper- or lowercase. myfirstfloatingpoint = 2.7999E10; Note The double type is the most efficient of these. This will be explained better in the section in this module titled Literal Values on page 32. During this course you should use the double type for all floating point values. 3-24 Java Programming for Non-Programmers

Java Primitive Types Textual Types Another data type you need to be able to store and manipulate is character information. The primitive type used for storing a single character is char. Please note that you can only store one character in a char variable. If you want to store whole words or phrases you use an object type called String. This will be discussed later. Character variables are declared as shown in this example: char myfirstcharacter; The Java Language Rules And Tools 3-25

Java Primitive Types Textual Types (Continued) You can store values in such variables with the assignment operator. The values you store must be single characters and must be placed within single quotes ( ). These quotes convert what would be considered a one-character identifier such as g into the character value g. myfirstcharacter = g ; Variables of the char type can store any value from the Java technology character set ( Java character set ). Most computer languages use ASCII (the American Standard Code for Information Interchange), an 8-bit character set that has an entry for every English character and punctuation mark, numbers, and so on. The Java programming language uses a 16-bit character set called Unicode that can store all the necessary displayable characters from the vast majority of languages used in the modern world. Your programs can therefore be written so they will work and display the correct language for almost any country in the world. 3-26 Java Programming for Non-Programmers

Java Primitive Types Logical Types One of the things you will need to do most often in your programs is to make a decision. These decisions must equate to one of two values: yes/no, on/off, true/false, and so on. The type used to store such values is the boolean, named after the Irish mathematician George Boole who is considered the early computer pioneer responsible for formalizing the decision-based logic for computing. The two values that boolean variables can store in the Java programming language are true and false. These are keywords and therefore have special meaning to the JVM. You do not need to know what the values actually are, just that a boolean variable can hold one of the two values. For example: boolean myfirstboolean; myfirstboolean = true; The Java Language Rules And Tools 3-27

Java Primitive Types Logical Types (Continued) This is perhaps the most difficult type of variable to understand, or at least understand the need for it. Remember that the CPU only stores information for the statement it is currently working on, so everything relating to a previous statement has been lost. If you know that you will need the outcome of some choice later then you must store that decision using the boolean type. 3-28 Java Programming for Non-Programmers

References Overview Use reference variables to store the addresses of objects. Remember that objects are large pieces of memory that hold functionality as well as data. Objects represent discrete items from the problem you are attempting to solve. The rules of the integer type state that they cannot hold values that have anything after the decimal point. The rules of references state that they can store only the address of objects of their own type. A reference declared to store the address of a Computer object could not be used to hold the address of a User. For example, the declaration of a Computer reference variable would be: Computer laptop; The Java Language Rules And Tools 3-29

References Overview (Continued) You use the name of the class as the type in the declaration. You now have a variable called laptop that can store the address of a Computer object. To create objects, use the new keyword: laptop = new Computer(); Reference variables act the same as the eight primitive types when you assign values to them. For example: int first = 9; int second = first; Computer laptop = new Computer(); Computer anotherreferencetolaptop = laptop; The first two lines create an integer called first and use it to store the number 9, then create another integer called second and use it to store a copy of first. If the contents of first are later changed this does not automatically change second. The third line creates a reference called laptop and stores the address of a new Computer object in it. The last line creates another reference, called anotherreferencetolaptop, and gives it a copy of the address of the Computer object as stored in laptop. It does not duplicate the object but copies the address; there are now two references to one Computer. 3-30 Java Programming for Non-Programmers

References Strings You now know how to store single characters in char variables, but what if you want to store words or sentences instead? For this you use the String class. You also know now how to create objects from classes, using the new keyword. For a String this would look like the following example: String animal = new String("walrus"); Strings are unique among all object classes because they are the only class you can build objects from without needing to use the new keyword. The syntax for this version is: String variable = "string_value"; Example: String animal = "walrus"; The Java Language Rules And Tools 3-31

Literal Values All the types mentioned so far in this module have literal values; that is, values that are typed directly into programs and used immediately by the compiler. In fact, when the compiler does find a literal value, it puts it into the class file with a note to the JVM that the value should be treated as an unnamed constant. Given that the compiler is storing these values as unnamed constants, then they must all have a type. The type governs what you can and cannot do with literals. 3-32 Java Programming for Non-Programmers

Literal Values Integer Literals The following line: int num32 = 27; involves a literal value (27). Whenever the compiler finds a wholenumber literal such as 27 it creates an anonymous constant of type int to store it in. The assignment operator above is therefore putting an int value into an int variable, which is permitted. Consider the following statement, however: byte num8 = 27; The Java Language Rules And Tools 3-33

Literal Values Integer Literals (Continued) The compiler creates a variable called num8 which is of type byte (that is, one byte long). It then creates an anonymous int variable (4 bytes long) and gives it the value 27. When the compiler attempts to squeeze the 32-bit value into 8 bits of space it checks to see if the 3 bytes it is about to discard are important (that is, if they contain anything other than 0s). In this case they are all 0s, so the assignment will work. Now consider the following statement: byte num8 = 128; This time the 3 bytes of the literal int 128 which have to be discarded do contain a 1, so the compiler will declare an error. The code is attempting what is called demotion, implicitly assuming the compiler would permit you to reduce the size of a value from int to byte. Demotion is not allowed under any circumstances. A similar error is created when assigning literal values to short variables and the value is outside the range for a short. You can explicitly request that the compiler reduce the size of a literal value using the cast syntax. If you put a type keyword in parentheses immediately in front of a value, that value is converted to the type. For example: byte num8 = (byte)27; int num32 = 27; byte num8a = (byte)num32; There are problems with casting down to bytes and shorts, however. Consider the following lines int num32 = 257; byte num8 = (byte)num32; 3-34 Java Programming for Non-Programmers

Literal Values Integer Literals (Continued) You may be surprised that num8 now contains the value 1. A demoting cast simply cuts off the left end of the value until it is the right size to fit into the variable, as the following binary images show: 257 as 32 bits: 00000000000000000000000100000001 cast to 8 bits: 00000001 Promotion takes a value and makes it larger. Promotion does not need a cast, it is automatic and pads out the beginning of a value with zeros. Promotion permits you to store literal values in variables of type long. For example: long num64 = 27; Alternatively you can append an L to the end of the number, forcing the compiler to store it as an unnamed 64 bit constant. You can use either an upper- or lowercase letter for this but uppercase is preferred because a lowercase L looks very much like a 1 (one) in most fonts. long num64 = 27L; The Java Language Rules And Tools 3-35

Literal Values Floating Point Literals Floating point numbers also have literal values. These values can be written in one of a number of ways, including engineering notation. For example, the following are all valid floating point literal values: 27.9 279E5 27.9E6 It is valid to use integer literals when assigning values to floating point numbers and is considered another form of promotion: float fp32 = 27; double fp64a = 27; double fp64b = 27L; 3-36 Java Programming for Non-Programmers

Literal Values Floating Point Literals (Continued) Just as integer literals default in size to int, floating point literals default to double. For example, the following line will cause a compiler error: float fpoint32 = 27.9; Creating a 32-bit variable and then demoting a 64-bit value into it is not possible under any circumstances. Either cast the literal or immediately append it with an f or F character to suggest float-size: float fpoint32a = (float)27.9; float fpoint32b = 27.9F; The Java Language Rules And Tools 3-37

Literal Values Character Literals A character literal is a single character within single quotes. For example: a Z @ Any character that can be typed at the keyboard can be stored in a char variable using a character literal. But what about formatting characters such as carriage-return or tab? If you type either of those in a text editor, the text editor responds to them rather than making them a literal within the file itself. There is a series of special character literals in the Java programming language for the usual formatting characters of the Unicode set. They are all formatted as a backslash character ( \ ) plus one other character, both inside one set of single quotes. Table 3-4 lists some of the more common formatting characters. 3-38 Java Programming for Non-Programmers

Literal Values Character Literals (Continued) Table 3-4 Common Formatting Character Literals \t \r \n tab carriage return newline Any printable character from the Unicode character set that does not appear on your keyboard can be specified using the \u1234 sequence, where 1234 is the hexadecimal Unicode value of the character. The Java Language Rules And Tools 3-39

Literal Values boolean Literals boolean variables have two literal values: true and false. These are keywords and must therefore be spelled using lowercase letters. Reference Literals Reference variables can only be set by using the new keyword: Computer laptop = new Computer(); or by assigning a value from another reference variable: Computer anotherlaptopreference = laptop; You cannot specify an absolute address for an object in the Java programming language. 3-40 Java Programming for Non-Programmers

Literal Values Reference Literals (Continued) There is one literal reference value. It is often necessary to make an existing reference variable stop pointing to an object. The reference to use when a variable must point to nothing is null. Computer noobject = null; The Java Language Rules And Tools 3-41

Literal Values String Literals Strings are objects, not primitives. Objects do not have associated literal values, except for String objects. String animal = "walrus"; Anything in double quotes is a String object literal. One character in double quotes is a short String ("a"). The shortest String of all is just a pair of double quotes (""). If you need to state that a String reference does not refer to a String object, you assign it the null reference. 3-42 Java Programming for Non-Programmers

Naming Conventions Sun has devised a set of naming conventions that help to standardize the look and feel of Java code. They are based on the fact that an identifier must be an unbroken stream of characters that may include several words to give them more meaning. The following list describes the conventions for the four most common identifiers: Class names Class names are written as a sequence of descriptive words (usually nouns and adjectives) where each word joins onto the next, and each word starts with an uppercase letter and continues in lowercase: class ClassOne {} class MyPetRhinoceros {} Variable Names Variable names follow the same rules as class names but the phrase begins with a lowercase letter: int variableone; String myfirstreferencevariable; The Java Language Rules And Tools 3-43

Naming Conventions Constant Names Constant names have uppercase letters for all the words in the phrase and underscore characters ( _ ) between each word: final int CONSTANT_ONE = 27; final double PI = 3.141592654; Note Constants are declared in the same way as variables but preceded by the final keyword. Method Names Methods follow the same format and style as variables except the phrase usually contains a verb structure and always ends with a pair of parentheses. The parentheses are not part of the name but part of the method-calling mechanism. int methodone() {} void printtheresults() {} 3-44 Java Programming for Non-Programmers

Check Your Progress Before continuing on to the next module, check that you are able to accomplish or answer the following: Use comments to document your code Use the Java primitive data storage types Use primitive literal values The Java Language Rules And Tools 3-45

Think Beyond If you want your program to run intelligently, how do you get it to make decisions to take different actions depending on the outcome of different tests? 3-46 Java Programming for Non-Programmers