Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 A Quick Tour of Java In this lesson you...

33
Copyright @ 2000 Jordan Anastasiade. All right s reserved. 1 A Quick Tour of Java In this lesson you will be learning about: The Java Platform. Basics elements of the Java Language: Variables Named Constants Flow of Control Classes and Objects. How to compile and execute a Java program.

Transcript of Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 A Quick Tour of Java In this lesson you...

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1

A Quick Tour of Java

In this lesson you will be learning about:

The Java Platform.

Basics elements of the Java Language: Variables Named Constants Flow of Control

Classes and Objects.

How to compile and execute a Java program.

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 2

Getting Started

Java programs are built from classes.A class is a template to build objects and contains members of the following type: Fields – Data belonging either to class or object of the class. Methods – Collections of statements that operate on fields. Classes – Nested or inner classes defined inside a class.

Example: First.java file

class First { public static void main(String[] args) { System.out.println(“The first program in Java –

PRO404”); }}

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 3

Java Platform – JDK 1.2

Java Platform has 3 components: 1. Java Programming Language. 2. Java Packages. 3. Java Virtual Machine.

Java Programming Language – called simply Java. General-purpose, ease of programming, safety features.

Java Packages. Grouping of related interfaces and classes. Ex: java.lang.

Java Virtual Machine. The Java virtual machine is an abstract computing machine.

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 4

How to Use Java Platform

Learn Java Programming Language Concepts, Vocabulary, Syntax, Semantics and Patterns. Write program and safe source code in files according with the Java

Programming Language rules.

Learn the structure of packages that come with JDK. Use classes already defined in the JDK packages according with

your program design. Do not invent the wheel!

Compile and run your program using tools from JDK. Compile using java compiler: javac MyProgramName.java Run your program using JVM: java MyProgrmName

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 5

From Birth to Execution

1. Coding: Java code is produced by the programmer.

COMPILER: javac2. Compiling: Build the Java program into byte-code, which is saved as a ".class" file.

JAVA VIRTUAL MACHINE: java 3. Loading: The class file is loaded by the Java Virtual Machine with its attached digital signature.

4. Bytecode Verification: The JVM verifies the class file digital signature. The JVM is simply an interpreter.

6. Internal Integrity: Verification checks are made to insure that the loaded Java program is well formed. Data types are verified along with other syntax structure.

7. Execution: Program execution begins from the main entry point.

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 6

Variables

Java has build-in primitives to support boolean, character, integer and floating-point values.----------------------------------------------------------------------------------------- boolean either true or false boolean b = true;------------------------------------------------------------------------------------------ char 16-bit Unicode 1.1 character char ch = ‘J’;------------------------------------------------------------------------------------------ byte 8-bit integer (signed) byte bt = 127; short 16-bit integer (signed) short sh = 32767; int 32-bit integer (signed) int i = 2147483647; long 64-bit integer (signed) long l =

9223372036854775807L;------------------------------------------------------------------------------------------- float 32-bit floating-point (IEEE 754-1985) float f = 1.0f; double 64-bit floating-point (IEEE 754-1985) double d = 1.e-1;-------------------------------------------------------------------------------------------

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 7

Comments, Named Constants

Comments in Code – enable to write descriptive text.

/* Comment type 1 – This text is ignored by the compiler */ // Comment type 2 – The text up to the end of line is ignored

/** Documentation comment is extracted by javadoc tool */

Named Constants – name used to describe constants.

public static final int MAX_INDEX = 1000;

class MathConstant { static final double E = 2.71; //the base of the natural

logarithms static final double PI = 3.14; }

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 8

Flow of Control

Flow of control is the term used for describing which statements are executed in a program.

Flow statements are: if – else for switch do – while while block of code – statements group within { and }.

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 9

Fibonaci sequenceThe Fibonacci sequence is an infinite sequence that starts with terms 1 and 1 and each successive term is the sum of the previous two terms.

