Está en la página 1de 34

1.

Revision on Java Programming


Any fool can write code that a computer can understand. Good programmers write code that humans can understand. Martin Fowler

1.1 Java Basics


Java is a Programming Language
Different platforms (JVM) Class libraries APIs for GUI, data storage, processing, I/O, and networking. Everything is an object (java.lang.Object) No code outside of class definition All classes are defined in .java files
One class per one .java file

The Java interpreter starts up a new Virtual Machine The VM executes the defined class by running its main() method
2

1.1 Java Basics


A Simple Java Program

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

1.1 Java Basics


Compiling and Running

HelloWorld.java

source code

Run
C:\ Hello World

HelloWorld.class

output

bytecode is an intermediate representation of the program (class). 4

Java Language More Details


Data types (primitive and references)
Operators

Flow Control
Classes and Objects

Arrays
Readability and Style
5

1.2 Data Types


Primitive Types
Keyword byte Description (integers) Byte-length integer 8-bit two's complement Size/Format

short
int long float double char boolean

Short integer
Integer Long integer (real numbers)
Single-precision floating point

16-bit two's complement


32-bit two's complement 64-bit two's complement 32-bit IEEE 754

Double-precision floating point 64-bit IEEE 754

(other types)
A single character A boolean value (true or false) 16-bit Unicode character true or false
6

NOTE: A variable of a primitive type always holds a value of that exact type

1.3 Operators
Assignment: = += -= *= Numeric: Relational: Boolean: + - * / % ++ -== != < && || ! > <= >=

1.3 Operators
Assignment Statement
Assignment operator is =, E. g. i = 7;

Variable must be on the left


1 = i not correct. k = 1 correct. k = i correct.

Expressions
x = 3 + y;

1.4 Flow of Control


Selection (Decision) Statements
if / if else switch

Iteration (Looping) Statements


for while do-while

break Statement Continue Statement


9

1.4 Flow of Control


if else Statement

Format
if( Boolean_Statement ) statements if true else statements if false

Example
if( value >= 0 ) goCompute(value); else { System.out.println(Negative!); }
10

1.4 Flow of Control


switch Statement

Similar to sequence of nested if statements


switch(expression){ case 0: statements break; case 1: statements break; default: statements } Expression must evaluate to char, byte, short, or int.

It you leave out break, the switch will evaluate all cases.

NOTE: The case statements fall through. A break statement prevents this from happening

11

1.4 Flow of Control


Uses of Switch Testing Chars

Switch statement useful when testing for particular characters Example


