Document not found! Please try again

Java Programming Basics: Identifiers, Types, Variables, Operators ...

81 downloads 13042 Views 3MB Size Report
Java Programming Basics: Identifiers, Types, Variables, Operators, and Control Flow. 2. CSD Univ. of Crete. Fall 2012. So, Where's the Java? • Developers of ...
Fall 2012

CSD Univ. of Crete

Java Programming Basics: Identifiers, Types, Variables, Operators, and Control Flow

1

Fall 2012

CSD Univ. of Crete

So, Where’s the Java?  Developers of Java tried to "fix" problems

of earlier languages: too many different platforms (including "appliances" such as phones, toasters, etc.) too many incompatibilities too much machine orientation and detail, without objects being built in difficult to use

Java Source Code public myApplet extends Applet { public void init( ) { Label myLabel = new Label("Hi"); add(myLabel); } }

javac psuedocode compiler

Java bytecodes

Web Server

 Java started as a programming language

for embedded systems (toasters, microwave ovens, washers, etc.) needed to be portable had to be reliable

 Web interest came along later

Macintosh Java Virutal Machine

UNIX - X-Windows Java Virtual Machine

Win 32 - PC Java Virtual Machine

2

1 1

Fall 2012

CSD Univ. of Crete

Java as Seen by its Developers



Simple Stripped-down

version of C/C++ minus all the confusing, troublesome features of C/C++  Object-oriented Promotes

good software engineering by facilitating code reuse



Platform-independent Executable

code is bytecode that can run run any machine. Compile once, run everywhere.

3

Fall 2012

CSD Univ. of Crete

Java as Seen by its Developers 

Portable Works

the same on all machines. “WORA”, or write once run anywhere



Multithreaded Programs can handle many operations simultaneously



Secure

Bytecode

verification on loading (not just compilation) Applet code runs in 'sandbox' with significant restrictions

4

2 2

Fall 2012

CSD Univ. of Crete

How is Java Different from other Languages  Less than you think:     

Java is an imperative language (like C++, Ada, C, Pascal) Java is interpreted (like LISP, APL) Java is garbage-collected (like LISP, Eiffel, Modula-3) Java can be compiled (like LISP) Java is object-oriented (like C++, Ada, Eiffel)

 A successful hybrid for a specific-application domain  A reasonable general-purpose language for non-real-time

applications  Work in progress: language evolving rapidly 5

Fall 2012

CSD Univ. of Crete

How Java works?  The Java compiler translates Java

source code into a special representation called bytecode Java bytecode is not the machine language for any traditional CPU

interpreter translates bytecode into machine language and executes it The JVM is a software layer that provides translation between Java byte codes and the native operating system

Java compiler

Java Virtual Machine

 Another software tool, called an

Java source code Java bytecode

Java interpreter

Just in Time Code Generator

Run-Time System

Machine code

6

3 3

Fall 2012

CSD Univ. of Crete

Bytecode  Like Machine code but machine

independent VM interprets each bytecode and executes it in the system’s machine opcode VM inner loop do { fetch an opcode byte execute an action depending on the value of the opcode } while (there is more to do);

 Each VM is machine dependent  Just in Time (JIT) code generator

can improve the performance of Java Applications by compiling bytecode to machine code before execution