class Fibonacci { /** Print out the Fibonacii numbers */ static final int MAX_INDEX = 10;

public static void main(String[] args) { int lo = 1;

int hi = 1; System.out.println(“1: “ + lo);

for (int i = 2; i < MAX_INDEX; i++) { System.out.println(“i: “ + hi); hi = lo + hi; //new hi is the sum of previous two

terms. lo = hi – lo; //new lo is the old hi i. e. sum – old hi } }}

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 10

Classes and Objects

Each class has three kinds of members: Fields are data variables of a class that store results of computations

performed by class’s methods. Methods contain the executable code, built from statements. Classes and interfaces can in the same time be members of a class.

Every object in Java has a state and a behavior. class Point { private double x_ = 0; //the state of object is defined by values of its data

private double y_ = 0;

/* the behaviors of an object is defined by its methods */

public void movePoint(double x, double y) { x_ = x; y_ = y;

}

}

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 11

Creating Objects

Objects are created using an expression containing

the new keyword.

Point lowerLeft = new Point();All objects are allocated within an area of system memory known as Heap and are accessed only via an object reference.Each Point object is unique and has its own copy of x and y fields.

x = 0 y = 0Point object

lowerLeft reference

Memory Heap

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 12

Identifiers

The name you choose for anything in java is called a java identifier.

Identifiers must start with a letter, an underscore ( _ ) or a dollar sign ( $ ) followed by letters or digits.

There is no limit for the length of identifiers and they are composed from the Unicode charter set.

Ex: toStart _color $accountÉvalué übung

Java language keywords cannot be used as identifiers.

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 13

Java Keywordsabstract boolean break

byte case catch

char class const

continue default do

double else extends

final finally float

for goto if

implements import instanceof

int interface long

native new package

private protected public

return short static

super switch synchronized

this throw throws

transient try void

volatile while

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 14

Literals

Each type in Java has literals, which are the way that constant values of that type are written. Integer constants are string of octal, decimal, hexadecimal digits.Ex: decimal 58L, octal 027, hexadecimal 0x8AF

Floating-point numbers are decimal numbers optional followed by an exponent.

Ex: double 18. .234E3 1.8e-1; float 1.234f 0.2e-5F

Characters literals appear between single quotes. Any valid Unicode character can appear between the quotes. Certain special characters are represented as escape sequence.

Ex: ‘J’, ‘A’, ‘V’, ‘A’ ‘\n’ newline ‘\u000A’ ‘\t ‘tab ‘\u0009’

\ddd a char by octal value d 0-7 String literals appear between double quote. Ex: “JAVA”

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 15

Numeric operators in Java

Prec Operator Description Example1 ++ Increment by 1(or 1.0)

k++

1 -- Decrement by 1(or 1.0) k--1 + Unary plus +value1 - Unary minus -value2 * Multiplication x * y2 / Division x / y2 % Modulo x % y3 + Addition x + y3 - Subtraction x - y5 < Less than x < y5 > Greater than x > y5 <= Less than/equal x <= y5 >= Greater than/equal x >= y6 == Equals (identical values) x == y6 != Is not equal to x != y13 op= op assignment(+ =, - =, *=, etc) x += y

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 16

Bitwise and logic operators

Prec Operator Type Description Example

1 ~ Integral Unary bitwise complement ~x1 ! Logical Unary logical complement !b4 << Integral Left shift x << 24 >> Integral Right shift (keep sign) x >> 54 >>> Integral Right shift (zero fill) x >>> 35 instanceof Obj type Tests class membership o instanceof

X6 == Object Equals (same object) x == y6 != Object Unequal (different object) x != y7 & Integral Bitwise AND x & y7 & Logical Logical AND b1 & b28 ^ Integral Bitwise XOR x ^ y8 ^ Logical Logical XOR b1 ^ b29 | Integral Bitwise OR x | y9 | Logical Logical OR b1 | b2

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 17

Bitwise and logic operators (continued)

Prec Operator Type Description Examp.10 && Logical Logical AND (conditional) b && c11 || Logical Logical OR (conditional) b1 ||

b212 ?: Logical Conditional (ternary) b ? x :

y13 = Variable,any Assignment x = 113 <<= Binary Left shift with assignment x <<=

213 >>= Binary Right shift with assignment x =>>

313 >>>= Binary Right shift, zero fill, assign x =>>

413 &= Binary Bitwise AND with assign x &= y13 &= Logical Logical AND with assign b1

&=b213 |= Binary Bitwise OR with assignment x |= y13 |= Logical Logical OR with assignment b1 |

=b213 ^= Binary Bitwise XOR with assignment x ^= y13 ^= Logical Logical XOR with

assignmentb1 ^=b2

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 18

Bitwise logic rules

AND 0 1

0 0 0

1 0 1

OR 0 1

0 0 1

1 1 1

XOR 0 1

0 0 1

1 1 0

0 & 0 = 0 0 & 1 = 01 & 0 = 0 1 & 1 = 1

0 | 0 = 0 0 | 1 = 11 | 0 = 1 1 | 1 = 1

0 ^ 0 = 0 0 ^ 1 = 11 ^ 0 = 1 1 ^ 1 = 0

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 19

Bitwise operations on short primitives (16 bit integers)

Binary Operation Decimal Hex

0000 0000 0101 0100 op1 84 0x0054

0000 0001 0100 0111 op2 327 0x0147

0000 0000 0100 0100 op1 & op2 68 0x0044

0000 0001 0101 0111 op1 | op2 343 0x0157

0000 0001 0001 0011 op1 ^ op2 275 0x0113

1111 1110 1011 1000 ~op2 -328 0xFEB8

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 20

Results of some bit-shifting

0000 0000 0000 0000 0000 0000 0110 0011 starting a = 99

0 0 0 0 0 0 6 3 a = 0x00000063

0000 0000 0000 0000 0000 0011 0001 1000 after a << 3 (792)

0 0 0 0 0 3 1 8 a = 0x00000318

0000 0000 0000 0000 0000 0000 0001 1000 after a >> 2 (24)

0 0 0 0 0 0 1 8 a = 0x00000018

1111 1111 1111 1111 1111 1111 1001 1101 stating b = -99

F F F F F F 9 D b = 0xFFFFFF9D

1111 1111 1111 1111 1111 1111 1111 1001 after b >> 4 = -7

F F F F F F F 9 b = 0xFFFFFFF9

0000 0000 0000 1111 1111 1111 1111 1111 after b >>> 12 = 1048575

0 0 0 F F F F F b = 0x000FFFFF

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 21

Type Conversions

Java is a strong typed language.

Implicit conversion for primitive value: any numeric value can be assigned to any numeric value whose type supports a larger range of values.

byte short int long float double

Explicit conversion – casting. boolean type doesn’t allow any casting at all. A char can be cast to any integer type and vice versa

excepting to a short type. When chart is cast to int type upper bits are filled with zeros.

Attention: Interger types are converted by chopping off the upper bits. If the larger integer has a value outside the range off the smaller type, dropping the

upper bits changes the value, including possibly changing sign.

Ex: short sh = -129; byte b = (byte)sh; b will have the value 127

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 22

if, if-else, if else –if else

1. if (boolean-expression) {

statements; }

2. if (boolean-expression) { statements;

} else {statements;

}

3. if (boolean-expression) { statements;

} else if (boolean-expresion ) {statements;

} else {statements;

}

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 23

for Statement

A for statement should have the following form:

for (initialization; condition; update) {

statements;}

Ex:for (k = 0, flag; k < 10 && flag; k++ ) {

. . .}

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 24

while, do - while Statements

while, do-while and for control looping are classified as iteration statements.

while (condition) {statements;

}

do {statements;

} while (condition);

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 25

break - Labeled break

A break “drops out of the bottom” of the loop. The break statement with no label attempts to transfer control to the innermost enclosing switch, for, while or do-while of immediately enclosing statement.A labeled break drops out of the bottom of the end of the loop denoted by the label. Ex:

out: for (int i = 0; i < 10; i++ ) {for (int k = 0; k < 10; k++) {

if (i == k) break out;

}}

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 26

continue – Labeled continue

A plain continue goes to the top of the innermost loop and continues. A labeled continue goes to the label and re-enters the loop right after that label.

Ex: Calculates the factorials of odd number.outerLoop: for (int i = 0; i < limit; i++ ) {

for (int k = 2; k < i; k++) {if (i % 2) continue outerLoop;factory *= i;

}}

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 27

switch

The switch is classified as a selection statement.switch (integral-selector) {

case integral-value1: statements;

break; default:

statements; } Integral-selector is an expression that produces an integral value.

The switch compares the result of integral-selector to each integral-value. If it finds a match, the corresponding statement (simple or compound) executes. If no match occurs, the default statement executes.

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 28

Array

An array is simply a sequence of either objects or primitives, all the same type and accessed together under one identifier name.

Arrays are implicit extensions of Object.

Arrays are defined and used with square-brackets indexing operator [ ].

int [ ] integerArray = new int[3];A Java array is guaranteed to be initialized and cannot be

accessed outside of its range.

for (int k = 0; k < integerArray.length; k++)integerArray[k] = k;

Creating an array of objects, one are really creating an array of references, and each of those references is automatically initialized to null.

  CelestialBody[ ] celBoliesArray = new CelestialBody[5];

Regardless of what type of array you’re working with, the array identifier is actually a reference to a true object that’s created on the heap.

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 29

Strings

Java strings are standard objects with built-in language support.

The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of String class.

Strings are constant; their values cannot be changed after they are created. Stringbuffer class supports mutable strings. Because String objects are immutable they can be shared.

For example:

  String str = "abc";

is equivalent to:

char data[] = {'a', 'b', 'c'}; String str = new String(data);

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 30

String Examples

Here are some more examples of how strings can be used:   System.out.println("abc"); String cde = "cde"; System.out.println("abc" + cde); String c = "abc".substring(2,3); String d = cde.substring(1, 2);The basic two methods:int length(); Returns the length of this string.char charAt(int index); Returns the character at the specified index. The Java language provides special support for the string concatentation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuffer class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java.

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 31

Strings’ Methods

Constructor Summary:

String();String(byte[] bytes);String(byte[] bytes, String enc);String(char[] value);String(char[] value, int offset, int count);String(String value);String(StringBuffer buffer);

 char charAt(int index);int compareTo(String anotherString);int compareToIgnoreCase(String str);

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 32

Strings’ Methods (cont)

static String copyValueOf(char[] data, int offset, int count);

boolean equals(Object anObject);boolean equalsIgnoreCase(String anotherString);byte[] getBytes(String enc);int hashCode();int indexOf(int ch);int lastIndexOf(int ch);int length();String replace(char oldChar, char newChar);boolean startsWith(String prefix);String substring(int beginIndex, int endIndex);char[] toCharArray();String toLowerCase();String toString();String toUpperCase();String trim();

static String alueOf(Object obj);

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 33

Conclusions

After completion of this lesson you should know:How to write a simple Java Program.

How to work with primitives: Integers and Floats.

To use Java Tools: compiler, interpreter, debugger.