CS 884 (Prasad)Java Types1 Language Specification Semantics of constructs. –Definition and use of name-value bindings: Name Resolution. Soundness : No.

Slides:



Advertisements
Similar presentations
CS884 (Prasad)java7ExprSt1 Statements and Expressions Execution.
Advertisements

CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
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.
©2004 Brooks/Cole Chapter 2 Variables, Values and Operations.
Java Generics.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 5 Types Types are the leaven of computer programming;
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 Java Object Model Part 1. 2 Type Definition: set of values – a set of values and set of operations –a set of operations that can be applied to those.
CS102 Data Types in Java CS 102 Java’s Central Casting.
PZ04A Programming Language design and Implementation -4th Edition Copyright©Prentice Hall, PZ04A - Scalar and composite data Programming Language.
Primitive Data Types: Numbers Strings Ordinal Types Pointers
Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs1 Programming in Java Objects, Classes, Program Constructs.
OOP Languages: Java vs C++
Programming Principles Data types and Variables. Data types Variables are nothing but reserved memory locations to store values. This means that when.
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
Names Variables Type Checking Strong Typing Type Compatibility 1.
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.
Operators Using Java operators An operator takes one or more arguments and produces a new value. All operators produce a value from their.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
Basic Java Syntax CSE301 University of Sunderland Harry R Erwin, PhD.
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.
Introduction to java Prepared By:-Pragnesh Patel Lect. In Computer Dept. NSIT,Jetalpur 1.
Java Structure import java_packages; class JavaClass { member variables declarations; void otherMethod( ) { } public static void main(String[]
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
1 Introduction to Java. 2 What is Java? A programming language. A platform –A virtual machine (JVM) definition. –Runtime environments in diverse hardware.
CSE 425: Data Types I Data and Data Types Data may be more abstract than their representation –E.g., integer (unbounded) vs. 64-bit int (bounded) A language.
CS3180(Prasad)L5Types1 A Complete Java Program public class HelloWorld { public static void main(String[] args) { System.out.println(“Hello World”); }
Assignment An assignment statement changes the value of a variable The assignment operator is the = sign total = 55; Copyright © 2012 Pearson Education,
ISBN Chapter 6 Data Types Introduction Primitive Data Types User-Defined Ordinal Types.
Types in programming languages1 What are types, and why do we need them?
Types(1). Lecture 52 Type(1)  A type is a collection of values and operations on those values. Integer type  values..., -2, -1, 0, 1, 2,...  operations.
Copyright Curt Hill Variables What are they? Why do we need them?
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
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.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
CSI 3125, Preliminaries, page 1 Data Type, Variables.
1 Lecture 5 More Programming Constructs Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
 Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. 
LESSON 5 – Assignment Statements JAVA PROGRAMMING.
1 Primitive Types n Four integer types:  byte  short  int (most common)  long n Two floating-point types:  float  double (most common) n One character.
A data type in a programming language is a set of data with values having predefined characteristics.data The language usually specifies:  the range.
Data Types References:  Data Type:  In computer science and computer programming, a data type or simply type is a.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
CS 3180 (Prasad)L67Classes1 Classes and Interfaces Inheritance Polymorphism.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Object Oriented Programming Lecture 2: BallWorld.
1 Scalar and composite data Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section
Scalar and composite data Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section
CSE 110: Programming Language I Matin Saad Abdullah UB 1222.
Spring 2006 Special Topics in Computer Engineering: Java Intro 1 Crash Course in Java Based on notes from D. Hollinger Based in part on notes from J.J.
Java Programming Language Lecture27- An Introduction.
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.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
April 13, 1998CS102-02Lecture 3-1 Data Types in Java CS Lecture 3-1 Java’s Central Casting.
Types Type Errors Static and Dynamic Typing Basic Types NonBasic Types
Java Primer 1: Types, Classes and Operators
Java Programming Language
Object Oriented Programming
Multiple variables can be created in one declaration
Objects, Classes, Program Constructs
Explicit and Implicit Type Changes
The Building Blocks Classes: Java class library, over 1,800 classes:
Java Programming Language
Java’s Central Casting
Lecture 7: Types (Revised based on the Tucker’s slides) 10/4/2019
Presentation transcript:

CS 884 (Prasad)Java Types1 Language Specification Semantics of constructs. –Definition and use of name-value bindings: Name Resolution. Soundness : No conflicting requirements. Completeness : No ambiguity, no omissions.

CS 884 (Prasad)Java Types2 Values, Variables, and Types Subtyping Relation

CS 884 (Prasad)Java Types3 Types Primitive Types Reference Types No composite types such as structures or unions. The null type is a special type with one value: the literal null.

CS 884 (Prasad)Java Types4 Primitive Types and Values Numeric Types –Integral Types (signed two’s complement) byte, short (2 bytes), int (4), long (8) char (16-bit Unicode) –Floating-point Types (IEEE 754 Standard) float (4 bytes), double (8 bytes) Boolean Type boolean (true, false)

CS 884 (Prasad)Java Types5 Numeric Types Explicit range and behavior. Java trades performance for cross-platform portability. byte : appropriate when parsing a network protocol or file format, to resolve “endianess”. –BIG endian : SPARC, Power PC : MSB-LSB –LITTLE endian : Intel X86 : LSB-MSB Calculations involving byte/short done by promoting them to int. Internally, Java may even store byte/short as int, except in arrays.

CS 884 (Prasad)Java Types6 Boolean Type Distinct from int type. – 0 (1) are not false ( true ). (Cf. C/C++) Let boolean b,c and int i. if (b) {} else {}; if (b == true) { c = false; } else { c = true; }; equivalent to c = ! b; if (i = 0) {}; is a type error (“ int used bool expected”).

CS 884 (Prasad)Java Types7 Reference Types and Values Class Types String is a class. Interface Types Array Types An object (resp. array object) is an instance of a class (resp. an array). A reference is a handle for (pointer to, address of) an object or an array object.

CS 884 (Prasad)Java Types8 Variable A variable is a storage location. It has an associated type called its compile- time type. It always contains a value that is assignment compatible with its type. –Compatibility of the value of a variable with its type is guaranteed by the language.

CS 884 (Prasad)Java Types9 l-value and r-value of a variable The l-value is the address of the storage location. The r-value is the contents of the storage location. rhsFor the assignment statement: “x = x” the lhs x denotes its l-value, the rhs x denotes its r-value.

CS 884 (Prasad)Java Types10 Variables and Values A variable of a primitive type always holds a value of that exact primitive type. reference referenceA variable of a reference type can hold either a null reference or a reference to any object whose class is assignment compatible with the type of the variable.

CS 884 (Prasad)Java Types11 Subtle Differences Assignment (x = y) Primitive type : copying a value Reference type: sharing an object final variable modifier Primitive type : constant value Reference type: constant object –Mutable : state of the object changeable –Immutable : state of the object constant E.g., class String

CS 884 (Prasad)Java Types12 Variable Initialization Each class/instance variable and each array component is automatically initialized to a fixed default value depending on its type. Each formal parameter and each exception parameter is initialized with the argument value. In contrast, a local variable is not initialized automatically. However, the compiler checks to ensure that it is not used before it has been assigned a value. (Definite Assignment)

CS 884 (Prasad)Java Types13 Type Conversions Every expression has a type deducible at compile-time. A conversion from type S to type T allows an expression of type S to be treated as having type T, at compile-time. A conversion can require some action at run-time.

CS 884 (Prasad)Java Types14 Casting class PrimCast { public static void main(String[] argv) { byte b = 0; int i = b; // widening float f = i; // widening b = i; // *error* b = (b * 0); // *error* b = (byte) i; b = (byte) 280; // = 24 b = 128; // *error* char four = (char) ( ‘1’ + 3 ); }}

CS 884 (Prasad)Java Types15 class Point { } class ColoredPoint extends Point { } class XYZ extends Point { } class RefCast { public static void main (String [] args) { Object oR; Point pR = null; ColoredPoint cpR = null; oR = pR; pR = cpR; cpR = pR; // *error* cpR = (ColoredPoint) pR; XYZ x = null; cpR = (ColoredPoint) x; // *error* }}

CS 884 (Prasad)Java Types16 Type Compatibility Examples class variable - subclass instance import java.awt.*; import java.applet.*; Panel p = new Applet(); Applet a = (Applet) p; p = a; import java.io.*; BufferedReader bin = new BufferedReader (new InputStreamReader (System.in)); interface variable - class instance Runnable p = new Thread();

CS 884 (Prasad)Java Types17 Kinds of Conversion Identity Conversions String Conversions Widening Primitive Conversions (19) –byte  short  int  long  float  double –char  int  long  float  double int  float may lose precision Narrowing Primitive Conversions (19+4) –char  short, char  byte, –byte  char, short  char may lose sign and magnitude information

CS 884 (Prasad)Java Types18 Widening Reference Conversions –null type  any reference type –any reference type  class Object –class S  class T, if S extends T –class S  interface K, if S implements K –interface J  interface K, if J extends K –array SC []  array TC [], if SC  TC, and both SC and TC are reference types. –array T  interface Cloneable –array T  interface Serializable

CS 884 (Prasad)Java Types19 Motivation for Primitive Array Type Constraints int i = 10; long l = i; byte b = (byte) i; int[] iA = new int[5]; byte[] bA = (byte[]) iA; // error b = bA[2]; // reason long[] lA = (long[]) iA; //error lA[2] = l; // reason

CS 884 (Prasad)Java Types20 Motivation for Reference Array Type Constraints Point i = new Point(); Object l = i; ColoredPoint b = (ColoredPoint) i; // throws exception Point[] iA = new Point[5]; Object[] lA = (Object[]) iA; lA[2] = l; // no exception b = lA[2] ; // *error* l = lA[2] ColoredPoint[] bA = (ColoredPoint[]) iA; // throws exception

CS 884 (Prasad)Java Types21 Another Example: Primitive Array Type void f(int[] a) { int i = a[4]; a[3] = i; } long[] la = new long[8]; short[] sa = new short[8]; f(la); // banned : compile-time error f(sa); // banned : compile-time error

CS 884 (Prasad)Java Types22 Another Example: Reference Array Type void f(Point[] pa) { pa[0] = new Point(); } Object[] oa = new Object[8]; f(oa); // compile-time error f((Point[]) oa); // ClassCastException ColoredPoint[] cpa = new ColoredPoint[8]; f(cpa); // array store exception in f

CS 884 (Prasad)Java Types23 Narrowing Reference Conversions –Permitted among reference types that can potentially share common instances. –These conversions require run-time test to determine if the actual reference is a legitimate value of the new type. Observe the interpretation of final class. Observe that every non-final class can potentially be extended to implement an interface.

CS 884 (Prasad)Java Types24 class S; interface K; class C extends+ S implements+ K; class S  interface K CSK C c = new C(); S s = c; K k = (C) s; s = (C) k;

CS 884 (Prasad)Java Types25 Narrowing Reference Conversions –class Object  any reference type –class S  class T, if T extends S –class S  interface K, if S is not final and S does not implement K –interface K  class T, if T is not final –interface K  class T, if T is final and T implements K –interface J  interface K, if K does not extend J and there is no common method with same signature but different return types. –array SC []  array TC [], if SC  TC, and both SC and TC are reference types.

CS 884 (Prasad)Java Types26 Type Errors : Arrays class TypeErrors { public static void main(String [] args) { long [] al = (long []) new int [10]; // compile-time error even with the cast ColoredPoint cp = new Point(); // compile-time type error : Need Explicit Cast ColoredPoint cp = (ColoredPoint ) new Point(); Point [] ap = new ColoredPoint [5]; ap [2] = new Point(); // run-time type error : ArrayStoreException ap [2] = (ColoredPoint) new Point(); // run-time type error : ClassCastException }}

CS 884 (Prasad)Java Types27 Conversion Contexts String Conversions –any primitive / reference / null type  type String Applied to an operand of the binary operator + when one of the argument is a String. (The operator + stands for string concatenation.) Numeric Promotion Applied to operands of an arithmetic operator.

CS 884 (Prasad)Java Types28 Assignment Conversions v = e; type of expression e is assignment compatible with type of variable v, if type(e)  type(v), using: –identity conversion –widening (primitive / reference) conversion –narrowing primitive conversion from an int constant to byte, short, or char, without overflow.

CS 884 (Prasad)Java Types29 Method invocation conversion differs from assignment conversion by banning narrowing conversions for int constants. –This simplifies resolution of calls to overloaded methods with integral type arguments. Casting conversion is applied to the operand of a cast operator. A cast can do any permitted conversion.

CS 884 (Prasad)Java Types30 Subsets, subclasses, subtypes Subsets –Natural Numbers  Integers  Reals Subclasses –class S is a subclass of class T, if class S can potentially reuse the implementation for the methods of class T. Subtypes – type S is a subtype of type T, if an object of type S can always replace an object of type T. In other words, they share a common behavior.

CS 884 (Prasad)Java Types31 Examples (Int, +,  ) is a subtype of (Double,+,  ), but is not its subclass. However, (Int, +, ,*,/) is not a subtype of (Double,+, ,*,/). A list-based Bounded Stack can be a subclass of a list-based Stack, but a Bounded stack is not a subtype of Stack.. An array-based Bounded Stack can be a subtype of list-based Bounded Stack, and vice versa. –subclass : subtype :: code sharing : behavior sharing

CS 884 (Prasad)Java Types32 Further Updates Java 1.1: Nested and Inner classes Java 5: Generics; Enumerated Types

CS 884 (Prasad)Java Types33 Parameterized Types Examples Vector Seq > Collection Pair // Vector –illegal, primitive types cannot be arguments // Pair –illegal, not enough arguments

CS 884 (Prasad)Java Types34 Type with Wildcard void printCollection(Collection c) { // a wildcard collection for (Object o : c) { System.out.println(o); } } Use of unbounded wildcard allows any kind of collection to be used as a parameter. –(cf. Collection )

CS 884 (Prasad)Java Types35 Bounded Wildcards interface Collection { boolean addAll(Collection c) {} … } (cf. Collection )