Java Variables and Types

Slides:



Advertisements
Similar presentations
Introduction to Computing Concepts Note Set 7. Overview Variables Data Types Basic Arithmetic Expressions ▫ Arithmetic.
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.
Introduction to Programming with Java, for Beginners Primitive Types Expressions Statements Variables Strings.
©2004 Brooks/Cole Chapter 2 Variables, Values and Operations.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
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.
JavaScript, Fourth Edition
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
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.
CSCI 1100/1202 January 16, Why do we need variables? To store intermediate results in a long computation. To store a value that is used more than.
The Data Element. 2 Data type: A description of the set of values and the basic set of operations that can be applied to values of the type. Strong typing:
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
2440: 211 Interactive Web Programming Expressions & Operators.
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 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.
CPS120: Introduction to Computer Science
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs.
BASICS CONCEPTS OF ‘C’.  C Character Set C Character Set  Tokens in C Tokens in C  Constants Constants  Variables Variables  Global Variables Global.
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.
SE-1010 Dr. Mark L. Hornick 1 Variables & Datatypes.
Primitive Variables.
CONSTANTS Constants are also known as literals in C. Constants are quantities whose values do not change during program execution. There are two types.
Copyright Curt Hill Variables What are they? Why do we need them?
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
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[]
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.
CPS120: Introduction to Computer Science Variables and Constants.
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.
Types Chapter 2. C++ An Introduction to Computing, 3rd ed. 2 Objectives Observe types provided by C++ Literals of these types Explain syntax rules for.
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
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.  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.
Fundamentals 2.
Chapter 2 Variables.
String Comparison, Scanner
Identifiers - symbolic names
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
ITEC113 Algorithms and Programming Techniques
Data Types, Identifiers, and Expressions
Multiple variables can be created in one declaration
Data types and variables
Switch, Rounding Errors, Libraries
Identifiers - symbolic names
Java Programming: From Problem Analysis to Program Design, 4e
IDENTIFIERS CSC 111.
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Chapter 2 Edited by JJ Shepherd
Chapter 2 Variables.
Chapter 2: Java Fundamentals
Chapter 2: Java Fundamentals
Chapter 2: Introduction to C++.
Primitive Types and Expressions
Chapter 2 Variables.
Presentation transcript:

Java Variables and Types CMSC 131 Object-Oriented Programming I Java Variables and Types Dept of Computer Science University of Maryland College Park This material is based on material provided by Ben Bederson, Bonnie Dorr, Fawzi Emad, David Mount, Jan Plane

Variables What is a variable? The name of some location of memory used to hold a data value Different types of data require different amounts of memory. The compiler’s job is to reserve sufficient memory Variables need to be declared once Variables are assigned values, and these values may be changed later Each variable has a type, and operations can only be performed between compatible types Example int width = 3; int height = 4; int area = width * height; width = 6; area = width * height; height area width 3 4 12 3 4 12 width 6 height 24 area

Variable Names Valid Variable Names: These rules apply to all Java names, or identifiers, including methods and class names Starts with: a letter (a-z or A-Z), dollar sign ($), or underscore (_) Followed by: zero or more letters, dollar signs, underscores, or digits (0-9). Uppercase and lowercase are different (total ≠ Total ≠ TOTAL) Cannot be any of the reserved names. These are special names (keywords) reserved for the compiler. Examples: class, float, int, if, then, else, do, public, private, void, …

