Java Fundamentals Expanded SE1021 Dr. Mark L. Hornick 1.

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Advertisements

Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example F Identifiers, Variables, and Constants F Primitive Data Types –byte,
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
1 Chapter 3 Arithmetic Expressions. 2 Chapter 3 Topics l Overview of Java Data Types l Numeric Data Types l Declarations for Numeric Expressions l Simple.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
22-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Agenda Review User input Scanner Strong type checking Other flow-control structures switch break & continue Strings Arrays 2.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Chapter 2: Introducing Data Types and Operators.  Know Java’s primitive types  Use literals  Initialize variables  Know the scope rules of variables.
Java Building Elements Lecture 2 Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung University
Chapter 12 – Type Details and Alternate Coding Mechanisms Primitive Data Types Integer Types Floating-Point Types BigInteger and BigDecimal BigInteger.
1 Chapter 11 – Type Details and Alternate Coding Mechanisms Primitive Data Types Integer Types Floating-Point Types char Type ASCII Table Unicode Standard.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
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.
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?
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
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.
Chapter 12 – Type Details and Alternate Coding Mechanisms Primitive Data Types Integer Types Floating-Point Types BigInteger and BigDecimal BigInteger.
Chapter 11 – Type Details and Alternate Coding Mechanisms Primitive Data Types Integer Types Floating-Point Types char Type ASCII Table Unicode Standard.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
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.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
1 Operations Making Things Happen (Chap. 3) Expressions.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
Java Programming, Second Edition Chapter Two Using Data Within a Program.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
1 Lecture 5 More Programming Constructs Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
Variables and Types Java Part 3. Class Fields  Aka member variable, field variable, instance variable, class variable.  These are the descriptors of.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
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.
LESSON 5 – Assignment Statements JAVA PROGRAMMING.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Programming Principles Operators and Expressions.
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Primitive Data Types and Operations F Introduce Programming with an Example F Identifiers, Variables, and Constants F Primitive Data Types –byte, short,
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.
Chapter 2 Basic Computation
Multiple variables can be created in one declaration
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 2 Basic Computation
Chapter 2.
IDENTIFIERS CSC 111.
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Chapter 2: Basic Elements of Java
Fundamentals 2.
Expressions and Assignment
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Primitive Types and Expressions
Chapter 2 Primitive Data Types and Operations
Presentation transcript:

Java Fundamentals Expanded SE1021 Dr. Mark L. Hornick 1

2 In Java, there are two basic categories of datatypes – primitives and classes Let's review primitive datatypes and cover them in more detail: byte, short, int, long float, double char boolean 1

3 The Integer Types To access a data type's minimum and maximum values, use the MIN_VALUE and MAX_VALUE named constants that come with the datatype's wrapper class. For example: System.out.println("Largest int = " + Integer.MAX_VALUE); TypeStorage Req’d Wrapper Class's MIN_VALUE Wrapper Class's MAX_VALUE byte 8 bits short 16 bits int 32 bits  -2 billion  2 billion long 64 bits  -9*10 18  9*10 18

4 The default integer literal constant datatype is int That is, a literal value like 123 is an int To explicitly force an integer constant to be a long, use an l or L suffix Thus, 123L is a long Examples: long ageOfPlanet = ; // compiler error! long ageOfPlanet = L; // OK

5 The Floating-Point datatypes – float and double For double s, the number of significant digits is approximately 15. For float s, the number of significant digits is approximately 6. Normally, the double type is preferred over the float type because the double type provides more accuracy as well as greater range TypeStoragePrecision Wrapper Class's MIN_NORMAL Wrapper Class's MAX_VALUE float 32 bits 6-9 digits  1.2 *  3.4*10 38 double 64 bits digits  2.2 *  1.8*10 308

6 A floating-point data type's minimum and maximum values are defined via the MIN_NORMAL and MAX_VALUE named constants Note that a floating-point MIN_NORMAL is qualitatively different from an integer MIN_VALUE. Instead of being the largest-magnitude negative value, it's the smallest-magnitude positive value. For floating-point numbers, if you want the largest-magnitude negative value, use the negation operator (-) with the MAX_VALUE named constant. For example, here's how to print the largest- magnitude negative float value: System.out.println( "Largest-magnitude negative float = " + -Float.MAX_VALUE);

7 The default floating-point literal constant datatype is double That is, a literal value like is a double If you declare a variable to be a float, you must append an f or F suffix to all floating-point constants that go into it, like this: float gpa1 = 3.22f; // OK float gpa2 = 2.75F;// OK float gpa3 = 4.0;// error!!

8 The char datatype For most languages (including Java), character values have an underlying numeric value. For example, the letter 'A' has the underlying value of 65. For most languages, the ASCII table specifies the underlying numeric values for characters.

9 The ASCII Table

10 What's the point of having an underlying numeric value? A: So characters can be ordered (e.g., 'A' comes before 'B' because A's 65 is less than B's 66). Character ordering is necessary so characters (and strings) can be sorted.

11 You can concatenate a char value to a String using the + operator Example: char first = ‘J'; char last = 'D'; System.out.println("Hello, " + first + last + '!'); When the JVM sees a String next to a + sign, it converts the operand on the other side of the + sign to a String, and then concatenates the Strings. Q: What mechanism does the JVM use to convert the non-String operand to a String?

