1 159.234lecture 159.234 lecture java 26 introduction

61
1 159.234 159.234 LECTURE LECTURE JAVA JAVA 26 26 Introduction

Upload: ashlyn-marshall

Post on 12-Jan-2016

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

1

159.234159.234 LECTURE LECTURE

JAVAJAVA

2626

Introduction

Page 2: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

2

• This section is intended as a rapid introduction to programming in the Java programming language and environment, focusing on the core language features.

• A number of worked example programs will be used as the main vehicle for exposition of the Java programming language features.

• The API's for the various packages will not be covered in detail.

• This course does not cover the topics of Networking or Threads.

Introduction toIntroduction to Java Java

Page 3: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

The The JavaJava Programming Language Programming Languagehttp://java.sun.comhttp://java.sun.com

“Write once, run anywhere”

Platform independent programs with features such as graphics, audio, video, and Internet connectivity.

developed by James Gosling at Sun Microsystems in the early 90’s

ideal for developing secure, distributed, network-based end-user applications in environments ranging from network-embedded devices to the World-Wide Web and the desktop.

Page 4: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

4

• Java is a programming language definition and an environment (J2SE SDK)

• As a language: Object Oriented, multi-threaded; dynamic loading; code checking for security and type safety.

• Large growing set of utilities and other library packages in accompanying development kit.

Language and EnvironmentLanguage and Environment

Page 5: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

The The JavaJava Programming Language Programming Languagehttp://java.sun.comhttp://java.sun.com

Java Virtual Machine – a

program that runs the bytecode

Java Virtual Machine – a

program that runs the bytecode

There’s a JVM for any Computer ++ Windows, Sun Solaris, Linux, Macintosh, etc.

Source code is compiled into its corresponding generic bytecode language

Page 6: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

6

Web BrowserWeb Browser

Elements of Elements of JavaJava

Netscape, Internet Explorer, Mozilla come bundled with the JVM.

Source codes and bytecodes are independent of the type of computer system.

Web page

Instructions to load a Java program

Web page

Instructions to load a Java program JVM

Browser automatically downloadsthe bytecode file and runs the JVM on it.

Page 7: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

7

Elements of Elements of JavaJavaAll Java programs are compiled to execute on a Java Virtual Machine (Java VM)

EditorEditor

MyProgram.java MyProgram.class

Java Compiler

Java Interpreter

bytecode

Java VM is simulated by a special program called Java Runtime Environment (JRE)

Special machine language known as bytecode

A version of JRE has been created for each Computer + OS combination.

JRE loads and verifies the bytecode to make sure that the program is valid.

JRE runs a Java Interpreter or possibly a just-in-time compiler (JIT) that converts the bytecode into the machine code of the particular computer

bytecode is independent of any particular computer hardware.

JREe.g. scite

Page 8: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

8

1. Java Programming Language

2. Java Runtime Environment

3. Java Application Programming Interface (API)

Elements of Elements of JavaJava

EditorEditor

MyProgram.javaMyProgram.class

Java Compiler

Java Interpreter

one timeonly

every time

bytecode

Tailored for a specific computer

Page 9: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

9

• Java Virtual Machine (JVM) constitutes:– the Run Time Environment (RTE)– Garbage Collector (GC) - as a separate thread– Security model

• JVM defines the:– Class file format– the register set– the Stack– Instruction set– Garbage collected heap– Memory area

The Java Virtual MachineThe Java Virtual Machine

Page 10: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

10

/*

This program prints out “Hello, World!” on the standard output and quits. It defines a class “HelloWorld” and a “mainmain” method within that class

*/

