Variables, Constants, and Data Types



Similar documents
Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

CS 106 Introduction to Computer Science I

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Chapter 1: Computer Systems

Chapter 2: Elements of Java

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Pemrograman Dasar. Basic Elements Of Java

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Introduction to Java. CS 3: Computer Programming in Java

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

C++ Language Tutorial

Introduction to Visual C++.NET Programming. Using.NET Environment

Java Basics: Data Types, Variables, and Loops

So far we have considered only numeric processing, i.e. processing of numeric data represented

Number Representation

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Outline Basic concepts of Python language

Conditionals (with solutions)

Moving from CS 61A Scheme to CS 61B Java

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

CS106A, Stanford Handout #38. Strings and Chars

Introduction to Java

Example of a Java program

Chapter 3. Input and output. 3.1 The System class

J a v a Quiz (Unit 3, Test 0 Practice)

Chapter 2 Introduction to Java programming

Lecture 1 Introduction to Java

Programming in Java Course Technology, a part of Cengage Learning.

Informatica e Sistemi in Tempo Reale

AP Computer Science Java Subset

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Lecture 5: Java Fundamentals III

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Chapter 4: Computer Codes

Introduction to Java Lecture Notes. Ryan Dougherty

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Regular Expression Syntax

Introduction to Python

Text Processing In Java: Characters and Strings

Chapter One Introduction to Programming

Chapter 2 Elementary Programming

VB.NET Programming Fundamentals

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Java CPD (I) Frans Coenen Department of Computer Science

PL / SQL Basics. Chapter 3

6.170 Tutorial 3 - Ruby Basics

Java Interview Questions and Answers

Chapter 7D The Java Virtual Machine

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

2 ASCII TABLE (DOS) 3 ASCII TABLE (Window)

Explain the relationship between a class and an object. Which is general and which is specific?

A list of data types appears at the bottom of this document. String datetimestamp = new java.sql.timestamp(system.currenttimemillis()).

Chapter 2 Basics of Scanning and Conventional Programming in Java

Building Java Programs

Building Java Programs

1 Introduction. 2 An Interpreter. 2.1 Handling Source Code

Programming and Data Structures with Java and JUnit. Rick Mercer

Some Scanner Class Methods

ASCII Code. Numerous codes were invented, including Émile Baudot's code (known as Baudot

Java programming for C/C++ developers

Java Crash Course Part I

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

Practical Session 4 Java Collections

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

ECE 122. Engineering Problem Solving with Java

Install Java Development Kit (JDK) 1.8

An Introduction to Computer Science

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

csce4313 Programming Languages Scanner (pass/fail)

Programming Project 1: Lexical Analyzer (Scanner)

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Ecma/TC39/2013/NN. 4 th Draft ECMA-XXX. 1 st Edition / July The JSON Data Interchange Format. Reference number ECMA-123:2009

Java Programming Fundamentals

Chapter 1 Java Program Design and Development

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Passing 1D arrays to functions.

Numeral Systems. The number twenty-five can be represented in many ways: Decimal system (base 10): 25 Roman numerals:

TCP/IP Networking, Part 2: Web-Based Control

Sample CSE8A midterm Multiple Choice (circle one)

Solution for Homework 2

ASSEMBLY LANGUAGE PROGRAMMING (6800) (R. Horvath, Introduction to Microprocessors, Chapter 6)

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

Primitive data types in Java

Numbering Systems. InThisAppendix...

Iteration CHAPTER 6. Topic Summary

Introduction to Programming

Finding XSS in Real World

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

Transcription:

Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class: L&L, 2.1-2.3, App C 1

Primitive Data There are eight primitive data types in Java Four of them represent integers: byte, short, int, long Two of them represent floating point numbers: float, double One of them represents characters: char And one of them represents boolean values: boolean 2

Numeric Primitive Data The difference between the various numeric primitive types is their size, and therefore the values they can store: Type Storage Min Value Max Value byte short int long 8 bits 16 bits 32 bits 64 bits -128-32,768-2,147,483,648 < -9 x 10 18 127 32,767 2,147,483,647 > 9 x 10 18 float double 32 bits 64 bits +/- 3.4 x 10 38 with 7 significant digits +/- 1.7 x 10 308 with 15 significant digits 3

Boolean Primitive Data A boolean value represents a true or false condition The reserved words true and false are the only valid values for a boolean type boolean done = false; A boolean variable can represent any two states such as a light bulb being on or off boolean ison = true; 4

Variables A variable is a name for a location in memory A variable must be declared by specifying the variable's name and the type of information that it will hold data type variable name int total; Multiple variables can be created in one declaration: int count, temp, result; 5

Variable Initialization A variable can be given an initial value in the declaration with an equals sign int sum = 0; int base = 32, max = 149; When a variable is referenced in a program, its current value is used See PianoKeys.java (page 66-67) int keys = 88; System.out.println( A piano has + keys + keys. ); Prints as: A piano has 88 keys. 6