Good Variable Names Choosing Good Names Not all valid variable names are good variable names Some guidelines: Do not use `$’ (it is reserved for special system names.) Avoid names that are identical other than differences in case (total, Total, and TOTAL). Use meaningful names, but avoid excessive length crItm  Too short theCurrentItemBeingProcessed  Too long currentItem Just right Camel case capitalization style In Java we use camel case Variables and methods start with lower case dataList2 myFavoriteMartian showMeTheMoney Classes start with uppercase String JOptionPane MyFavoriteClass

Valid/Invalid Identifiers $$_ R2D2 INT okay. “int” is reserved, but case is different here _dogma_95_ riteOnThru SchultzieVonWienerschnitzelIII Invalid: 30DayAbs starts with a digit 2 starts with a digit pork&beans `&’ is illegal private reserved name C-3PO `-’ is illegal

Primitive Data Types Java’s basic data types: Integer Types: byte 1 byte Range: -128 to +127 short 2 bytes Range: roughly -32 thousand to +32 thousand int 4 bytes Range: roughly -2 billion to +2 billion long 8 bytes Range: Huge! Floating-Point Types (for real numbers) float 4 bytes Roughly 7 digits of precision double 8 bytes Roughly 15 digits of precision Other types: boolean 1 byte {true, false} (Used in logic expressions and conditions) char 2 bytes A single (Unicode) character String is not a primitive data type (they are objects)

Numeric Constants (Literals) Specifying constants: (also called literals) for primitive data types. Integer Types: byte short optional sign and digits (0-9): 12 -1 +234 0 1234567 int long Same as above, but followed by ‘L’ or ‘l’: -1394382953L Floating-Point Types: double Two allowable forms: Decimal notation: 3.14159 -234.421 0.0042 -43.0 Scientific notation: (use E or e for base 10 exponent) 3.145E5 = 3.145 x 105 = 314500.0 1834.23e-6 = 1834.23 x 10-6 = 0.00183423 float Same as double, but followed by ‘f’ or ‘F’: 3.14159F -43.2f Avoid this lowercase L. It looks too much like the digit ‘1’ Note: By default, integer constants are int, unless ‘L’/‘l’ is used to indicate they are long. Floating constants are double, unless ‘F’/‘f’ is used to indicate they are float.

Character and String Constants char constants: Single character enclosed in single quotes (‘…’) including: letters and digits: ‘A’, ‘B’, ‘C’, …, ‘a’, ‘b’, ‘c’, …, ‘0’, ‘1’, …, ‘9’ punctuation symbols: ‘*’, ‘#’, ‘@’, ‘$’ (except single quote and backslash ‘\’) escape sequences: (see below) String constants: Zero or more characters enclosed in double quotes (“…”) (same as above, but may not include a double quote or backslash) Escape sequences: Allows us to include single/double quotes and other special characters: \” double quote \n new-line character (start a new line) \’ single quote \t tab character \\ backslash Examples: char x = ’\’’  (x contains a single quote) ”\”Hi there!\””  ”Hi there!” ”C:\\WINDOWS”  C:\WINDOWS System.out.println( ”Line 1\nLine 2” ) prints Line 1 Line 2

Data Types and Variables Java  Strongly-type language Strong Type Checking  Java checks that all expressions involve compatible types int x, y; // x and y are integer variables double d; // d is a double variable String s; // s is a string variable boolean b; // b is a boolean variable char c; // c is a character variable x = 7; // legal (assigns the value 7 to x) b = true; // legal (assigns the value true to b) c = ‘#’; // legal (assigns character # to c) s = “cat” + “bert”; // legal (assigns the value “catbert” to s) d = x – 3; // legal (assigns the integer value 7 – 3 = 4 to double d) b = 5; // illegal! (cannot assign int to boolean) y = x + b; // illegal! (cannot add int and boolean) c = x; // illegal! (cannot assign int to char)

Numeric Operators Arithmetic Operators: Unary negation: -x Multiplication/Division: x * y x/y Division between integer types truncates to integer: 23/4  5 x % y returns the remainder of x divided by y: 23%4  3 Division with real types yields a real result: 23.0/4.0  5.75 Addition/Subtraction: x+y x-y Comparison Operators: Equality/Inequality: x == y x != y Less than/Greater than: x < y x > y Less than or equal/Greater than or equal: x <= y x >= y These comparison operators return a boolean value: true or false.

Common String Operators String Concatenation: The ‘+’ operator concatenates (joins) two strings. “von” + “Wienerschnitzel”  “vonWienerschnitzel” When a string is concatenated with another type, the other type is first evaluated and converted into its string representation (8*4) + “degrees”  “32degrees” (1 + 2) + “5”  “35” String Comparison: Strings should not be compared using the above operators (==, <=, <, etc). Let s and t be strings. s.equals(t)  returns true if s equals t s.length()  returns length s.compareTo(t)  compares strings lexicographically (dictionary order) result < 0 if s is less than t result == 0 if s is equal to t result > 0 if s is greater than t Note: Concatenation does not add any space

Examples Let’s take a look at some examples See code distribution