public class HelloWorld{

//Define the main method

public static void main( String args[] ) {

System.out.println(”Hello World!"); //print line

}

}

‘‘Hello, World!’ ExampleHello, World!’ ExampleA simple applicationA simple application

Comments

Class Definition

Method Definition

ExecutableStatement

A Java application consists of one or more classes defining data and methods.

Page 11: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

11

/*

This program prints out “Hello, World!” on the standard output and quits. It defines a class “HelloWorld” and a “main” method within that class

*/

public class HelloWorld{

//Define the main method

public static void main( String args[] ) { //must appear in every Java //application

System.out.println(”Hello World!"); //print line

}

}

‘‘Hello, World!’ ExampleHello, World!’ Example

Comments

Class Definition

Method Definition

ExecutableStatement

Every Java application must have at leastat least one user-defined class, and that class must contain a method named main, which is where the program startsexecuting.

Simplest possible Java application : - single class with single method main.

Page 12: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

12

public class HelloWorld{

//Define the main method

public static void main( String[] args ) {

System.out.println(”Hello World!");

}

}

‘‘Hello, World!’ ExampleHello, World!’ Example

public: can be accessed from any other class in a Java

program

static: means method can be run without first creating an object

from this class

public: can be invoked by any

caller

Filename: HelloWorld.java

To compile: javac HelloWorld.java

To run: java HelloWorldcase-sensitive

By convention, first letter of each word in a class name is capitalized (no space or underscore in between).

Contains any command-line

arguments passed to the program

Name of the class being defined mustbe the same as the name of the filecontaining the class (.java extension)

Page 13: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

13

public class Hello2{ public static void main(String[] args){ String greetings = "Hello world!"; System.out.println(greetings); }}

‘‘Hello, World!’ ExampleHello, World!’ Example

VARIANTSpublic class Hello3{

private static String greetings = "Hello world!";

public static void main(String[] args){

System.out.println(greetings);

}

}

public class Hello4{

private String greetings = "Hello world!";

public Hello4(){

System.out.println(greetings);

}

public static void main(String[] args){

new Hello4();

}

}

public class Hello{

public static void main(String[] args){

System.out.println("Hello,World!");

}

}

Page 14: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

14

‘‘Hello, World!’ ExampleHello, World!’ Example

public class Hello4{

private String greetings = "Hello world!";

public Hello4(){

System.out.println(greetings);

}

public static void main(String[] args){

new Hello4();

}

}

Static methods cannot use directly non-static fields and methods.

The main method is always declared static.

Constructors act like static methods, but are not explicitly declared static.

Constructors has no type,Its name is the same as the class name, and it is invoked byusing the keyword new.

Page 15: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

15

• Things that might go wrong: case sensitivity; files not found; class not found…

• main() structure, necessary for system/JVM

• System is class;

• out is static variable of type PrintStream;

• println() is a method; also System.err.print()

• note comment structure

• path and CLASSPATH need to be set up for this to work (find java and javac, and have . on CLASSPATH )

Hello World ExampleHello World Example

Page 16: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

Features Removed from C / C++Features Removed from C / C++

16

http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076

Page 17: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

17

• This section discusses features removed from C and C++ in the evolution of Java.

• The first step was to eliminate redundancy from C and C++. In many ways, the C language evolved into a collection of overlapping features, providing too many ways to say the same thing, while in many cases not providing the needed features. C++, in an attempt to add "classes in C", merely added more redundancy while retaining many of the inherent problems of C.

Features Removed from C/C++Features Removed from C/C++

http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076

Page 18: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

18

• No preprocessor (operates on the source text, prior to any parsing, by performing simple substitution of tokenized character sequences according to user-defined rules.

(begins with ‘#’ as directives)• No #define and related capabilities• No typedef• No header files, the Java language source files provide the

declarations of other classes and their methods

• Too many #defines and typedefs results in every programmer inventing another language

Features Removed from C/C++Features Removed from C/C++1) No More Typedefs, Defines, or Preprocessor 1) No More Typedefs, Defines, or Preprocessor

http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076

Problem with C/C++

Page 19: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

19

• Instead of #define, use constants• Instead of typedef, declare classes• Instead of header files, Java compiles class definitions into a binary form

• Java becomes remarkably context-free without these• This will reduce the amount of context you need to understand before starting

with your coding.

Features Removed from C/C++Features Removed from C/C++1) No More Typedefs, Defines, or Preprocessor 1) No More Typedefs, Defines, or Preprocessor

http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076

Page 20: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

20

• Java has no structures or unions as complex data types.• You don't need structures and unions when you have classes;

you can achieve the same effect simply by declaring a class with the appropriate instance variables.

Features Removed from C/C++Features Removed from C/C++2) No More Structures or Unions 2) No More Structures or Unions

