cos 240 object-oriented languages the anatomy of a java program aubg, spring 2014 svetla boytcheva

48
COS 240 COS 240 Object-Oriented Languages Object-Oriented Languages The Anatomy of a Java Program The Anatomy of a Java Program AUBG, Spring 2014 AUBG, Spring 2014 Svetla Boytcheva

Upload: clinton-page

Post on 20-Jan-2016

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

COS 240COS 240

Object-Oriented LanguagesObject-Oriented Languages

The Anatomy of a Java ProgramThe Anatomy of a Java Program

AUBG, Spring 2014AUBG, Spring 2014

Svetla Boytcheva

Page 2: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

Course Text Book:

Y. Daniel Liang,

Introduction to Java Programming, Comprehensive Version,

9th edition, Pearson, 2013

Page 3: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

Aditional Book: Thinking in Java

• Bruce Eckel, Thinking in Java (4th Edition) – http://www.planetpdf.com/developer/article.asp?ContentID=6632– http://www.codeguru.com/java/tij/

• Other useful links (comparisson between C++ and Java):– http://www.javacoffeebreak.com/articles/thinkinginjava/comparingc++andjava.html

Page 4: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

Eclipse

• Downloads:– http://www.eclipse.org/downloads/

• Tutorials:– http://www.vogella.de/articles/Eclipse/article.html– http://eclipsetutorial.sourceforge.net/totalbeginner.html

Page 5: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

Overview

From the very beginning, Java was designed as an object-oriented language

- unlike C++ which is just an object-oriented extension to C. But like C#.

Classes are the building blocks of Java programs

- again, unlike C++. But like C#.

Java is case sensitive. Like C#.

- a is different to A

Page 6: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

Versions of Java

Java 1

Java 2

Java 5.0

Java 1.1: Adds inner classes and a completely new event-handling model

Java 1.2: Includes “Swing” but no new syntax

Java 1.3: Additional methods and packages, but no new syntax

Java 1.4: More additions and the assert statement

Java 1.5: Generics, enums, new for loop, and other new syntax

Java: Original, not very good version (but it had applets)

Java 6 (=1.6): A few new features, mostly at the advanced level

Page 7: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

How Java Works

• Java's platform independence is achieved by the use of the Java Virtual Machine (JVM).

• A Java program consists of one or more files with a .java extension

• these are just text (i.e. source) files.

• When a Java program is compiled, the .java files are fed to the compiler which produces a .class file for each .java file.

• The .class file contains Java bytecode. • • Java bytecode is like machine language, but it is

intended for the Java Virtual Machine, not a specific processor.

Page 8: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva
Page 9: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

Executing a Java program

Page 10: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

• To run a Java program, the bytecode in a .class file is fed to an interpreter/compiler which converts the bytecode to machine code for a specific processor.

• Some people refer to the interpreter/compiler as "The Java Virtual Machine" (JVM).

• The interpreter/compiler is platform specific because it takes the platform-independent bytecode and produces machine language instructions for a particular processor.

• So a Java program could be run an any type of computer that has a JVM written for it.

Page 11: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

Java was initially developed by Sun Microsystems

- producers of Unix platforms and Unix OS.

Java programs may be applications or applets.

Applications are standalone programs, similar to .NET Console and Windows applications.

Applets are similar to applications, but they do not run as standalone programs.

- Instead, applets adhere to a set of conventions that lets them run within a Java-compatible browser (client-side).

- You can only run an applet from an HTML page.

Page 12: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

JVM is an Emulation

• The difficult part of creating Java byte code is that the source code is compiled for a machine that does not exist.

• This machine is called the Java Virtual Machine, and it exists only in the memory of our computer.

• Fooling the Java compiler into creating byte code for a nonexistent machine is only one-half of the ingenious process that makes the Java architecture neutral.

• The Java interpreter must also make our computer and the byte code file believe they are running on a real machine. It does this by acting as the intermediary between the Virtual Machine and our real machine.

Page 13: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

JVM emulation run on a physical machine

Page 14: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

JVM

• The Java Virtual Machine is responsible for interpreting Java byte code and translating this into actions or Operating System calls.

• For example, a request to establish a socket connection to a remote machine will involve an Operating System call.

• Different Operating Systems handle sockets in different ways - but the programmer doesn't need to worry about such details. It is the responsibility of the JVM to handle these translations so that the Operating System and the CPU architecture on which the Java software is running is completely irrelevant to the developer.

Page 15: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

JVM handles translations

Page 16: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

Preview to Java Language

