Types, Values and Variables (Chapter 4, JLS)

Similar documents
Lexical Structure (Chapter 3, JLS)

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

1 Shyam sir JAVA Notes

Introduction to Programming Using Java (98-388)

Index COPYRIGHTED MATERIAL

CSC Java Programming, Fall Java Data Types and Control Constructs

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Expressions Evaluation, Denotation, and Result Variables as Values Type of an Expression FP-strict Expressions

Operators and Expressions

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

CS260 Intro to Java & Android 03.Java Language Basics

Points To Remember for SCJP

Declarations and Access Control SCJP tips

Full file at Chapter 2 - Inheritance and Exception Handling

Java-Programm. Klassen. CompilitionUnit ::= PackageDeclaration opt ImportDeclarations opt TypeDeclarations

15CS45 : OBJECT ORIENTED CONCEPTS

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Brief Summary of Java

Sri Vidya College of Engineering & Technology Question Bank

COE318 Lecture Notes Week 10 (Nov 7, 2011)


CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

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

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Fundamentals of Object Oriented Programming

The Java language has a wide variety of modifiers, including the following:

Object Oriented Programming

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

COP 3330 Final Exam Review

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

Java Primer 1: Types, Classes and Operators

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

S.No Question Blooms Level Course Outcome UNIT I. Programming Language Syntax and semantics

Programming Lecture 3

National University. Faculty of Computer Since and Technology Object Oriented Programming

Exceptions Handling Errors using Exceptions

Programming overview

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

Java Object Oriented Design. CSC207 Fall 2014

Selected Java Topics

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

More on Exception Handling

Programming II (CS300)

Exception-Handling Overview

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

Comp 249 Programming Methodology Chapter 9 Exception Handling

14. Exception Handling

Casting -Allows a narrowing assignment by asking the Java compiler to "trust us"

ECS 142 Spring Project (part 2): Lexical and Syntactic Analysis Due Date: April 22, 2011: 11:59 PM.

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

STRUCTURING OF PROGRAM

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories

Object Oriented Design. Object-Oriented Design. Inheritance & Polymorphism. Class Hierarchy. Goals Robustness Adaptability Flexible code reuse

WA1278 Introduction to Java Using Eclipse

Lexical Considerations

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

Pace University. Fundamental Concepts of CS121 1

Lecture 1: Object Oriented Programming. Muhammad Hafeez Javed

EXCEPTIONS. Java Programming

Exceptions. CSC207 Winter 2017

Programming II (CS300)

A Short Summary of Javali

Lecture #6-7 Methods

Class, Variable, Constructor, Object, Method Questions

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p.

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Object-Oriented Design. March 2005 Object Oriented Design 1

Programming Language Concepts: Lecture 2

The Decaf Language. 1 Lexical considerations

Lexical Considerations

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

More on Exception Handling

Correctness and Robustness

Java Fundamentals (II)

Computer Science II (20073) Week 1: Review and Inheritance

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

Programming II (CS300)

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Some Interview Question-Answers on Java JAVA. dfghjklzxcvbnmqwertyuiopasdfghjklzx 1/10/2013. cvbnmqwertyuiopasdfghjklzxcvbnmq.

Decaf Language Reference Manual

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

JAVA MOCK TEST JAVA MOCK TEST II

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

Lecture 19 Programming Exceptions CSE11 Fall 2013

Engineering Robust Server Software

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Chapter 5 Object-Oriented Programming