http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076

The code fragment below declares a class called Point. class Point extends Object { double x; double y; // methods to access the

// instance variables }

class Rectangle extends Object { Point lowerLeft; Point upperRight; // methods to access the instance //variables }

In C, these would be defined as structures, in Java, you simply declare classes

Page 21: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

21

• Java has no enum types. • You can obtain something similar to enum by declaring a class whose only

raison d'etre is to hold constants.

Features Removed from C/C++Features Removed from C/C++3) Originally No Enums (enum was introduced eventually)3) Originally No Enums (enum was introduced eventually)

http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076

You could use this feature something like this:

class Direction extends Object { public static final int North = 1; public static final int South = 2; public static final int East = 3; public static final int West = 4; }

You can now refer to, say, the South constant using the notation Direction.South.

Page 22: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

22

Features Removed from C/C++Features Removed from C/C++3) Originally No Enums (enum was introduced eventually)3) Originally No Enums (enum was introduced eventually)

http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076

You could use this feature something like this:

class Direction extends Object { public static final int North = 1; public static final int South = 2; public static final int East = 3; public static final int West = 4; }

You can now refer to, say, the South constant using the notation Direction.South.

Using classes to contain constants in this way provides a major advantage over C's enum types. In C (and C++), names defined in enums must be unique: if you have an enum called HotColors containing names Red and Yellow, you can't use those names in any other enum. You couldn't, for instance, define another Enum called TrafficLightColors also containing Red and Yellow.

Page 23: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

23

Features Removed from C/C++Features Removed from C/C++3) Originally No Enums (enum was introduced eventually)3) Originally No Enums (enum was introduced eventually)

http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076

class CompassRose extends Object { public static final int North = 1; public static final int NorthEast = 2; public static final int East = 3; public static final int SouthEast = 4; public static final int South = 5; public static final int SouthWest = 6; public static final int West = 7; public static final int NorthWest = 8; }

There is no ambiguity because the name of the containing class acts as a qualifier for the constants. In the second example, you would use the notation CompassRose.NorthWest to access the corresponding value. Java effectively provides you the concept of qualified enums, all within the existing class mechanisms.

Page 24: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

24

Features Removed from C/C++Features Removed from C/C++3) enum (J2SE 5.0) – it’s a full-fledged class!3) enum (J2SE 5.0) – it’s a full-fledged class!

http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html

public enum Planet { MERCURY (3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), EARTH (5.976e+24, 6.37814e6), ... PLUTO (1.27e+22, 1.137e6); private final double mass; // in kg. private final double radius; // in meters Planet(double mass, double radius) { this.mass = mass; this.radius = radius; }

The enum type Planet contains a constructor, and each enum constant is declared with parameters to be passed to the constructor when it is created.

public double mass() { return mass; } public double radius() { return radius; }

// universal gravitational constant (m3 kg-1 s-2)

public static final double G = 6.67300E-11;

public double surfaceGravity() { return G * mass / (radius * radius); } public double surfaceWeight(double otherMass) { return otherMass * surfaceGravity(); }}

Page 25: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

25

Features Removed from C/C++Features Removed from C/C++3) enum (J2SE 5.0) – it’s a full-fledged class!3) enum (J2SE 5.0) – it’s a full-fledged class!

public static void main(String[] args) { double earthWeight = Double.parseDouble(args[0]); double mass = earthWeight/EARTH.surfaceGravity();

for (Planet p : Planet.values()) System.out.printf("Your weight on %s is %f%n“, p, p.surfaceWeight(mass)); }

Here is a sample program that takes your weight on earth (in any unit) and calculates and prints your weight on all of the planets (in the same unit):

$ java Planet 175Your weight on MERCURY is 66.107583Your weight on VENUS is 158.374842Your weight on EARTH is 175.000000Your weight on MARS is 66.279007...

http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html

Page 26: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

26

Features Removed from C/C++Features Removed from C/C++4) No More Functions 4) No More Functions

