Prof Darshana Mistry HOD of Computer Department Gandhinagar Institute Of Technology

69
Prof Darshana Mistry HOD of Computer Department Gandhinagar Institute Of Technology Core Java 1

description

Prof Darshana Mistry HOD of Computer Department Gandhinagar Institute Of Technology. Core Java. James Gosling and Sun Microsystems Oak Java, May 20, 1995, Sun World HotJava The first Java-enabled Web browser JDK Evolutions - PowerPoint PPT Presentation

Transcript of Prof Darshana Mistry HOD of Computer Department Gandhinagar Institute Of Technology

Page 1: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Prof Darshana MistryHOD of Computer Department

Gandhinagar Institute Of Technology

Core Java

1

Page 2: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

2

HistoryJames Gosling and Sun MicrosystemsOakJava, May 20, 1995, Sun WorldHotJava

◦The first Java-enabled Web browserJDK EvolutionsJ2SE, J2ME, and J2EE (not mentioned in

the book, but could discuss here optionally)

Page 3: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

3

Characteristics of Java Java is simple Java is object-oriented Java is distributed Java is interpreted Java is robust Java is secure Java is architecture-neutral Java is portable Java’s performance Java is multithreaded Java is dynamic

Page 4: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Versions of Java Java Language vs Java Platform

◦ Current version of the language is 1.4.1◦ Core language plus additional APIs is called the Java 2

platform◦ Three versions of the Java 2 Platform, targetted at different

uses Java 2 Micro Edition (J2ME)

◦ Very small Java environment for smart cards, pages, phones, and set-top boxes

◦ Subset of the standard Java libraries aimed at limited size and processing power

Java 2 Standard Edition (J2SE)◦ The basic platform, which this course will cover

Java 2 Enterprise Edition (J2EE)◦ For business applications, web services, mission-critical

systems◦ Transaction processing, databases, distribution, replication

Page 5: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

The Java APIs Sun are constantly adding new features and APIs The Core Java API is now very large

◦ Often difficult to keep up with every change Separate set of extension APIs for specific purposes

◦ E.g. Telephony, Web applications, Game programming All new developments reviewed through Java