Assignment An assignment statement changes the value of a variable The equals sign is also the assignment operator total = 55; The expression on the right is evaluated and the result is stored as the value of the variable on the left The value previously stored in total is overwritten You can only assign a value to a variable that is consistent with the variable's declared type See Geometry.java (page 68) 7

Constants A constant is an identifier that is similar to a variable except that it holds the same value during its entire existence As the name implies, it is constant, not variable In Java, we use the reserved word final in the declaration of a constant final int MIN_HEIGHT = 69; Any subsequent assignment statement with MIN_HEIGHT on the left of the = operator will be flagged as an error 8

Constants Constants are useful for three important reasons First, they give meaning to otherwise unclear literal values For example, NUM_STATES means more than the literal 50 Second, they facilitate program maintenance If a constant is used in multiple places and you need to change its value later, its value needs to be updated in only one place Third, they formally show that a value should not change, avoiding inadvertent errors by other programmers 9

Characters A char variable stores a single character Character literals are delimited by single quotes: 'a' 'X' '7' '$' ',' '\n' Example declarations: char topgrade = 'A'; char terminator = ';', separator = ' '; 10

Character Sets A character set is an ordered list of characters, with each character corresponding to a unique number A char variable in Java can store any character from the Unicode character set The Unicode character set uses sixteen bits per character, allowing for 65,536 unique characters It is an international character set, containing symbols and characters from many world languages 11

Characters The ASCII character set is older and smaller than Unicode, but is still quite popular (in C programs) The ASCII characters are a subset of the Unicode character set, including: uppercase letters lowercase letters punctuation digits special symbols control characters A, B, C, a, b, c, period, semi-colon, 0, 1, 2, &,, \, carriage return, tab,... 12

Character Strings A string of characters can be represented as a string literal by putting double quotes around the text: Examples: "This is a string literal." "123 Main Street" "X" Note the distinction between a primitive character X, which holds only one character, and a String object, which can hold a sequence of one or more characters Every character string is an object in Java, defined by the String class 13

The println Method In the Lincoln program from Chapter 1, we invoked the println method to print a character string The System.out object represents a destination (the monitor screen) to which we can send output System.out.println ("Whatever you are, be a good one."); object method name information provided to the method (parameters) 14

The print Method The System.out object provides another method The print method is similar to the println method, except that it does not start the next line Therefore any parameter passed in a call to the print method will appear on the same line See Countdown.java (page 59) System.out.print ( Three ); System.out.print ( Two ); Prints as: Three Two 15

String Concatenation The string concatenation operator (+) is used to append one string to the end of another "Peanut butter " + "and jelly" It can also be used to append a number to a string A string literal cannot be broken across two lines in a program so we must use concatenation See Facts.java (page 61) System.out.println( We present the following facts for your + extracurricular edification ); NOTE: No ; here 16

String Concatenation The + operator is also used for arithmetic addition The function that it performs depends on the type of the information on which it operates If both operands are strings, or if one is a string and one is a number, it performs string concatenation If both operands are numeric, it adds them The + operator is evaluated left to right, but parentheses can be used to force the order See Addition.java (page 62) System.out.println( 24 and 45 concatenated: + 24 + 45); Prints as: 24 and 45 concatenated: 2445 17

String Concatenation The + operator is evaluated left to right, but parentheses can be used to force the order See Addition.java (page 62) System.out.println( 24 and 45 added: + (24 + 45)); Prints as: 24 and 45 added: 69 Then concatenation is done Addition is Done first 18

Escape Sequences What if we want to include the quote character itself? The following line would confuse the compiler because it would interpret the two pairs of quotes as two strings and the text between the strings as a syntax error: System.out.println ("I said "Hello" to you."); A String Syntax Error A String An escape sequence is a series of characters that represents a special character Escape sequences begin with a backslash character (\) System.out.println ("I said \"Hello\" to you."); A String 19

Escape Sequences Some Java Escape Sequences Escape Sequence Meaning \b \t \n \r \" \' \\ backspace tab newline carriage return double quote single quote backslash See Roses.java (page 64) System.out.println( Roses are red,\n\tviolets are blue,\n + Prints as: Roses are red, Violets are blue, 20

Escape Sequences To put a specified Unicode character into a string using its code value, use the escape sequence: \uhhhh where hhhh are the hexadecimal digits for the Unicode value Example: Create a string with a temperature value and the degree symbol: double temp = 98.6; System.out.println( Body temperature is + temp + \u00b0f. ); Prints as: Body temperature is 98.6 ºF. 21

Methods of the String class String is a class and classes can have methods. Use the Sun website link to find definitions of the methods for each standard library class The classes are listed in alphabetical order The String class has methods that can be used to find out the characteristics of a String object such as its length: System.out.println( Hello.length()); Prints the number 5 (for 5 characters in length) 22