AL_CODE: Method 1 Method="HelloWorld.main"(#24) Signature="([Ljava/lang/String;)V"(#26) Access=public,static (0x0009) Attribute Count=1 Attribute="Code"(#20) Length=51 Max Stack=2 Max Locals=1 Code Length=9 0x00000000 B20008 getstatic (#8) java/lang/System.out 0x00000003 1201 ldc (#1) "Hello World"(#34) 0x00000005 B60007 invokevirtual (#7) java/io/PrintStream.println 0x00000008 B1 return Exception Handler Entries=0 Attribute="LineNumberTable"(#17) Length=6 Entry Count=1 Start=0x00000000 Line Number=5 Attribute="LocalVariableTable"(#15) Length=12 Entry Count=1 Start=0x00000000 Effective Length=9 Slot=0 Name="args"(#35) 7 Signature="[Ljava/lang/String;"(#36)

Fall 2012

CSD Univ. of Crete

The Java Development Process Edit

Compile

Text Editor

javac Compiler

Source Code

Run Application java Interpreter

Bytecodes myfile.class

myfile.java

Run Applet HTML File

Web browser

afile.html appletviewer

8

4 4

Fall 2012

CSD Univ. of Crete

Java Compile vs RunTime Environment

9

Fall 2012

CSD Univ. of Crete

Using Java with HTML: Applets  A Java applet is a Java program

that is intended to be sent across a network and executed using a Web browser  Links to applets can be

TicTacToe v 1.1

TicTacToe v 1.1

...

embedded in HTML documents The Tag

10

5 5

Fall 2012

CSD Univ. of Crete

Java Applets  Most Internet Browser software

contains a JVM Load java byte codes from the remote computer Run locally the Java Program in a Browser Window

Java source code

Java compiler

Java bytecode

Remote computer

Web browser Java interpreter

Local computer 11

Fall 2012

CSD Univ. of Crete

Java History  1990

 The group was code named The Green Project Naughton threatens to leave Sun  Goal was to develop a system  Scott McNeally CEO of Sun asks that was compact and simple Naughton to write up list of problems driven by consumer electronics with Sun and what should be done • “Tell me what you would do if you  1991 were God.”  Green was a solution looking for a problem  Naughton’s suggestions  Gosling realised that C++ wasn’t • hire an artist to pretty up Sun’s reliable enough for communicauninspired interfaces ting consumer electronics and • pick a single programming toolkit developed the language Oak • focus on a single windows  Naughton was interested in the technology user interface and developed • lay off just about everybody in the multimedia animations to work existing windows group with Oak  McNeally agrees to Naughton’s  The Green team’s ambition was to build a device that was an suggestions and gives Naughton, interface to cyberspace in colour James Gosling and Mike Sheridan $1 12 and 3-D written in Oak million and one year to deliver  Patrick

6 6

Fall 2012

CSD Univ. of Crete

Java History  1992

 While

 Demoed

first device made of bits and pieces from handheld TVs and  Nintendo GameBoys called *7 (Star 7) a wireless PDA  Sun set up wholly owned subsidiary as FirstPerson Inc.  1993  Oak was used to create a set-top box for interactive TV  Marc Andreessen and Eric Bina from NCSA release the first version  of the Mosaic web browser   1994   With no shipping product the focus   moved to personal computers   Gosling went back to reprogram  Oak for the internet

Naughton worked on the next killer-app, WebRunner, a web browser 1995  Oak is renamed Java and is posted to the web including source code  Fearing Java’s popularity Microsoft announces Blackbird  First demo of WebRunner displaying a web page as well as an Applet  Marc Andreessen licences Java for use in the Netscape Navigator web browser 1996 - JavaTM 1.0 1997 - JavaTM 1.1 1998 - JavaTM 1.2 - aka Java 2 Platform 2000 - JavaTM 2 Rel.1.3Stand.Ed.(J2SE) 2002 - JavaTM 2 Rel. 1.4 J2SE 2004 - JavaTM 2 Rel. 1.5 - aka Java 5 Pl. 2006 - JavaTM 2 Rel. 1.6 - aka Java 6 Pl. 13

Fall 2012

CSD Univ. of Crete

Versions of Java Java 1.0

Java 1.1

Java 1.2

Java 1.3

Java 1.4

Java 1.5

8 packages 212 classes

23 packages 504 classes

59 packages 1520 classes

77 packages 1595 classes

103 packages 2175 classes

131 packages 2656 classes

New Events

JFC/Swing

JNDI

Inner class

Drag and Drop

Java Sound

Object Serialization Jar Files International

Timer

Java2D CORBA

Regular Exp javax.activity, Logging javax. Assertions management NIO java.nio, javax.imageio, javax.net, javax.print, javax.security, org.w3c

javax.naming, javax.sound, javax.transaction

Reflection JDBC

javax.accessibility, javax.swing, org.omg

RMI java.math, java.rmi, java.security, java.sql, java.text, java.beans java.applet, java.awt, java.io, java.lang, java.net, java.util

14

7 7

Fall 2012

CSD Univ. of Crete

J2SE 5.0: Java 2 Platform Standard Edition 5.0

15

Fall 2012

CSD Univ. of Crete

Java Market Facts TIOBE Programming Community

Java Software Investments in $US

Source: IDC 2000

Source: www.tiobe.com September 2008

16

8 8

Fall 2012

CSD Univ. of Crete

The Java Phenomena: Myths and Reality

 Java is Simple

 Java is only for the Internet Java is an advanced Wrong again: Java is steadily programming language (PL) gaining as a general purpose PL • Programming is NOT simple (in • Current systems are about 20% any language !!!) slower than C++  Java Runs on all Platforms • Upcoming releases claim to lower or eliminate that gap (10%) Well QCross-platform code can • No Language, No Operating be achieved, but you must test on System, No Platform is right for all platforms you will deliver on EVERY Application 17 Wrong:

Fall 2012

CSD Univ. of Crete

Overview of Java Programs

18

9 9

Fall 2012

CSD Univ. of Crete

Java's "Building Blocks"

Programs Types Vassilis the Teacher

Hire Vassilis at CSD

Objects

float Salary = 78234.0F; int Age = 32;

Person

Grade Students of CS252

Attributes: Name Age Salary Methods: Grade(); IncreaseSalary();

Bits (the int 32) 0000 0000 0000 0000 0000 0000 0010 0000

19

Fall 2012

CSD Univ. of Crete

Java's "Building Blocks"  Java programs relies on software components called objects An

object contains both data and behavior An object is defined by a class  A program is made up of one or more classes A

class contains one or more methods A method contains program statements  Statements are Variable

declarations: primitive data types and classes arithmetic, logical, bit-level, class access Control structures: selection, looping, etc. Object messages: i.e., calls to methods Operations:

 A Java application always executes the main method 20

10 10

Fall 2012

CSD Univ. of Crete

Programs: Classes, Methods and Statements

Class MyProgram { main() { statement1 statement2 statement3 Q } method1() { Q } method2() }

Java Program Class A { methodA1() { statement1 statement2 statement3 Q } methodA2() { Q } }

Class B { methodB1() { } methodB2() { } methodB3() } Class C { Q }

21

Fall 2012

CSD Univ. of Crete

Encapsulation and Packages  Every field, method belongs to a class  Every class is part of some package The

default package is used unless an other package is specified The name of a package is a sequence of names, separated by ”.” e.g., ”java.lang” The fully qualified name of a class is the name of the package followed by the a ”.”followed by the name of the class. The fully qualified name of class String is ”java.lang.String” A package does not declare which classes belong in it. Instead a class define which package it belong to. This is done by the package declaration in a sourcefile, e.g., package gr.uoc.csd.hy252.example

22

11 11

Fall 2012

CSD Univ. of Crete

A Program /* Display a message */ class hello { public static void main(String[] args){ System.out.println("Hello World!"); } }

23

Fall 2012

CSD Univ. of Crete

Functions /* Display a message */ class hello { public static void main(String[] args){ System.out.println("Hello World!"); } }  Java program consists of a named class

24

12 12

Fall 2012

CSD Univ. of Crete

Functions /* Display a message */ class hello { public static void main(String[] args){ System.out.println("Hello World!"); } }  The body of the class is surrounded by braces

25

Fall 2012

CSD Univ. of Crete

Functions /* Display a message */ class hello { public static void main(String[] args){ System.out.println("Hello World!"); } }  (Almost) every Java program must have one and only one main()

function

26

13 13

Fall 2012

CSD Univ. of Crete

Functions /* Display a message */ class hello { public static void main(String[] args){ System.out.println("Hello World!"); } }  The body of the function is surrounded by brackets  Statements can be combined within braces to form a block statement A

block statement can be used wherever a statement is required by the Java syntax 27

Fall 2012

CSD Univ. of Crete

Statements /* Display a message */ class hello { public static void main(String[] args){ System.out.println("Hello World!"); } }  A semicolon is a statement terminator

28

14 14

Fall 2012

CSD Univ. of Crete

Java Separators  Nine ASCII characters are the Java punctuators (separators)

{ [ ( ; , :

} ] )

curly braces square braces parenthesis semi-colon comma colon

(" code block for a group of statements ") (" array element size ") (" groups operations ") (" ends a java statement ") (" inside of a for loop ") (" with a label with break or continue ")

29

Fall 2012

CSD Univ. of Crete

White Spaces

/* Display a message */ class hello { public static void main(String[] args){ System.out.println("Hello World!"); } } Spaces, blank lines, and tabs are collectively called white space and are

used to separate words and symbols in a program  Extra white space is ignored, so a valid Java program can be formatted in many different ways  Programs should be formatted to enhance readability, using consistent indentation 30

15 15

Fall 2012

CSD Univ. of Crete

Objects /* Display a message */ class hello { public static void main(String[] args){ System.out.println("Hello World!"); } }  The identifier System.out is an object  The identifier println is one of the methods for that object

31

Fall 2012

CSD Univ. of Crete

Strings /* Display a message */ class hello { public static void main(String[] args){ System.out.println("Hello World!"); } }  "Hello World" is called an object string  There is an explicit string type (class) in Java (unlike C/C++) Strings

are different than characters !!! 32

16 16

Fall 2012

CSD Univ. of Crete

Preprocessor Directives /* Display a message */ class hello { public static void main(String[] args){ System.out.println("Hello World!"); } }  public indicates that this function can be called by objects outside of

the class

33

Fall 2012

CSD Univ. of Crete

Preprocessor Directives /* Display a message */ class hello { public static void main(String[] args){ System.out.println("Hello World!"); } }  static indicates that this function remains in memory throughout the

execution of the application

34

17 17

Fall 2012

CSD Univ. of Crete

Preprocessor Directives /* Display a message */ class hello { public static void main(String[] args){ System.out.println("Hello World!"); } }  void indicates that this function does not return a value to the object

that calls it

35

Fall 2012

CSD Univ. of Crete

Preprocessor Directives /* Display a message */ class hello { public static void main(String[] args){ System.out.println("Hello World!"); } }  args can be used in the main function to pass parameters from the

operating system command line

36

18 18

Fall 2012

CSD Univ. of Crete

Comments /* Display a message */ class hello { public static void main(String[] args){ System.out.println("Hello World!"); } }  Comments are the most important part of your program Criteria

for good comments

37

Fall 2012

CSD Univ. of Crete

Comments There are two kinds of comments:  

/* text */ A traditional comment. All the text from the ASCII characters /* to the ASCII characters */ is ignored // text An end-of-line comment. All the text from the ASCII characters // to the end of the line is ignored

Comments do not nest  

/* and */ have no special meaning in comments that begin with // // has no special meaning in comments that begin with /* or /**

 As a result, the text: /* this comment /* // /** ends here: */

is a single complete comment 38

19 19

Fall 2012

CSD Univ. of Crete

Java Identifiers

39

Fall 2012

CSD Univ. of Crete

Java Identifiers  Identifiers are the words a programmer uses in a program Most

identifiers have no predefined meaning except as specified by the programmer  Rules... An identifier can be made up of letters, digits, the underscore character (_ _), and the dollar sign ($ $) The first character must be any non-digit from the Unicode standard Subsequent characters may include digits Avoid using underscore and $ for the first character Java is case sensitive, therefore Total and total are different identifiers  Three types of identifiers: words that we make up ourselves words that are reserved for special purposes in the language words that are not in the language, but were used by other programmers to make the library

40

20 20

Fall 2012

CSD Univ. of Crete

Java Reserved Words  Some identifiers, called reserved words, have specific meanings in

Java and cannot be used in other ways User-defined identifiers cannot duplicate Java reserved words (aka keywords) abstract boolean break byte byvalue case cast catch char class const continue

default do double else extends false final finally float for future generic

goto if implements import inner instanceof int interface long native new null

operator outer package private protected public rest return strictfp short static super

switch synchronized this throw throws transient true try var void volatile while 41

CSD Univ. of Crete

Fall 2012

Words that we Make up Ourselves /* Display a message */ class hello { public static void main(String[] args){ System.out.println("Hello World!"); } }

42

21 21

CSD Univ. of Crete

Fall 2012

Words that we Reserved by Java /* Display a message */ class hello { public static void main(String[] args){ System.out.println("Hello World!"); } }

43

CSD Univ. of Crete

Fall 2012

Words Used by other Programmers /* Display a message */ class hello { public static void main(String[] args){ System.out.println("Hello World!"); } }

44

22 22

Fall 2012

CSD Univ. of Crete

println(…) is a method declared in the class: PrintStream java.io.PrintStream class is Java’s printing expert: public class { … public public public public … }

PrintStream extends FilterOutputStream

print (String s) { … } print (int i) {…} print (boolesn b) {…} println (String s) { … }

So, different print() and println() methods belong to PrintStream class 

45

CSD Univ. of Crete

Fall 2012

System.out is a variable from class System and is of type PrintStream public final class System { ... public static PrintStream out; out;// // Standart output stream public static PrintStream err;// err;// Standart error stream public static InputStream in; // Standart input stream ... } 

System class is part of java.lang package

46

23 23

Fall 2012

CSD Univ. of Crete

Putting them all Together System.out.println(“Hello World!”)

object



 

method

Information provided to the method (parameters)

A method println(…) is a service that the System.out object can perform This is the object of type PrintStream, PrintStream declared in java.lang.System class Method println(…) is invoked ( or called ) The method println(…) is called by sending the message to the System.out object, requesting the service 47

Fall 2012

CSD Univ. of Crete

Naming Style of Identifiers  Names should be chosen carefully: they play a central role in the

readability of the program and is part of its documentation; they should be: meaningful BankAccount, vs. XP12_r$, BankAccount size XP12_r$ wq1 long

enough to express the meaning of the name numberOfElements

But

not unnecessarily long theCurrentItemBeingProcessed

48

24 24

Fall 2012

CSD Univ. of Crete

All Identifiers have an Associated Scope  The scope of a name is the region of program code where that name

is visible  A name cannot be accessed outside its scope  Within a method: Braces

({}) mark closed regions of program statements A local variable is only visible from the point of its declaration until the closing brace enclosing it Public void thisMethod() { int variable1 = ...; while ( notDone ) { int variable2 = ...; } }

49

Fall 2012

CSD Univ. of Crete

Java Types and Variables

50

25 25

Fall 2012

CSD Univ. of Crete

Data Types  A data type is defined by a set of values and the operators you can

perform on them Each value stored in memory is associated with a particular data type

islowercase isuppercase isdigit

Character

Values

Data Type

Operations

 Java has several predefined types, called primitive data types Java

Literals are the representation of simple data values : mainly numbers and text

51

Fall 2012

CSD Univ. of Crete

Primitive Data Types Type

Size (Bits)

Range

Default Value

byte

8

-128, +127

(byte) 0

short

16

-32768, +32767

(short) 0

int

32

-2147483648, +2147483647

0

long

64

-9.223E18, +9.223E18

0L

float

32

1.4E-45, 3.4 E+38

0.0f

double

64

4.9E-324, 1.7 E+308

0.0d

1 (?)

true, false

false

16

‘\u0000’, ’\uffff’

‘\u0000’

boolean char

52

26 26

Fall 2012

CSD Univ. of Crete

Unicode Character Type A char value stores a single character from the Unicode character set  The total number of represented characters is 216 = 65535

The Unicode character set uses 16 bits per character Unicode  Check out codes at http://unicode.org The ASCII character set is still the basis for ISO-8859-1 many other programming languages  The ASCII character set uses 8 bits (one byte) per character  To provide backwards compatibility with the ASCII code, the first 128 characters are the ASCII coded characters Java 5 supports Unicode 4.0, which defines some characters that require 21 bits in addition to the 16-bit standard Unicode 3.0 characters  You use int to represent these characters, and some of the static methods in the Character class now accept int arguments to deal with them.  In a String, use a pair of char values to encode a 21-bit character 

53

Fall 2012

CSD Univ. of Crete

Part of the Unicode Set 0x0021 …

0x3041 …

0x05B0 … 0x77CD …

… 54

27 27

Fall 2012

CSD Univ. of Crete

Part of the ASCII Set 0x21 …

…0xB9 55

Fall 2012

CSD Univ. of Crete

The Great Escape  What is an escape sequence?  \b for writing “difficult to represent” characters  \t Include invisible and punctuation  \n characters  \f  Parts of an escape sequence  \r The escape character: the  \” backslash (\ \)  \’ The translation value  \\ • Unicode values: ‘\u2122’  \ddd (Hex -decimal value)  \uXXXX • When using an octal number you may use 1, 2, or 3 digits • Each digit must be in the range 0-7 Method

Backspace Tab New line Form feed Return (ENTER) Double quote Single quote Backslash Octal code Hex-decimal code

56

28 28

Fall 2012

CSD Univ. of Crete

The Life Time of Variables  Declaration Give

Declaration

a type and a name

 Instantiation Give

Instantiation

a name a location in memory

• Automatic with primitives  Assignment Set

Assignment

or change the value

Initialization

• The first time we set or change the value

Reference

 Reference Use

or read the value 57

Fall 2012

CSD Univ. of Crete

Variable Declaration  The Java programming language is a strongly typed language every

variable and every expression has a type that is known at compile time (as opposed to runtime)

 Syntax

type name [= value]

58

29 29

Fall 2012

CSD Univ. of Crete

Variable Declaration Decimal

1006 char ch;

1007

short number;

1008

...

1009

72

ch

ch = 'H';

100A

100

number

number = 100

100B

...

100C 100D 59

Fall 2012

CSD Univ. of Crete

Variable Declaration Binary

1006 char ch;

1007

short number;

1008

...

1009

01001000

ch

ch = 'H';

100A

01100100

number

number = 100

100B

...

100C 100D 60

30 30

Fall 2012

CSD Univ. of Crete

Variable Declaration Hex

1006 char ch;

1007

short number;

1008

...

1009

48

ch

ch = 'H';

100A

64

number

number = 100

100B

...

100C 100D 61

Fall 2012

CSD Univ. of Crete

Java Data Conversions  Sometimes it is convenient to convert data from one type to another For

example, we may want to treat an integer as a floating point value during a computation  What are compatible conversions? Data conversions between different types where no information is lost Possible from less precise to more precise types  Two kinds of data conversions Widening are safest because they tend to go from a small data type to a larger one: char, short  int, long, float, double Narrowing can lose information because they tend to go from a large data type to a smaller one : double, float, long, int  char, short  In Java, data conversions can occur in three ways: assignment conversion arithmetic promotion 62 casting

31 31

Fall 2012

CSD Univ. of Crete

Assignment Conversions  Assignment conversion occurs when a value of one type is assigned to

a variable of another Only widening conversions can happen via assignment

double d float f byte b long l

= = = =

123.45F;// 123.45; // 128; // 123; //

OK Not OK Not OK OK Floating point constants are assumed to be double, by default!

63

Fall 2012

CSD Univ. of Crete

Arithmetic Promotions  Arithmetic promotion happens automatically when operators in

expressions convert their operands When an integer and a floating-point number are used as operands to a single arithmetic operation, the result is floating point The integer is implicitly converted to a floating-point number before the operation takes place int i=37; double x=27.475; System.out.println(“i+x=“+(i+x));

Output: i+x=64.475

64

32 32

Fall 2012

CSD Univ. of Crete

Type Promotion Rules double

None

float

double

long

float, double

int

long, float, double

char

int, long, float, double

short

int, long, float, double

byte

short, int, long, float, double

boolean

None 65

Fall 2012

CSD Univ. of Crete

Long Integer to Floating point Conversion may result in Precision Loss

/* integer values can have Testing data conversion up to 10 digits precision */ public class DataConv mantissa of a float has only { 7-digit precision (23 bitspublic static void main(String [] args) fraction, 8-exponent, 1-sign {long i=100000001; // 9 digits sign*mantissa*fractionexponent) float x; precision:governed by number x=i; of digits in the mantissa System.out.println("x="+x);} } range:governed by number of

digits in the exponent

Output:

66

33 33

Fall 2012

CSD Univ. of Crete

Explicit Conversions: Casts  What are casts? Tell

Java to “try” to store a value according to a new type Creates temporary expression value  Cast syntax : (type) value To cast, the type is put in parentheses in front of the value being converted Both widening and narrowing conversions can be accomplished by explicitly casting a value

byte b = (byte) 123; byte b = (byte) 256; int n = (int) .999;

// OK // OK??? // OK??? 67

Fall 2012

CSD Univ. of Crete

Narrowing Cast: What Happens?

0000000011111010

0000000011111010

short a = 250;

byte b = (byte) a;

Discarded Bits

68

34 34

Fall 2012

CSD Univ. of Crete

Narrowing Cast: What Happens? A 2’s complementary integer is negative if its leftmost bit is 1

0000000011111111

char c = ‘\u00FF’ ;

-1 in decimal

0000000011111111

byte b = (byte) c;

Discarded Bits

69

CSD Univ. of Crete

Fall 2012

Narrowing Casts can Lose both Numeric Magnitude and Precision

/* short to char conversion */ public class ShortChar { public static void main(String []args) {short x=97; char c=(char)x; System.out.println("After conversion short x=97x=97->char c"); System.out.println("c="+c);} }

Output:

70

35 35

Fall 2012

CSD Univ. of Crete

Narrowing Casts can Lose both Numeric Magnitude and Precision

/* char to short conversion */ public class CharShort { public static void main(String []args) {char c='a'; short x=(short)c; System.out.println("After conversion char'a'char'a'->short x"); System.out.println("x="+x);} }

Output:

71

Fall 2012

CSD Univ. of Crete

Values and References  The differences between literals and objects Primitive

types hold values Object types (including Strings) hold references

72

36 36

Fall 2012

CSD Univ. of Crete

The Null Type Null type has no name and does not belong to any category 

It is impossible to declare a variable of the null type

The null type has one value, the null reference, represented by the

literal null, null which is formed from ASCII characters Usually the null type is ignored and we pretend that null is merely a

special literal that can be of any reference type

73

Fall 2012

CSD Univ. of Crete

The Java Typing System

74

37 37

Fall 2012

CSD Univ. of Crete

Java vs. C or C++ Data Types  Two type categories

 Various type categories

 All nonprimitive types are objects  Separate types for structs, unions,

enums, and arrays  All numeric types are signed

 Signed and unsigned numeric types

 All primitive types are a fixed size Primitive type size varies by platform

for all platforms  16-bit Unicode characters  Boolean data type primitive  Conditions must be boolean expressions  Variables are automatically initialised

 8-bit ASCII characters  No explicit boolean data type  Integer results are interpreted as

boolean conditions  No automatic initialisation of

variables 75

Fall 2012

CSD Univ. of Crete

Java vs. C++ Typing System

76

38 38

Fall 2012

CSD Univ. of Crete

Java Operators

77

Fall 2012

CSD Univ. of Crete

What’s an Operator?  Operators are tokens that trigger some computation when applied to

variables and other objects Arithmetic, logical, and bit-level operators Class access operators  The Java operators are formed from ASCII characters:

()

/




|

--

+

=

||

~




!=

=

*

>>>

&

op=

78

39 39

Fall 2012

CSD Univ. of Crete

Unary Operators



79

Fall 2012

CSD Univ. of Crete

Unary Operators

☺ Operator

80

40 40

Fall 2012

CSD Univ. of Crete

Unary Operators



x

81

Fall 2012

CSD Univ. of Crete

Unary Operators



x Operand

82

41 41

Fall 2012

CSD Univ. of Crete

Unary Operators



x

x



Some operators are “switch hitters”

83

Fall 2012

CSD Univ. of Crete

Unary Operators Group expression

() Unary plus

+ Unary minus

-

84

42 42

Fall 2012

CSD Univ. of Crete

Unary Operators Bitwise complement

~ Logical negation

! Pre- or Post-increment

++ Pre- or Post-decrement

--

85

CSD Univ. of Crete

Fall 2012

Increment and Decrement Operators  The increment and decrement operators are arithmetic and operate on

one operand The increment operator (++) adds one to its operand The decrement operator (--) subtracts one from its operand  The statement count++; is essentially equivalent to count= count + 1;  The increment and decrement operators can be applied in prefix form

(before the variable) or postfix form (after the variable)  When used alone in a statement, the prefix and postfix forms are basically

equivalent That is, count++; is equivalent to ++count; 86

43 43

Fall 2012

CSD Univ. of Crete

Unary Operators

i = 0;

i

1

count = 2 + i++;

count

2

i = 0;

i

1

count = 2 + ++i;

count

3

87

Fall 2012

CSD Univ. of Crete

Binary Operators



88

44 44

Fall 2012

CSD Univ. of Crete

Binary Operators

x

y



89

Fall 2012

CSD Univ. of Crete

Binary Operators Operator

x

☺ Operand

y Operand

90

45 45

Fall 2012

CSD Univ. of Crete

Binary Operators Additive & Multiplicative Plus

+ Minus

Multiply

* Divide

/ Remainder

%

91

Fall 2012

CSD Univ. of Crete

Binary Operators

=

Assignment

 Assignment is a binary operator in Java  The left-hand operand of an assignment must be an LVALUE (left value)

92

46 46

Fall 2012

CSD Univ. of Crete

Binary Operators

=

Assignment

 An LVALUE is an expression that refers to a region of memory Names

of variables are LVALUES Names of functions and arrays are not LVALUES

93

Fall 2012

CSD Univ. of Crete

Binary Operators

=

Assignment

cat = dog + 1;

legal

cat + 1 = dog;

illegal

94

47 47

Fall 2012

CSD Univ. of Crete

Binary Operators

=

Assignment

Not an LVALUE cat = dog + 1;

cat + 1 = dog;

legal

illegal

95

Fall 2012

CSD Univ. of Crete

Binary Operators

=

Assignment

cat = dog + 1;

legal

1 + cat = dog;

96

48 48

Fall 2012

CSD Univ. of Crete

Binary Operators

=

Assignment

Not an LVALUE cat = dog + 1;

1 + cat = dog;

legal

illegal

97

Fall 2012

CSD Univ. of Crete

Binary Operators

=

Assignment

This is an LVALUE cat = dog + 1;

1 + (cat = dog) dog);

legal

Not what you want!

98

49 49

Fall 2012

CSD Univ. of Crete

Binary Operators

class Test { public static void main(String[] args) { int result, val_1, val_2; result = (val_1 = 1) + (val_2 = 2); System.out.println("val_1 = "+val_1); System.out.println("val_2 = "+val_2); System.out.println("result = "+result); }

val_1 = 1 val_2 = 2 result = 3

}

99

Fall 2012

CSD Univ. of Crete

Binary Operators Expressions involving only integers are evaluated using integer

arithmetic

float result; int i,j;

result

2.0

i=25; j=10; result = i/j;

100

50 50

Fall 2012

CSD Univ. of Crete

Binary Operators Expressions involving only integers are evaluated using integer

arithmetic

float result; int i,j;

result

2.5

i=25; j=10; result = (float) i/j; 101

Fall 2012

CSD Univ. of Crete

Quick Review of / and %  





Remember when both operands are integers, / performs integer division This simply truncates your answer: -11/3 is -3 and 5/4 is 1 The % operator simply computes the remainder of dividing the first operand by the second If the first operand is negative then the answer will also be negative (or zero) If the first operand is positive, then the answer will also be positive (or zero) Examples: 11 %3 is 2 11 %-3 is 2 -11 %3 is -2 -11 %-3 is -2 If you are at all unsure how these work, please try a few out on your own, compile and run them This is as easy as running a program with the statement System.out.println(System.out.println(-11%11%-3); 102

51 51

Fall 2012

CSD Univ. of Crete

Binary Operators Assignment Assign sum

+= Assign difference

-= Assign product

*= Assign quotient

/= Assign remainder

%=

103

Fall 2012

CSD Univ. of Crete

Binary Operators Assignment Compound operators provide a convenient shorthand

int i; i = i + 5; i += 5;

104

52 52

Fall 2012

CSD Univ. of Crete

Binary Operators Relational Less than

< Greater than

> Less than or equal to

=

105

Fall 2012

CSD Univ. of Crete

Binary Operators Relational Equal to

= = Not equal to

!=

106

53 53

Fall 2012

CSD Univ. of Crete

Equality Testing  Identity or simple equality

Two variables refer to the same object or String Value equality  Two object variables have the same contents Test for identity using the equality operators For value equality use the equals() method defined on Java Objects Example: 

   

if ( nameString.equals(“Hi”) ) { }

107

Fall 2012

CSD Univ. of Crete

Equality vs. Identity

108

54 54

Fall 2012

CSD Univ. of Crete

Comparing Floating Point Values  We also have to be careful when comparing two floating point values

(float float or double) double for equality  You should rarely use the equality operator (== ==) == when comparing two floats  In many situations, you might consider two floating point numbers to be "close enough" even if they aren't exactly equal  Therefore, to determine the equality of two floats, you may want to use the following technique:

if (Math.abs (f1 - f2) < 0.00001) System.out.println ("Essentially equal.");

109

Fall 2012

CSD Univ. of Crete

Binary Operators Logical Logical AND

&& Logical OR

||

110

55 55

Fall 2012

CSD Univ. of Crete

Binary Operators Expressions connected by && and || are evaluated from left to right

This never gets evaluated! class Test { public static void main(String[] args) { int i=0; System.out.println("Test:" + ((2> One’s complement

~ Bitwise AND

& Bitwise XOR

^ Bitwise OR

|

112

56 56

Fall 2012

CSD Univ. of Crete

Binary Operators Bitwise The right sift operator >>> does not preserves the sign but rather fills the vacated positions with zeros

The right sift operator >> preserves the sign

byte b = 3; // 00000011 in binary (byte is 8 bits) b >> 1;

// 00000001 in binary, 1 in decimal

b > 1;

// 11111110 in binary, -2 in decimal

b >>> 1;

// 01111110 in binary, 126 in decimal

113

Fall 2012

CSD Univ. of Crete

Ternary Operators





114

57 57

Fall 2012

CSD Univ. of Crete

Ternary Operators Operator





115

Fall 2012

CSD Univ. of Crete

Ternary Operators

x

☺ Operand

y

 Operand

z Operand

116

58 58

Fall 2012

CSD Univ. of Crete

Ternary Operators Conditional “if a then x, else y”

a?x:y result = (x