char c = input a character, or equivalent;
switch(c){ case 'a': System.out.println("The character was a"); break; case 'c': System.out.println("The character was c"); break; default: System.out.println(Not a nor c."); }
12

1.4 Flow of Control


While Loop Statement
Format
while( continue_condition ) { statements }

Note that condition is only evaluated at the top The loop is executed as long as the condition is satisfied Example
i=1; while( i<10 ) { System.out.println(i); i=i+1; }
13

What would be the output?

1.4 Flow of Control


Infinite Loop

Format
while(true) { statements }

Why/where would you use this?

14

1.4 Flow of Control


Do While Loop Statement

Format
do {

statements } while( continue_condition );

Note the semicolon! When would you use this loop?

15

1.4 Flow of Control


For Loop Statement

Format
for(initial; condition; adjustment) { statements Must evaluate to a } boolean

Example: Loop a specified number of times (how many?)


int i; for(i = 0; i < 100; i=i+1)

System.out.println(Loop);
16

1.4 Flow of Control


Break and Continue Statements
Breaks the loop (aborts execution)
for(int i = 0; i < 10; i++) {

if(i = = 5) break; System.out.println(i); }

Which numbers are printed? Continue interrupts the execution of the current iteration within the loop but maintains the loop execution
for(int i = 0; i < 10; i++) {

if(i == 5) continue; System.out.println(i); }

Which numbers are printed?


17

1.5 Classes and Objects


Each Java program consists of one or more classes A Java class consists of:
Attributes (fields/members) represent the data that is unique to an instance of a class Behaviors are methods that operate on the data to perform various tasks

Classes

Java development environment provides many class implementations


public class Student { String name; double grade1, grade2; double average() { return (grade1+grade2)/2; } Atributes

Methods

NOTE: All Java statements must appear within methods. All methods are defined within classes.

18

1.5 Classes and Objects


Defining Classes
One top level we have public class per .java file
typically end up with many .java files for a single program One .java file (class) has a static public main() method

Class name must match the file name


E.g. Student.java compiler/interpreter use class names to figure out what file name is

19

1.5 Classes and Objects


Sample Class
File Name: Point.java
public class Point { public double x,y; Point(double x, double y) { this.x = x; this.y = y; } public double distanceFromOrigin() { return Math.sqrt(x*x+y*y); } public static void main (String [] args) { System.out.println (Point Class"); } }
20

y P(x, y)

1.5 Classes and Objects


Objects
Objects are the physical instantiations of classes Many objects can be instantiated from one class. Many objects of different classes can be created, used, and destroyed in the course of executing a program. An object has state, behavior, and identity.
Attributes or data members refer to the state (values) of an object Behaviors are described by methods (constructor, accessor, modifier/mutator, destructor) Identity is the property of an object that distinguishes it from all other objects.

Example: Student myStud = new Student(); Point p = new Point(3.1,2.4);


21

1.5 Classes and Objects


Objects and new

You have to declare a variable that can hold an object


Point p;

But this doesnt create the object! You have to use new to create a new object:
Point p = new Point(3.1,2.4);

Strings are different:


String name = Paul Murphy ";

22

1.5 Classes and Objects


Using Objects

Invoke a method:
objectname.methodname()

Access to a data member:


objectname.dataMember

Example
Point p = new Point(3.0,2.0); double dist = p.distanceFromOrigin(); p.x = 7.0;
23

1.6 Arrays
Arrays are supported as a kind of reference type. Declaring an array:
double marks[];

Creating an array (remember an array is an object):


marks = new double[5];

Initialisation of the array elements


marks[2] = 12.26;

Array elements:
0 1 2 3 4 1.2 6.1 0.2
-1.1

1.9

marks[2]

Refers to the element at the position 2


24

1.6 Arrays
Notes on Arrays
Arrays index starts at position 0

arrays cant shrink or grow (use Vector instead)


each element is initialised array bounds checking (no overflow!)
ArrayIndexOutOfBoundsException

Arrays have a .length (a very useful attribute) An array of strings is declared and created as follows:
String name[] = new String[10]; name[0] = rob;

An array can also be initialised in the following manner:


String[] weekEndDayName = {Saturday, Sunday}; int[] marks = {1,2,3,4,5};
25

1.6 Arrays
Example Code
int[] values = {1,2,3,4,5}; int total = 0; ... for (int i=0; i<values.length; i++) { total = total + values[i]; } System.out.println("total is " +total);

What will be the result?

26

1.7 Readability and Style


Class name starts with uppercase letter
Person, Point, Student, PostGrad, GradDip,

Use meaningful names, capitalise the first letter in every word method and variable identifiers start with lowercase letter
setName, getAge, numberOfStudents,

Use named constants instead of embedded values


public static final int MIN_TAX = 17; public static final int MIN_AGE = 16;

27

1.7 Readability and Style


Organise each class in the following order:
1. 2. 3. 4. constants variables constructors methods.

Indent statement blocks. (tab or 2-4 spaces) Use comments that add meaning to the program and explain ambiguous or confusing constructs.
28

1.7 Readability and Style


class FileIn { public static void main(String args[]) { if (args.length == 1) { try { // quick explanation MY CODE HERE

- Example

/* Block comments are good for explaining the purpose of a method (statement block) and complex code sections. */ MORE CODE HERE } catch (Exception e) { // DEAL WITH THE EXCEPTION BLOCK HERE } } else { // STATEMENTS CODE HERE } } }
29

1.7 Readability and Style


Variable Scope

Variable scope modifiers:


public access granted to anyone protected same package/subclasses private same class only

30

1.7 Readability and Style


Variable Scope

31

1.7 Readability and Style


Method Scope

Method scope modifiers:


public access granted to anyone protected same package/subclasses private same class only

32

1.7 Readability and Style


How to solve a problem?
Describe the series of actions in English first
Imagine you have to give instructions to a friend with a calculator e.g. Take the first number, then divide by two, add it to the second number etc..

Describe your solution in broad terms before going into detail Break the problem down into a sequence of simple operations
E.g. Input number, Division, Addition, Print result

33

1.7 Readability and Style


How to solve a problem?
Draw a flowchart before writing code Solve part of the problem first

Solve a simpler version of the problem first


Think in advance how many variables youll need
give them useful names

If you have to make decisions use if ...else statement


If you have to repeat the same operations many times use a loop
E.g. for, while, do-while
34

También podría gustarte