http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076

class Point extends Object { double x; double y; public void setX(double x) { this.x = x; } public void setY(double y) { this.y = y; } public double getX() { return x; } public double getY() { return y; } }

If the x and y instance variables are private to this class, the only means to access them is via the public methods of the class.

• Anything you can do with a function you can do just as well by defining a class and creating methods for that class

Page 27: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

27

Features Removed from C/C++Features Removed from C/C++5) No More Multiple Inheritance 5) No More Multiple Inheritance

http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076

• An interface is not a definition of a class. Rather, it's a definition of a set of methods that one or more classes will implement.

• An interface is like an abstract base class in C++.

• An important issue of interfaces is that they declare only methods and constants.

• Variables may not be defined in interfaces.

• Multiple inheritance--and all the problems it generates--was discarded from Java. The desirable features of multiple inheritance are provided by interfaces

Page 28: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

28

Features Removed from C/C++Features Removed from C/C++5) No More Multiple Inheritance 5) No More Multiple Inheritance

http://java.sun.com/docs/books/tutorial/java/IandI/createinterface.html

public interface OperateCar {

// constant declarations, if any

// method signatures int turn(Direction direction, // An enum with values RIGHT, LEFT double radius, double startSpeed, double endSpeed); int changeLanes(Direction direction, double startSpeed, double endSpeed); int signalTurn(Direction direction, boolean signalOn); int getRadarFront(double distanceToCar, double speedOfCar); int getRadarRear(double distanceToCar, double speedOfCar); ...... // more method signatures}

Page 29: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

29

Features Removed from C/C++Features Removed from C/C++5) No More Multiple Inheritance 5) No More Multiple Inheritance

interface TargetPursuitTargetPursuit{ public boolean targetDestroyed(int x, int y); public int distance(int x, int y); }interface ObstacleAvoidanceObstacleAvoidance{ public boolean safeDistance(); public void findObstacles(); }

public class Robot{ protected void initialize(){ //Codes for initialize } protected void switchRole(){ //Codes for switchRole } protected void retreat(){ //Codes for retreat } }

public class Attacker extends Robot implements TargetPursuit, ObstacleAvoidance { // Code here does something }

Page 30: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

30

Features Removed from C/C++Features Removed from C/C++6) No More Goto Statements6) No More Goto Statements

http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076

• As mentioned above, multi-level break and continue remove most of the need for goto statements.

• Java has no goto statement. Studies illustrated that goto is (mis)used more often than not simply "because it's there".

• Eliminating goto led to a simplification of the language--there are no rules about the effects of a goto into the middle of a for statement, for example.

• Studies on approximately 100,000 lines of C code determined that roughly 90% of the goto statements were used purely to obtain the effect of breaking out of nested loops.

Page 31: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

31

Features Removed from C/C++Features Removed from C/C++7) No More Operator Overloading7) No More Operator Overloading

http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076

• Eliminating operator overloading leads to great simplification of code.• There is one exception though, look at the String class:

String s1 = “meet me”;

String s2 = “ at sunset”;

String s = s1 + s2;

• There are no means provided by which programmers can overload the standard arithmetic operators.

• Once again, the effects of operator overloading can be just as easily achieved by declaring a class, appropriate instance variables, and appropriate methods to manipulate those variables.

Page 32: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

32

Features Removed from C/C++Features Removed from C/C++8) No More Automatic Coercions8) No More Automatic Coercions

http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076

• In Java, the assignment of myFloat to myInt would result in a compiler error compiler error indicating a possible loss of precision and that you must use an explicit cast.

• Java prohibits C and C++ style automatic coercions. If you wish to coerce a data element of one type to a data type that would result in loss of precision, you must do so explicitly by using a cast. Consider this code fragment:

int myInt;double myFloat = 3.14159;

myInt = myFloat;myInt = myFloat;