public class Test { static int age; public static void main (String args []) { age = age + 1; System.out.println("The age is " + age); }

Tutorial 8 Date: 15/04/2014

JAVA REVIEW cs2420 Introduction to Algorithms and Data Structures Spring 2015

Introduction to Java. Handout-3a. cs402 - Spring

Transcription:

Lecture Notes CS 141 Winter 2005 Craig A. Rich Types, Values and Variables (Chapter 4, JLS) Primitive Types Values Representation boolean {false, true} 1-bit (possibly padded to 1 byte) Numeric Types Integral Types Z byte 2 7... (2 7 1) 8-bit signed two s complement short 2 15... (2 15 1) 16-bit signed two s complement int 2 31... (2 31 1) 32-bit signed two s complement long 2 63... (2 63 1) 64-bit signed two s complement char 0..(2 16 1) 16-bit Unicode (www.unicode.org) Floating-Point Types R float 32-bit ANSI/IEEE Standard 754 double 64-bit ANSI/IEEE Standard 754 Reference Types Class Type e.g. Object e.g. String Array Type e.g. int[] e.g. String[] Values user-defined objects sequence of Type

Variables Primitive Types Value stored in variable e.g. boolean x = true; e.g. int y = 5; e.g. char z = A ; Default value stored is false or 0 e.g. boolean x; e.g. int y; final variables can be assigned at most once e.g. final int SIZE = 10; e.g. final char EXCELLENT = A ; e.g. final float PI = 3.14159; Reference Types Reference (i.e., pointer) to value (i.e., object) stored in variable e.g. String x = "hello"; e.g. Widget y = new Widget(); e.g. int[] z = {3, 2, 4, 5}; Default reference stored is null, which refers to nothing e.g. String x; e.g. int[] y; final variables can be assigned at most once; however, objects to which they refer can be modified e.g. final String GREETING = "hello"; e.g. final int[] CUTOFFS = {90, 80, 70, 60};

Expressions (Chapter 15, JLS) Literals Variables Operations: Prec./Assoc. Category Operator Operand(s) Result high n/a Postfix ++ -- numeric variable numeric value, before side effect n/a Prefix ++ -- numeric variable numeric value, after side effect numeric (+ -) 32-bit numeric value Unary + - ~! integral (~) 32-bit integral value boolean (!) boolean value Multiplicative * / % numeric, numeric 32-bit numeric value Additive + - numeric, numeric 32-bit numeric value Shift << >> >>> integral, integral 32-bit integral value n/a Relational < > <= >= numeric, numeric boolean value boolean, boolean Equality ==!= numeric, numeric boolean value Bitwise & ^ { && reference, reference { boolean, boolean integral, integral { boolean value 32-bit integral value Boolean boolean, boolean boolean value, short-circuit Conditional?: boolean, any, any value, short-circuit low Assignment = *= /= %= += -= <<= >>= >>>= &= ^= = variable, any (=) numeric variable, numeric (*= /= %= += -=) Order of operations determined by 1) parentheses 2) precedence 3) associativity Evaluation: result (and possible side effect) obtained by 1) evaluating left operand 2) evaluating right operand (unless short-circuit) 3) applying operation integral variable, integral (<<= >>= >>>= &= ^= =) boolean variable, boolean (&= ^= =) value, after side effect

Statements (Chapter 14, JLS) Block { Statement } - used to execute a sequence of statements Empty statement ; - has no effect Labeled statement Identifier : Statement - used with labeled break and continue statements Local variable declaration [final] Type Identifier [= Expression](, Identifier [= Expression]) ; - used to create local variable(s) and optionally assign initial value(s) - scope of variable is from point of declaration to end of block in which declared Expression Expression ; - Expression must have a side effect if statement if ( Expression ) Statement [else Statement] - condition Expression must be of type boolean switch statement switch ( Expression ) { ((case Expression :) + Statement + ) [default : Statement + ] } - condition Expression must be integral - case Expression(s) must be integral constant (literal or final variable)

while statement while ( Expression ) Statement - condition Expression must be of type boolean do statement do Statement while ( Expression ) ; - condition Expression must be of type boolean for statement for ( [Expression(, Expression) ]; [Expression]; [Expression(, Expression) ] ) Statement for ( LocalVariableDeclaration; [Expression]; [Expression(, Expression) ] ) Statement - initial Expression(s) must have a side effect - condition Expression must be of type boolean - update Expression(s) must have a side effect break statement break [Identifier] ; - must occur inside a switch, while, do or for statement continue statement continue [Identifier] ; - must occur inside a while, do or for statement

Arrays (Chapter 10, Sections 15.10 and 15.13, JLS) - Arrays are objects that contain zero or more component variables. - Arrays are homogeneous components have the same type. - Arrays are created dynamically (as the program executes). - The length of an array is the number of components therein; it does not change after creation. Array type Type ([]) + - component type may be any Type (including array types) - dimension is number of pairs of [] Array initializer { [Expression (, Expression) ] [,] } { [ArrayInitializer (, ArrayInitializer) ] [,] } - creates an array - components are assigned from expression values - length is number of expressions or array initializers Array creation expression new ArrayType ArrayInitializer - creates an array having a specific component type - dimension, length and compatible component values can be given new Type ([ Expression ]) + ([]) - dimension and lengths (in some dimensions) can be given by expression values Array type local variable declaration [final] ArrayType Identifier [= Expression](, Identifier [= Expression]) ; [final] ArrayType Identifier [= ArrayInitializer](, Identifier [= ArrayInitializer]) ; - used to create local array variable(s) and optionally assign initial component value(s) - expressions must be array creation expressions - scope of variable is from point of declaration to end of block in which declared Array access expression Expression [ Expression ] - array reference expression must be array type and have non-null value - index expression must be integral type and have value between 0 and length-1 - first, second, third,... components are accessed by index expression values 0, 1, 2,... Array length expression Identifier.length