• Basic syntax the same as C++ (which was then copied by C#!).

• Pointers exist but in a simplified and hidden form. – Object references

• Garbage Collection is used– No need for destructors (but may have!).– Memory leaks very unlikely .– Not as many memory management issues (Memory is

still managed, but by the run time system instead of the programmer.).

• Array index out of bounds causes a runtime error– Java uses the term Exceptions for runtime errors

Page 17: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

Basic syntax for class declaration

In Java, a class comprises a class header and class body.

public class class_name{

class body;}

Note: No semicolon (;) to terminate class block.

But statements must be terminated with a ;

Class body comprises class members – constructor, data fields and methods.

Page 18: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

Each feature (constructor, data fields and methods) is individually tagged as public or private. (There are other qualifiers …)

E.g.

public class class_name{

private data_type name;

public method_name(parameters){

...}

public another_method(parameters){

...}

}

Page 19: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

Reference Types

• Non-primitive types in Java are called reference types.

• Variable does not really hold an object, it holds a

reference to (i.e. address of) the object.

• Java hides this indirection from you. Like C#.

In Java, declaring a variable to hold an object does not create the object (instance) itself. Need to invoke constructor (via new) to create and initialize instance.

The variable only holds a reference to the object.

class_name variable_name;

Page 20: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

To create an instance of a class, use the new operator which invokes the class constructor.

new class_name(parameters)

Variables of type class_name can be created in this way:

class_name instance_name = new class_name(params);

An object of type String can be created by simply enclosing the characters in double quotes

String s = “Here is a string”;

Page 21: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

The dot operator . is used in conjunction with the object to access the members of a class (like C++ and C#).

Every class defined in Java must extend some other object

– Default: implicit extension of the Object class

Page 22: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva
Page 23: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva
Page 24: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva
Page 25: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva
Page 26: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva
Page 27: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva
Page 28: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva
Page 29: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

Syntax for simple Java program

public class class_name{

public static void main(String[] args){

implementation of method}

}

The first method that will be invoked when execution commences must be called main().

Note the case of main() and String !

- C# has public static void Main(string[] args)

Page 30: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

// Javapublic class Hello { public static void main(String[] args) { System.out.println("Hello world in Java"); }}

// C#

public class Hello {

public static void Main(string[] args) {

System.Console.WriteLine("Hello world in C#");

System.Console.ReadLine();

}

}

Page 31: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva
Page 32: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

The general syntax for a method

modifers return_type method_name(parameters){

data declarationssequence of statements

}

E.g.

public static void main(String[] args)

Page 33: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

Import statement

A Java program is never entirely self-contained butinstead must execute in the “world” provided by theJava runtime system.

Use of the import statement:

import java.lang.*;

This statement makes the methods in the library packagejava.lang available to the class following it.

java.lang is just one package in the Java library or API.

Page 34: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

Actually, importing java.lang is not required since it is automatically available to all Java programs.

The package java.lang is important because it contains the class System which itself contains I/O methods.

E.g. Methods System.out.print(...)and System.out.println(...)and System.in.read()

A Java package is similar to a C# namespace.

Page 35: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

Standard Output

• To print to standard output use

System.out.print( expression ); // no newline

System.out.println( expression ); // newline

System.out.println( ); // just a newline

Common behaviour is to build up expression to be printed out

System.out.println( "x is: " + x + " y is: " + y );

Page 36: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

// Package Declarationimport java.lang.*; // not required

// Program start class public class HelloWorld { // Main begins program execution public static void main(string[] args) { // This is a single line comment

/* This is a multiple line comment */

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

Example

Page 37: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

public class HelloWorldApp {

public static void main(String[] args) {

// Display "Hello World!" System.out.println("Hello World!");

} }

Example

Page 38: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

import java.io.*;public class Testclass{ public static void main( String args[] ) { int count = 0; while ( count < 10 ) { System.out.println("counter is " + count ); count++; } }}

Example

Page 39: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

public class HelloWorld {

public static void main(String[] args) {

String name = "Java";

// See if an argument was passed from the command line

if (args.length == 1)

name = args[0];

System.out.println("Hello, " + name + "!");

}

}

Example

Page 40: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

import java.util.*;

public class test11 {

public static void main(String[] args) {

System.out.println("Hello, it’s: ");

System.out.println(new Date());

}

}

Page 41: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

Language Basics

• Data types– 8 primitive types:

• boolean, byte, short, int, long, float, double, char

– Class types, either provided by Java, or made by programmers (Reference types)• String, Object, Frame, Person, Animal, …

– Array types (also reference types)

• Variables– dataType identifier [ = Expression]:– Example variable declarations and initializations:

int x; x=5;boolean b = true;Frame win = new Frame();String x = “How are you?”;

int[] intArray;intArray = new int[2];intArray[0] = 12;intArray[1] = 6;Person pArray = new Person[10];

Page 42: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

Constants via final

Assigned value cannot be changed

– Similar to the const keyword in C

Variables declared with final

– must be initialized in the declaration

– can be initialized in a constructor, but must be assigned a value in every constructor of the class

Page 43: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

Flow of control if, if-else, if-else if

switch

for, while, do-while

break

continue

Page 44: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

If-else

/**

* return the difference of x and y

*/

public static int abs(int x, int y){

if (x < y)

return y - x;

else if(x > y)

return x - y;

else

return 0;

}

Page 45: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

Switch-case

switch ( N ) { // (Assume N is an integer variable.) case 1: System.out.println("The number is 1."); break; case 2: case 4: case 8: System.out.println("The number is 2, 4, or 8."); System.out.println("(That's a power of 2!)"); break; case 3: case 6: case 9: System.out.println("The number is 3, 6, or 9."); System.out.println("(That's a multiple of 3!)"); break; case 5: System.out.println("The number is 5."); break; default: System.out.println("The number is 7 or is outside the range 1 to 9.");}

Page 46: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

For-loop

For (int i=1, j=10; i < j; i++, j-=2)

System.out.println("i="+i+" j="+j);

for (int i = 0; i < 4; i++){ for( char letter = 'A'; letter <= 'A' + i; letter++) System.out.print(letter); System.out.println();}

i=1 j=10i=2 j=8i=3 j=6

AABABCABCD

Page 47: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

The break statement

• Inside any loop, the break statement will immediately get you out of the loop– If you are in nested loops, break gets you out of the

innermost loop

• It doesn’t make any sense to break out of a loop unconditionally - you should do it only as the result of an if test

Example: for (int i = 1; i <= 12; i++) { if (badEgg(i)) break;}

• break is not the normal way to leave a loop– Use it when necessary, but don’t overuse it

Page 48: COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

The continue statement

• Inside any loop, the continue statement will start the next pass through the loop

– In a while or do-while loop, the continue statement will bring you to the test

– In a for loop, the continue statement will bring you to the increment, then to the test