// This will only result to a warning in C++!

Thus, you should re-write the code fragments as:

int myInt; double myFloat = 3.14159; myInt = (int)myFloat;myInt = (int)myFloat;

Page 33: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

33

Features Removed from C/C++Features Removed from C/C++9) No More Pointers9) No More Pointers

http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076

• Most studies agree that pointers are one of the primary features that enable programmers to inject bugs into their code. Given that structures are gone, and arrays and strings are objects, the need for pointers to these constructs goes away. Thus, Java has no pointer data types.

• Any task that would require arrays, structures, and pointers in C can be more easily and reliably performed by declaring objects and arrays of objects.

• Instead of complex pointer manipulation on array pointers, you access arrays by their arithmetic indices.

• The Java run-time system checks all array indexing to ensure indices are within the bounds of the array.

• You no longer have dangling pointers and trashing of memory because of incorrect pointers, because there are no pointers in Java.

Page 34: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

34

http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076

Applet

Page 35: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

35

import javax.swing.*;import java.awt.*;

public class HelloWorldApplet extends JApplet{ String message;

public void init() { message = "Hello World"; }

public void paint(Graphics artist) { artist.drawString(message, 20, 30); }}

‘‘Hello, World!’ Hello, World!’ appletapplet

Applet inherits a paint() method from JApplet class that can be used to paint

text, shapes and graphics into the applet’s display area.

A web page will display an applet program in a display area that is embedded between the other contents on that page.

By default, this will appear as a blank canvas onto which text, Swing components, graphics and images can be painted by the applet program.

Knows how to render content onto

the canvas.

Serves like a constructor for initializing variables and for adding Swing components to the applet’s

interface.

The paint method is called spontaneously.

Page 36: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

36

<html>

<head>

<title>Hello World Applet</title></head>

<body>

<applet code = "HelloWorldApplet.class"width = "300" height = "60">

You require a Java-enabled browser to view this applet.

</applet>

</body>

</html>

‘‘Hello, World!’ Hello, World!’ appletapplet

Default text

To embed a Java applet in a web page, the HTML code must specify the name of the applet file and the size of the applet’s display area that is to be allocated on the page.

The information is specified in the body of the web page with attributes of the HTML <applet> tag.

Canvas size of 300x60 pixels in which the applet

will run.

code attribute is assigned the name of the compiled applet file

including its .class extension.

This pair of tags can surround a text message thatwill only be displayed if the applet cannot be executed.

Embedding in a web page

Page 37: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

37

‘‘Hello, World!’ Hello, World!’ appletappletJava SDK includes AppletViewer for testingCompiled programs with the Java interpreter.

Both the HTML file and compiled applet file should be saved together in a directory.

Appletviewer will display the applet but not other contents in a

web page.

Appletviewer HelloWorldApplet.htmlAppletviewer HelloWorldApplet.html

Testing with Applet Viewer

The applet can now be tested from a command prompt:

Appletviewer will open a window that displays the HelloWorldApplet program:

Page 38: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

39

Another form of JavaAnother form of Java comment comment

javadoc is an automatic system for generating program documentation directly from comments embedded in Java programs.

javadoc comments start with the symbol /** end with the symbol */, and can stretch over multiple lines.

These comments are automatically copied from Java source code into documentation when the javadoc program is executed.

javadoc is described in the Java SDK documentation.

Page 39: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

40

javadocjavadocJAVA DOCUMENTATIONJAVA DOCUMENTATION

/* * @(#)Person.java 1.0 04/10/05 * Copyright 2005 Reyes Consulting, Inc. */

//import java.util.Date;import java.util.*;

/** * A class whose objects represent people. * @author Napoleon R * @version 1.0 04/10/05 * @see java.util.Date * @since 1.2 */