class Sorting { // public static void main(string[] arguments) { int[] v; System.out.println("Bubble sorting..."); println(v = new int[]{8, 2, 5, 3, 9, 4, 6, 1, 10, 7}); for (int i = v.length-1; i > 0; i--) for (int j = 0; j < i; j++) // if (v[j] > v[j+1]) swap(v, j, j+1); println(v); System.out.println("Selection sorting..."); println(v = new int[]{8, 2, 5, 3, 9, 4, 6, 1, 10, 7}); for (int i = 0; i < v.length-1; i++) { int lowindex = i; for (int j = i+1; j < v.length; j++) if (v[j] < v[lowindex]) lowindex = j; // swap(v, lowindex, i); } println(v); System.out.println("Insertion sorting..."); println(v = new int[]{8, 2, 5, 3, 9, 4, 6, 1, 10, 7}); // } for (int i = 1; i < v.length; i++) for (int j = i; j > 0; j--) if (v[j] < v[j-1]) swap(v, j, j-1); println(v); private static void swap(int[] v, int i, int j) { int temp = v[i]; v[i] = v[j]; v[j] = temp; } // swap v[i] and v[j] private static void println(int[] v) { // print array v } } for (int i = 0; i < v.length; i++) System.out.print(" " + v[i]); System.out.println();

Methods (Sections 8.4 and 15.12, JLS) - A method declares an encapsulated sequence of statements that can be invoked. - On invocation, a fixed number of argument values are passed into a method as parameters. - On completion, either nothing (void) or one value is returned. Method modifier public protected private - determines how widely a method is visible/accessible (default is package private) abstract - determines if a method has no body (abstract) static - determines if a method is a class method (static) or an instance method (non-static) - a class method is associated (statically) with its class - an instance method is associated (dynamically) with every object (instance) of its class type final - determines if a method cannot be overridden by a subclass of its class (final) Formal parameters [final] Type Identifier (, [final] Type Identifier) - determine number, type and order of values passed into a method - viewed as local variable declarations by encapsulated statements - assigned incoming values on invocation Method header MethodModifier Type Identifier ( [FormalParameters] ) [throws Type (, Type) ] MethodModifier void Identifier ( [FormalParameters] ) [throws Type (, Type) ] - specifies modifiers, return type, name, formal parameters, thrown exception types - method signature consists of method name and formal parameters Method declaration MethodHeader { Statement } - occurs within a class declaration - non-abstract method body must be a sequence of statements (i.e., block) MethodHeader ; - abstract method body must be omitted

Argument list Expression (, Expression) - list of expressions evaluated from left-to-right - expression values are assigned to corresponding formal parameters Method invocation expression Identifier ( ArgumentList ) - invokes the method with matching signature - causes evaluation of arguments, assignment to formal parameters, execution of body - can have side effects (caused by argument evaluation or body execution) return statement return [Expression] ; - causes abrupt completion of encapsulated statements - optionally contains an expression whose value is returned by a method - non-void method bodies must contain (and eventually execute) a return statement - non-void method bodies may not contain return statements without expressions - void method bodies may not contain return statements with expressions

Classes (Chapter 8, Section 15.9 and 15.11, JLS) - A class declares encapsulated members fields (i.e., variables), methods or other classes. - A class declares a user-defined reference type; i.e., a class type. - Objects (instances) of the class type can be created. - Encapsulated members may be class members (static) or instance members (non-static). - Class members are associated (statically) with the class. - Instance members are associated (dynamically) with every object (instance) of the class type. Field modifier public protected private - determines how widely a field is visible/accessible (default is package private) static - determines if a field is a class variable (static) or an instance variable (non-static) - a class variable is associated (statically) with the class - an instance variable is associated (dynamically) with every object (instance) of the class type final - determines if a field can be assigned at most once (final) Field declaration FieldModifier Type Identifier [= Expression](, Identifier [= Expression]) ; - used to create class or instance variable(s) and optionally assign initial value(s) - scope of variable depends on visibility/accessibility field modifiers Field access expression Type. Identitifer - Type must be a class type - Identifier must be a class variable in class Type - result is class variable in class Type Expression. Identitifer - Expression must be of class type - Identifier must be an instance variable in class - result is instance variable in object referred to by Expression value Static initializer static Block - block of statements initializes class variables before class methods are invoked

Class Instance Creation Expression new Type ( [ArgumentList] ) - creates an object (instance) of class type Type - object created contains its own (non-static) instance variables and instance methods - object created does not contain (static) class variables or class methods - invokes instance initializer in class Type, if any - invokes the constructor with matching signature in class Type - result is a reference to the object created Instance initializer Block - block of statements initializes instance variables before constructors or instance methods are invoked Constructor modifier public protected private - determines how widely a constructor is visible/accessible (default is package private) Constructor header ConstructorModifier Type ( [FormalParameters] ) [throws Type (, Type) ] - specifies modifiers, name (same as class name), formal parameters, thrown exception types - constructor signature consists of class name and formal parameters Constructor declaration - like an instance method whose name is the class name - invoked only by a class instance creation (new) expression - block of statements initializes instance variables depending on formal parameters this expression this - must occur in the body of an instance initializer, constructor or instance method - result is a reference to object whose instance initializer, constructor or instance method is executing

Class modifier public protected private - determines how widely a class type is visible/accessible (default is package private) abstract - determines if a class contains methods with no body (abstract) static - determines if a class is static or an inner class (non-static) - a static class is associated (statically) with the class - an inner class is associated (dynamically) with every object (instance) of the class type final - determines if a class cannot have subclasses (final) Class Body Declaration FieldDeclaration MethodDeclaration StaticInitializer InstanceInitializer ConstructorDeclaration ClassDeclaration InterfaceDeclaration - a member encapsulated within a class declaration Class Declaration ClassModifier class Type [extends Type] [implements Type(, Type) ] { ClassBodyDeclaration } - type extended is called direct superclass (i.e. parent type), Object if omitted - type declared is a subclass of its direct superclass (i.e. parent type) - types implemented must be interfaces, called direct superinterfaces

Exceptions (Chapter 11, Sections 15.6, 14.9 and 14.7, JLS) - An exception signals that a running program has violated a semantic constraint - An exception transfers control abruptly from point thrown to point caught - An exception is represented by an instance of class Throwable or its subclasses - An exception can be thrown during expression evaluation: Expression Potential Exception / % ArithmeticException ArrayCreationExpression ArrayAccessExpression MethodInvocationExpression ClassInstanceCreationExpression FieldAccessExpression OutOfMemoryError NegativeArraySizeException NullPointerException ArrayIndexOutOfBoundsException NullPointerException StackOverflowError Throwable (from method body) OutOfMemoryError Throwable (from constructor body) NullPointerException - An exception can be thrown by a throw statement - An exception can be caught by a try statement or propagated upward to caller try statement try Block (catch ( FormalParameter ) Block) + - catch clause parameter must be of type Throwable or its subclass types - try block is executed - exception thrown within try block is caught by first catch clause to which it can be passed - catch clause that catches the exception (if any) is executed throw statement throw Expression ; - causes an exception to be thrown - expression must refer to an exception that 1) is unchecked of type Error or RuntimeException or their subclass types, or 2) is checked and 2a) is thrown within a try block having a catch clause to which it can be passed, or 2b) is thrown within a method or constructor whose throws clause lists its type