12 Be wary of applying the + operator to two chars The + operator does not perform concatenation; instead, it performs mathematical addition using the characters' underlying ASCII values char first = 'J'; char last = 'D'; System.out.println(first + last + ", What's up?"); // result is: 142, What's up? The intended output is: JD, What's up? Q: How can you fix the code?

13 Java is a strongly-typed language Each variable and each value within a Java program must be defined to have a particular datatypes, but statements within a program can often mix datatypes. Example: int x = 3; // int double y = x; // mixing double and int How? Through datatype conversions. Conversions are only allowed for numeric types, not booleans.

14 Primitive datatype Conversions The ordering scheme for primitive datatype conversions: narrowerwider byteshortintlongfloatdouble char This diagram illustrates what datatypes “fit inside” other datatypes: A “narrower” datatype can “fit inside” a “wider” datatype.

15 There are two types of conversion: Promotion and Type casting Promotion: A promotion = an implicit conversion it's when an operand's type is automatically converted without having to use a typecast operator. It occurs when there's an attempt to use a narrower type in a place that expects a wider type it occurs when you’re going with the flow of the arrows in the previous diagram.

16 Examples of Promotions For each statement, what happens in terms of promotion? long x = 44; float y = x; double z = ; int num = 'f' + 5; With a mixed expression, the narrower operand(s) is promoted to match the type of the wider operand. These are mixed expressions. Mixed expressions contain operands of different data types.

17 Promotions typically occur as part of assignment statements, mixed expressions, and method calls. Here's a method call example. public class MethodPromotion { public static void main(String[] args) { float x = 4.5f; printSquare(x); // x is a float! printSquare(3); // 3 is an int! } private static void printSquare(double num) { System.out.println(num * num); } } // end class MethodPromotion

18 Type casting = an explicit type conversion. It's when an expression's type is (forcibly) converted by using a cast operator. It's legal to use a cast operator to convert any numeric type to any other numeric type the conversion can go in either direction in the previous "ordering scheme" diagram. Syntax: ( ) double x = ; int y = (int) x; // result in y??

19 Example from p 444 import java.util.*; public class PrintCharFromAscii { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); int asciiValue; // user entered ASCII value char ch; // the asciiValue's associated character char nextCh; // the character after ch in the ASCII table System.out.print("Enter an integer between 0 and 127: "); asciiValue = stdIn.nextInt(); ch = (char) asciiValue; nextCh = (char) (asciiValue + 1); System.out.println("Entered number: " + asciiValue); System.out.println("Associated character: " + ch); System.out.println("Next character: " + nextCh); } // end main } // end class PrintCharFromAscii

20 There are two different modes for the ++ increment operator – prefix and postfix. Prefix mode: ++x  increment x before x's value is used Example: y = ++x;  x = x + 1; y = x; Postfix mode: x++  increment x after x's value is used Example: y = x++;  y = x; x = x + 1;

21 Trace this code fragment int x, y; x = 4; y = ++x; System.out.println(x + " " + y); x = 4; y = x++; System.out.println(x + " " + y);

22 Decrement operators work the same as increment operators …except that subtraction is performed instead of addition. Trace this code fragment: int a, b, c; a = 8; b = --a; c = b a; System.out.println(a + " " + b + " " + c);

23 Assignment expressions are sometimes embedded inside larger expressions int a, b = 8, c = 5; a = b = c; System.out.println(a + " " + b + " " + c); When that happens, remember that: An assignment expression evaluates to the assigned value. The assignment operator exhibits right-to-left associativity. In the interest of compactness, it's fairly common to embed an assignment expression inside a loop condition. For example: while ((score = stdIn.nextDouble()) != -1)

24 Conditional operator expressions implement if else logic using a more compact form Syntax: ? : Semantics: If the condition is true, then the conditional operator expression evaluates to the value of expression1. If the condition is false, then the conditional operator expression evaluates to the value of expression2. Assume x = 2 and y = 5. What does this expression evaluate to? (x>y) ? x+1 : y-1

25 A conditional operator expression cannot appear on a line by itself …because it is not considered to be a statement. Instead, it must be embedded inside of a statement. For example: int score = 88; boolean extraCredit = true; score += (extraCredit ? 2 : 0); Is the same as: int score = 88; boolean extraCredit = true; if( extraCredit ) score += 2; else score += 0;

26 Short-Circuit Evaluation What happens when the code runs with null input values? String input = JOptionPane.showInputDialog(“Enter a pos value”); int value; if( (input!=null) && value=Integer.parseInt(input)>0 ) { // do something with positive value } else { // print an error message }

27 The empty statement is a statement that does nothing. It consists of a semicolon by itself. Use the empty statement in places where the compiler requires a statement, but there is no need to do anything. Example: The below for loop can be used as a "quick and dirty" way to add a delay to your program: for (long i=0; i< L; i++) ; Style requirement: Put the empty statement on a line by itself and indent it.

28 Empty Statements can also cause errors! Be aware that you can sometimes accidentally introduce the empty statement into a program Such statements are usually the source of runtime errors. For example: System.out.print("Do you want to play a game (y/n)? "); while (stdIn.next().equals("y")); { // The code to play the game goes here... System.out.print("Play another game (y/n)? "); } empty statement