public class Person{ private String name; private Date dob; //date of birth private String address;

/** * Constructs a Person object. * @param aName the name of this person. */public Person(String aName){ this.name = aName;}

/** * Constructs a Person object. * @param aName the name of this person. * @param aDob this person's date of birth */public Person(String aName, Date aDob){ this.name = aName; this.dob = aDob;}

See person.html

javadoc Person.java

Page 40: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

41

javadocjavadocJAVA DOCUMENTATIONJAVA DOCUMENTATION

/** * Returns a string that contains info. about this person * @return a string that contains info. about this person. */public String toString(){ return name + "(" + dob + ")";}

/** * prints info. about the person */public void printinfo(){ System.out.println(name); System.out.println(address); System.out.println(dob);}/** * sets address of person */public void setAddress(String a) { address = a;}

/** * sets date of birth of person */public void setDateOfBirth(int year, int month, int day){ // Get object of type calendar and set it to the given date Calendar c = Calendar.getInstance(); c.set(year, month, day, 0, 0, 0);

// Get a date object and assign it to dateOfBirth dob = c.getTime();}

static public void main(String[] args) {

Person p = new Person("Napoleon"); p.setAddress("Albany"); p.setDateOfBirth(1900, 4, 25); p.printinfo();}

} //end of class Person See person.html

Page 41: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

42

//// Primitive Types Example Program//public class Types{ public static void main( String args[] ) {

boolean b = true; // try out various primitive byte eight = 8; // type declarations short little = 16384; int i, j, k; long l = 42LL; float f; double d; double e = 2.71828182846; char ch ='a';

i = 12; j = 032; k = 0x0xFF; // try out some simple f = 3.141592654FF; // assignments d = (double) f; i = eight; // try vagaries of string concatenation System.out.println("d is: " + d ); System.out.println(i + f + d + j + k + " " + b ); System.out.println(eight + little + " using arithmetic"); System.out.println(eight + " " + little + " using arithmetic"); }}

• boolean• byte, short, int, long• float, double - IEEE 754• char• reference type is used for objects

• Results:> java Typesd is: 3.1415927410125732295.2831857204437 true16392 using arithmetic8 16384 using arithmetic>

JavaJava Primitive Data Types Primitive Data Types

Page 42: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

43

• literals int unless L or l suffix used• octal using leading 0 and hex using leading 0x• real numbers are double unless F or f suffix (opposite

to int)• There is a definite memory model for these, sizes of

primitives fixed - see table• Strings and arrays are special reference types

The range of values are given in the next slide.

JavaJava Literals Literals

Page 43: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

44

Type Description Default Size(bits) Min/Maxboolean true/false false 1 Not applicable

char Unicode character \u0000 16 \u0000

\uFFFF

byte Signed integer 0 8 -128

127

short Signed integer 0 16 -32768

32767

int Signed integer 0 32 -2147483648

2147483647

long Signed integer 0 64 -9223372036854775808

9223372036854775807

float IEEE 754 Floating point

0.0 32 +/- 1.40239846E-45

+/- 3.40282347E+38

double IEEE 754 floating point

0.0 64 +/- 4.94065645841246544E-324

+/- 1.79769313486231570E-308

Java Data Types Memory UsageJava Data Types Memory Usage

Page 44: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

45

• http://java.sun.com/docs/codeconv/index.html

• http://java.sun.com/j2se/1.5.0/docs/guide/language/index.html

Coding ConventionsCoding Conventions

UpdatesUpdates

http://java.sun.com/j2se/1.5.0/docs/api/index.html

APIAPI

Page 45: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

46

Interactive String Input (old approach)Interactive String Input (old approach)

Import java.io.*;BufferedReader in;throws IOExceptionin = new BufferedReader(new InputStreamReader(System.in));

This code creates an object, named in, that can execute its

readLine() method to input strings interactively.

To input a string, you need these pieces of Java code:

Java manages all input through stream objects, which throw exceptionsthat are meant to be caught.

To read one string per line of input, you can use:

in.readLine()import java.io.*;class Hello{ public static void main(String[] args) throws IOException{ BufferedReader in; in = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter your name: "); String name = in.readLine(); System.out.println("Hello, " + name); }}

Interactive Hello

Reads bytes and translates them into characters

according to a specified character encoding

Read text from a character-input stream, buffering characters for efficient

reading of characters, arrays, and lines

Page 46: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

47

Interactive String Input (since v.5) Interactive String Input (since v.5)

import java.util.Scanner;

To input a string, you need this:

To read one string per line of input, you can use:

nextLine()import java.util.Scanner; class Hello2{ public static void main(String[] args) {

Scanner input = new Scanner(System.in); System.out.print("Enter your name: ");

String name = input.nextLine(); System.out.println("Hello, " + name); }}

Interactive Hello

Read text from a character-input stream, buffering characters for efficient

reading of characters, arrays, and lines

Page 47: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

48

Interactive Numeric Input (since v.5) Interactive Numeric Input (since v.5)

import java.util.Scanner;

To input a number, you this:

To read a number, you can use one of the following:

nextInt(), nextFloat(), nextDouble(), nextByte(), etc…

import java.util.Scanner;

class Addition2{ public static void main(String[] args) { Scanner input = new Scanner(System.in); int num1, num2, sum;

System.out.print("Enter first integer: "); num1 = input.nextInt(); System.out.print("Enter second integer: "); num2 = input.nextInt(); sum = num1 + num2; System.out.printf("Sum is %d\n", sum); }}

Interactive Addition

Page 48: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

49

Classes and ObjectsClasses and ObjectsClass Point public class Point{

private int x, y;public Point(int x, int y){ this.x = x; this.y = y;}public boolean equals(Point p){ return (x == p.x && y == p.y);}public int getX(){ return x;}public int getY(){ return y;}public String toString(){ return new String("(" + x + ", " + y + ")");}

}

This has no main() method and so it cannot be executed as a Java program.

Whenever an object of this class is expected to return a

String, the compiler automatically invokes the

toString() method.

Page 49: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

50

Classes and ObjectsClasses and Objects

public class TestPoint{public static void main(String args[]){

Point p = new Point(2, -3);

System.out.println("p: " + p); System.out.println("p.getX(): " + p.getX());System.out.println("p.getY(): " + p.getY());Point q = new Point(7,4);System.out.println("q: " + q); System.out.println("q.equals(p): " + q.equals(p));

System.out.println("q.equals(q): " + q.equals(q)); }

}

TestPoint

For as long as the resulting Point.class file is in the same folder as our TestPoint.java file, we can compile and run our test program.

Page 50: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

51

3 main kinds of declarations in a Java class3 main kinds of declarations in a Java class

Syntax

Fields Modifiers type name;

Constructors Modifiers class_name (parameters) { statements}

Methods Modifers return_type name (parameters) clause { statements}

Page 51: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

52

Class ModifiersClass Modifiers

Modifier Meaning

abstract The class cannot be instantiated

final The class cannot be extended

public Its members can be accessed from any other class.

Page 52: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

53

Field ModifiersField Modifiers

Modifier Meaning

final It must be initialized and cannot be changed

private It is accessible only from within its own class

protected It is accessible only from within its own class and its extensions.

public It is accessible from all classes

static The same storage is used for all instances of the class.

transient It is not part of the persistent state of an object

volatile It may be modified by asynchronous threads

Examples:

private double m;private transient String middleName;

Page 53: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

54

Constructor ModifiersConstructor Modifiers

Modifier Meaning

private It is accessible only from within its own class.

protected It is accessible only from within its own class and its extensions.

public It is accessible only all classes.

Page 54: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

55

Method ModifiersMethod Modifiers

Modifier Meaning

final It cannot be overridden in class extensions

native Its body is implemented in another programming language.

private It is accessible only from within its own class.

protected It is accessible only from within its own class and its extensions.

static It has no implicit argument.

synchronized It must be locked before it can be invoked by a thread.

volatile It may be modified by asynchronous threads.

Page 55: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

56

Local Variable ModifierLocal Variable Modifier

Modifier Meaning

final It must be initialized and cannot be changed.

Page 56: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

57

Access ModifiersAccess ModifiersThe three access modifiers, public, protected, and privatepublic, protected, and private, are used to specify where the declared entity (class, field, constructor, or method) can be used.

If none of these is specified, then the entity has package access, which means that it can be accessed from any class in the same package.

Page 57: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

58

Access ModifiersAccess ModifiersThe modifier finalfinal has three different meanings, depending upon which kind of entity it modifies.

If it modifies a class, it means that the class cannot have subclasses.

If it modifies a field or a local variable, it means that the variable must be initialized and cannot be changed (i.e. constant).

If it modifies a method, it means that the method cannot be overridden in any subclass.

public final class MyFinalClass {...}

public class MyClass { public final void myFinalMethod() {...}}

public final double radius;public final double xpos;

Page 58: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

59

Access ModifiersAccess ModifiersThe modifier static static is used to specify that a method is a class method. Without it, the method is an instance method.

An instance method is a method that can be invoked only when bound to an object of the class. That object is called an implicit argument of the method invocation.

For example, p.getX(); //getX() is bound to object p, so p is its implicit argument.

A class method (or static method) is a method that is invoked without being bound to any specific object of the class.

Note that every program’s main() method is a class method.

See next slide for an example...

Page 59: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

60

Classes and ObjectsClasses and ObjectsClass Point public class Point{

private int x, y;public Point(int x, int y){ this.x = x; this.y = y;}...public static double distanceBetween(Point p1, Point p2){ double dx = p2.x – p1.x; double dy = p2.y – p1.y; return Math.sqrt(dx*dx + dy*dy);}

}

...//sample function callSystem.out.println(“distance = “ + Point.distanceBetween(p, q));

In a separate program,

Page 60: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

61

// Structure of Java programs, Example// package XYZ; // if missing, file is part of anonymous packageimport java.lang.*; // importspublic class Structure{ // at most one public class per file // if class is public, then must match filename // member variables and methods follow in any order public static int instancecount = 0; // shared by all instances private int serialnumber; // belongs to an instance object Structure(){ System.out.println(" A Structure has been constructed "); instancecount++; serialnumber = instancecount; } public int getserialnumber(){ // return serial number of instance return serialnumber; } public int getinstancecount(){ // return number of objects return instancecount; // instantiated so far } public static void main(String args[]){ // main must match this pattern if present System.out.println("arguments are:"); for(int i=0;i<args.length;i++){ System.out.println(args[i]); // NB, no argc nor C-like argv[0] } library(); // accessible since it is a class method Structure s = new Structure(); s.test(); // invoke instance's test method System.out.println( "Serial No is: " + s.getserialnumber() ); s = new Structure(); // create a new instance, discard old one System.out.println("instancecount is " + instancecount); // access direct since main is part of the class ancillary.help(); } public void test(){ // an instance method System.out.println("test method in class Structure"); } public static void library(){ System.out.println("Callable without an instantiation of class"); // will need to be called as Structure.library() outside this class }}class ancillary{ static void help(){ System.out.println("No help information available"); }}

• Java Source File Structure:– package statement (optional, defaults

to anonymous package)

– import statement(s) (optional)

– class definition(s)

– at most one public class per file, whose name must match filename

– class(es) contain member variables and methods in any order

• Results:> java Structure

arguments are:

Callable without an instantiation of class

A Structure has been constructed

test method in class Structure

Serial No is: 1

A Structure has been constructed

instancecount is 2

No help information available

>

Page 61: 1 159.234LECTURE 159.234 LECTURE JAVA 26 Introduction

62

Objects and References to ThemObjects and References to ThemLifetime of an object

public class TestPoint2{public static void main(String args[]){ Point p = null, q = null; p = new Point(2, -3); //p gets memory from heap q = p; //both p and q points to the same memory location p = new Point(7,4); //p gets a new memory location again q = p; //the previous memory location pointed by q is garbage-collected p = null; //q still points to the memory alloted for p earlier q = null; //the object pointed by q earlier will be garbage collected.}

}

The life of an object begins when it is created by a constructor, and it continues as long as there is at least one reference to it. When its last reference has been reassigned, then the object dies.