Community Process (http://www.jcp.org)◦ Chance for developers to provide feedback on emerging

standards and APIs◦ Useful to keep an eye on what's coming through

Also a wide range of “open source“ APIs available◦ E.g. through the Jakarta project (http://jakarta.apache.org)

Page 6: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Useful ResourcesUseful resources on the webJava home (http://java.sun.com)

◦ Articles, Software and document downloads, TutorialsJava Developer Services

http://developer.java.sun.com◦ Early access downloads, forums, newsletters, bug database

Javaworld (http://www.javaworld.com)◦ Java magazine site, good set of articles and tutorials

IBM developerWorks (http://www.ibm.com/developerWorks)◦ Technology articles and tutorials

Page 7: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Java programs are compiled to BytecodeBytecode is then interpreted by a JVM, or Java Virtual machine.The virtual machine is what runs

your program.It’s the JVM that cares about your Operating

system, NOT THE PROGRAM!WORA - Write Once, Run Anywhere!

Is Java Interpreted or Compiled?

BOTH!!

Page 8: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Compiling and Executing of Java Program

Page 9: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

The Virtual MachineJava is both compiled and interpreted

◦ Source code is compiled into Java bytecode◦ Which is then interpreted by the Java Virtual Machine (JVM)◦ Therefore bytecode is machine code for the JVM

Java bytecode can run on any JVM, on any platform◦ …including mobile phones and other hand-held devices

Networking and distribution are core features◦ In other languages these are additional APIs◦ Makes Java very good for building networked applications,

server side components, etc.

Page 10: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Features of the JVMThe Garbage Collector

◦ Java manages memory for you, the developer has no control over the allocation of memory (unlike in C/C++).

◦ This is much simpler and more robust (no chance of memory leaks or corruption)

◦ Runs in the background and cleans up memory while application is running

The Just In Time compiler (JIT)◦ Also known as “Hot Spot”◦ Continually optimises running code to improve performance◦ Can approach the speed of C++ even though its interpreted

Page 11: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Features of the JVMSecurity

◦ Java offers very fine control over what an application is allowed to do

◦ E.g. Read/write files, open sockets to remote machines, discover information about the users environment, etc

◦ Used in Java Applets to create a “sandbox”. Stops a rogue applet attacking your machine.

◦ Makes Java very safe, an important feature in distributed systems

Class Loading◦ Loading of bytecode into the virtual machine for execution◦ Code can be read from a local disk, over a network, or the

Internet◦ Allows downloading of applications and applets on the fly◦ …and even ‘mobile code’

Page 12: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Is Java Object Oriented?

YES!

Every bit of code in a Java program is in a “Class”

Code Reuse, Encapsulation, Polymorphism, Inheritance

Page 13: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Object-Oriented ProgrammingUnderstanding OOP is fundamental to writing

good Java applications◦ Improves design of your code◦ Improves understanding of the Java APIs

There are several concepts underlying OOP:◦ Abstract Types (Classes)◦ Encapsulation (or Information Hiding)◦ Aggregation◦ Inheritance◦ Polymorphism

Page 14: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

What is OOP?Modelling real-world objects in softwareWhy design applications in this way?

◦We naturally classify objects into different types.◦By attempting to do this with software aim to make

it more maintainable, understandable and easier to reuse

In a conventional application we typically:◦decompose it into a series of functions, ◦define data structures that those functions act

upon◦there is no relationship between the two other than

the functions act on the data

Page 15: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

What is OOP?How is OOP different to conventional

programming?◦Decompose the application into abstract data

types by identifying some useful entities/abstractions

◦An abstract type is made up of a series of behaviours and the data that those behaviours use.

Similar to database modelling, only the types have both behaviour and state (data)

Page 16: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Abstract Data Types Identifying abstract types is part of the modelling/design

process◦ The types that are useful to model may vary according to the

individual application◦ For example a payroll system might need to know about

Departments, Employees, Managers, Salaries, etc◦ An E-Commerce application may need to know about Users,

Shopping Carts, Products, etcObject-oriented languages provide a way to define

abstract data types, and then create objects from them◦ It’s a template (or ‘cookie cutter’) from which we can create new objects◦ For example, a Car class might have attributes of speed, colour, and

behaviours of accelerate, brake, etc◦ An individual Car object will have the same behaviours but its own

values assigned to the attributes (e.g. 30mph, Red, etc)

Page 17: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

"O O P rogram m ing" --Abs trac t T ypes c om bine data and behav iour

-- ----- - - -- - - - -- - - - -

- - - - -- - - - -- - - - -- - - - -

- - - - -- - - - -- - - - -- - - - -

"Conventional P rogram m ing" --F unc tions or P roc edures operating on independent data

Page 18: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

EncapsulationThe data (state) of

an object is private – it cannot be accessed directly.

The state can only be changed through its behaviour, otherwise known as its public interface or contract

This is called encapsulation

P rivate D ata

P ublic In terfac e

"T he D oughnut D iagram "S how ing that an ob jec t hasprivate s tate and publicbehaviour . S tate c an only bec hanged by invok ing s om ebehaviour

Page 19: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

EncapsulationMain benefit of encapsulation

◦ Internal state and processes can be changed independently of the public interface

◦ Limits the amount of large-scale changes required to a system

Page 20: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

What is an OO program?What does an OO program consist of?

◦ A series of objects that use each others behaviours in order to carry out some desired functionality

◦ When one object invokes some behaviour of another it sends it a message

◦ In Java terms it invokes a method of the other object◦ A method is the implementation of a given behaviour.

OO programs are intrinsically modular◦ Objects are only related by their public behaviour

(methods)◦ Therefore objects can be swapped in and out as required

(e.g. for a more efficient version)◦ This is another advantage of OO systems

Page 21: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

AggregationAggregation is the ability to create new classes

out of existing classes◦ Treating them as building blocks or components

Aggregation allows reuse of existing code◦ “Holy Grail” of software engineering

Two forms of aggregationWhole-Part relationships

◦ Car is made of Engine, Chassis, WheelsContainment relationships

◦ A Shopping Cart contains several Products◦ A List contains several Items

Page 22: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

InheritanceInheritance is the ability to define a new class in

terms of an existing class◦ The existing class is the parent, base or superclass◦ The new class is the child, derived or subclass

The child class inherits all of the attributes and behaviour of its parent class◦ It can then add new attributes or behaviour◦ Or even alter the implementation of existing behaviour

Inheritance is therefore another form of code reuse

Page 23: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

PolymorphismMeans ‘many forms’Difficult to describe, easier to show, so we’ll look at

this one in a later lessonIn brief though, polymorphism allows two different

classes to respond to the same message in different ways

E.g. both a Plane and a Car could respond to a ‘turnLeft’ message, ◦ however the means of responding to that message (turning

wheels, or banking wings) is very different for each.Allows objects to be treated as if they’re identical

Page 24: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

24

A Simple ApplicationExample//This application program prints Welcome//to Java! Import java.io.*;package chapter1;

public class Hello { public static void main(String[] args) { System.out.println(“Hello World!"); }}

The import statement tells the compiler to make available classes and methods of another package

A main method indicates where to begin executing a class (if it is designed to be run as a program)

public = can be seen from any package static = not “part of” an object

Page 25: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

25

Creating and Compiling Programs

On command line◦javac file.java(it produce file.class file)

Source Code

Create/Modify Source Code

Compile Source Code i.e. javac Welcome.java

Bytecode

Run Byteode i.e. java Welcome

Result

If compilation errors

If runtime errors or incorrect result

Page 26: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

26

Executing ApplicationsOn command line

◦java classname (Starts the JVM and runs the main method)

JavaInterpreter

on Windows

JavaInterpreter

on Sun Solaris

JavaInterpreteron Linux

Bytecode

...

Page 27: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

27

Examplejavac Hello.java

Java Hello

output:...Hello World

Page 28: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Downloading a Java JDK

You want a JDK, not just a JRE

Create a “Temp” directory on your PC or laptop

Go to http://java.sun.com

Go to the “Popular Downloads” section and select “Java SE”

Select a JDK without Netbeans (We’ll talk about this later)

Agree to the accept the use policy

Right Click and Save the Offline Windows JDK to your temp dir

Page 29: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Installing a Java JDKGo to your “Temp” dir using Windows Explorer

Make sure no other apps are running and double click the install program you just downloaded. Follow the steps.

I install in C:\Java

Watch fom multiple JREs and JDKs! In Windows the Registry runs the show now, not the JAVA_HOME env variable

Test with a Command Prompt Window and “java –version”

Add C:\Java\”Java ver”\bin to your PATH var

Be sure to add “current directory” to the CLASSPATH (if you had one)

Page 30: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Now, Lets test it

DOS - Command Prompt

Make a directory structure

Type “Edit” and Voila

PSVM

Test JAVAC and JAVA

Create Bytecode ( the *.class file) with “Javac”

Run Program with “Java”

Page 31: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

If we were lucky we got something that looks like this…

Page 32: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Help on the Webhttp://java.sun.com/javase/6/docs/api/

http://www.javaranch.com

http://java.sun.com/docs/books/tutorial/

http://www.sorcon.com/java2/

http://remus.rutgers.edu/freestuff

Got an Error?Just type it verbatim into Google and you usually can find the answer to your question or solve your problem.

Wikipedia is a good place to get background and history On anything, and Java is no exception

Page 33: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

33

References and Primitive Data TypesJava distinguishes two kinds of entities

◦Primitive types◦Objects

Primitive-type data is stored in primitive-type variables

Reference variables store the address of an object◦No notion of “object (physically) in the stack”◦No notion of “object (physically) within an object”

Page 34: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

34

Primitive Data TypesRepresent numbers, characters, boolean

valuesIntegers: byte, short, int, and longReal numbers: float and doubleCharacters: char

Page 35: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

35

Primitive Data TypesData type Range of values

byte -128 .. 127 (8 bits)

short -32,768 .. 32,767 (16 bits)

int -2,147,483,648 .. 2,147,483,647 (32 bits)

long -9,223,372,036,854,775,808 .. ... (64 bits)

float +/-10-38 to +/-10+38 and 0, about 6 digits precision

double +/-10-308 to +/-10+308 and 0, about 15 digits precision

char Unicode characters (generally 16 bits per char)

boolean True or false

Page 36: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

36

Primitive Data Types (continued)

Page 37: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

37

Operators1. subscript [ ], call ( ), member access .2. pre/post-increment ++ --, boolean

complement !, bitwise complement ~, unary + -, type cast (type), object creation new

3. * / %4. binary + - (+ also concatenates strings)5. signed shift << >>, unsigned shift >>>6. comparison < <= > >=, class test instanceof7. equality comparison == !=8. bitwise and &9. bitwise or |

Page 38: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

38

Operators11.logical (sequential) and &&12.logical (sequential) or ||13.conditional cond ? true-expr :

false-expr14.assignment =, compound assignment +=

-= *= /= <<= >>= >>>= &= |=

Page 39: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

39

Type Compatibility and ConversionWidening conversion:

◦In operations on mixed-type operands, the numeric type of the smaller range is converted to the numeric type of the larger range

◦In an assignment, a numeric type of smaller range can be assigned to a numeric type of larger range

byte to short to int to longint kind to float to double

Page 40: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

40

Declaring and Setting Variablesint square;square = n * n;

double cube = n * (double)square;◦Can generally declare local variables where

they are initialized◦All variables get a safe initial value anyway

(zero/null)

Page 41: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

41

Referencing and Creating ObjectsYou can declare reference variables

◦They reference objects of specified typesTwo reference variables can reference the

same objectThe new operator creates an instance of a

classA constructor executes when a new

object is createdExample: String greeting = ″hello″;

Page 42: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

42

Java Control StatementsA group of statements executed in order is

written◦{ stmt1; stmt2; ...; stmtN; }

The statements execute in the order 1, 2, ..., N

Control statements alter this sequential flow of execution

Page 43: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

43

Java Control Statements (continued)

Page 44: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

44

Java Control Statements (continued)

Page 45: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

45

MethodsA Java method defines a group of statements as

performing a particular operationstatic indicates a static or class methodA method that is not static is an instance

methodAll method arguments are call-by-value

◦Primitive type: value is passed to the method◦Method may modify local copy but will not affect

caller’s value◦Object reference: address of object is passed◦Change to reference variable does not affect caller◦But operations can affect the object, visible to caller

Page 46: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Appendix A: Introduction to Java

46

The Class Math

Page 47: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Appendix A: Introduction to Java

47

Escape SequencesAn escape sequence is a sequence of two

characters beginning with the character \A way to represents special

characters/symbols

Page 48: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

OO Programming Concepts

data field 1

method n

data field n

method 1

An object

...

...

State

Behavior

Data Field radius = 5

Method findArea

A Circle object

Page 49: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Class and Objects

circle1: Circle

radius = 2

new Circle()

circlen: Circle

radius = 5

new Circle()

...

UML Graphical notation for classes

UML Graphical notation for objects

Circle radius: double findArea(): double

UML Graphical notation for fields

UML Graphical notation for methods

Page 50: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Class Declarationclass Circle { double radius = 1.0;

double findArea(){ return radius * radius * 3.14159; }}

Page 51: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Declaring Object Reference VariablesClassName objectReference;

Example:Circle myCircle;

Page 52: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Creating ObjectsobjectReference = new ClassName();

Example:myCircle = new Circle();

The object reference is assigned to the object reference variable.

Page 53: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Declaring/Creating Objectsin a Single Step

ClassName objectReference = new ClassName();

Example:Circle myCircle = new Circle();

Page 54: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Differences between variables of primitive Data types and object types

1

c: Circle

radius = 1

Primitive type int i = 1 i

Object type Circle c c reference

Created using new Circle()

Page 55: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Copying Variables of Primitive Data Types and Object Types

1

c1: Circle

radius = 5

Primitive type assignmenti = j

Before:

i

2j

2

After:

i

2j

Object type assignmentc1 = c2

Before:

c1

c2

After:

c1

c2

c2: Circle

radius = 9

Page 56: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Garbage Collection As shown in the previous figure, after the

assignment statement c1 = c2, c1 points to the same object referenced by c2. The object previously referenced by c1 is no longer useful. This object is known as garbage. Garbage is automatically collected by JVM.

Page 57: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Garbage Collection, cont TIP: If you know that an object is no longer

needed, you can explicitly assign null to a reference variable for the object. The Java VM will automatically collect the space if the object is not referenced by any variable.

Page 58: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Accessing ObjectsReferencing the object’s data: objectReference.data myCircle.radius

Invoking the object’s method: objectReference.method myCircle.findArea()

Page 59: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

ConstructorsCircle(double r) { radius = r;}

Circle() { radius = 1.0; }

myCircle = new Circle(5.0);

Constructors are a special kind of methods that are invoked to construct objects.

Page 60: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Constructors, cont.A constructor with no parameters is referred to as a default constructor.

·       Constructors must have the same name as the class itself.

·       Constructors do not have a return type—not even void.

·       Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects.

Page 61: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Visibility Modifiers and Accessor MethodsBy default, the class, variable, or data can beaccessed by any class in the same package.

publicThe class, data, or method is visible to any class in any package.

private The data or methods can be accessed only by the declaring class.

The get and set methods are used to read and modify private properties.

Page 62: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Scope of VariablesThe scope of instance and class

variables is the entire class. They can be declared anywhere inside a class.

The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be used.

Page 63: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

The Keyword thisUse this to refer to the current object.Use this to invoke other constructors of

the object.

Page 64: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Array of Objects Circle[] circleArray = new Circle[10];

An array of objects is actually an array of reference variables. So invoking circleArray[1].findArea() involves two levels of referencing as shown in the next figure. circleArray references to the entire array. circleArray[1] references to a Circle object.

Page 65: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Array of Objects, cont.

reference

Circle object 0 circleArray[0]

circleArray circleArray[1]

circleArray[9]

Circle object 9

Circle object 1

Circle[] circleArray = new Circle[10];

Page 66: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Class Abstraction Class abstraction means to separate class

implementation from the use of the class. The creator of the class provides a description of the class and let the user know how the class can be used. The user of the class does not need to know how the class is implemented. The detail of implementation is encapsulated and hidden from the user.

Page 67: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Java API and Core Java classesjava.lang

Contains core Java classes, such as numeric classes, strings, and objects. This package is implicitly imported to every Java program.

java.awt Contains classes for graphics.

java.applet Contains classes for supporting applets.

Page 68: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

java.awt.image Contains classes for managing bitmap images.

java.awt.peer Platform-specific GUI implementation.

Others:java.sqljava.rmi

Java API and Core Java classes, cont.

Page 69: Prof  Darshana Mistry HOD of Computer Department Gandhinagar  Institute Of Technology

Summary

Java is interpreted and compiled language.

Java is fully object oriented and machine independent language.