Interfaces (Chapter 9, Section 8.4.3.1, JLS) - An abstract method is a public instance method with no body - An abstract method declares publicized object behavior (not yet implemented) - An abstract method cannot be invoked - An abstract method must be contained in an abstract class Abstract method modifier public - must be public, implied if omitted - cannot be protected or private abstract - determines if a method has no body (abstract) - cannot be static, must be an instance method Abstract method header AbstractMethodModifier Type Identifier ( [FormalParameters] ) [throws Type (, Type) ] AbstractMethodModifier void Identifier ( [FormalParameters] ) [throws Type (, Type) ] - specifies modifiers, return type, name, formal parameters, thrown exception types - method signature consists of method name and formal parameters Abstract method declaration AbstractMethodHeader ;

- An abstract class may contain abstract methods - An interface is an abstract class that contains only constants and abstract methods Interface modifier public - must be public, implied if omitted abstract - must be abstract, implied if omitted - cannot be static or final Interface Member Declaration ConstantDeclaration (public static final, implied if omitted) AbstractMethodDeclaration ClassDeclaration InterfaceDeclaration ; - a member encapsulated within an interface declaration Interface Declaration InterfaceModifier interface Type [extends Type + ] { InterfaceMemberDeclaration } - types extended must be interfaces, called direct superinterfaces

Inheritance (Sections 8.2 and 8.4.6, JLS) Recall class declarations: Class Declaration ClassModifier class Type [extends Type] [implements Type(, Type) ] { ClassBodyDeclaration } - type extended is called direct superclass (i.e. parent type), Object if omitted - type declared is called a subclass of its direct superclass (i.e. parent type) - types implemented must be interfaces, called direct superinterfaces - A class inherits all non-private members of its direct superclass and superinterfaces - A class does not inherit static initializers, instance initializers or constructors - Instance methods declared in the class override inherited ones with the same signature - An overridden method can be invoked using a method invocation expression qualified with super. - A method name shared by multiple methods with different signatures is called overloaded