java technologies. java basics - klevas.mif.vu.ltvaldo/jate2014/javatech.l01.pdf · • basic...

68
Preparation of the material was supported by the project „Increasing Internationality in Study Programs of the Department of Computer Science II“, project number VP1–2.2–ŠMM-07-K-02-070, funded by The European Social Fund Agency and the Government of Lithuania. Valdas Rapševičius Vilnius University Faculty of Mathematics and Informatics 2014.03.05 Java Technologies Lecture I 2014.03.05 Valdas Rapševičius. Java Technologies 1

Upload: others

Post on 22-May-2020

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Preparation of the material was supported by the project „Increasing Internationality in Study Programs of the Department of Computer Science II“, project number VP1–2.2–ŠMM-07-K-02-070, funded by The European Social Fund Agency and the Government of Lithuania.

Valdas Rapševičius Vilnius University

Faculty of Mathematics and Informatics

2014.03.05

Java Technologies Lecture I

2014.03.05 Valdas Rapševičius. Java Technologies 1

Page 2: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Session Objectives

• Remind you the principles of Object-Oriented Programming and how it is being handled in Java programming language – Variables – Operators – Flow Control – Classes – Interfaces – Inheritance

• Basic understanding of Java type system including – Numbers – Character – String – Enum

• Get familiar with more recent Java techniques – Generics – Annotations

• Overview of the essential – Packages – Naming Convention

2014.03.05 Valdas Rapševičius. Java Technologies 2

Page 3: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

OOP: Objects

• Objects are key to understanding object-oriented technology • Real-world objects share two characteristics: they all have state and

behaviour • An object stores its state in fields (variables in some programming

languages) and exposes its behaviour through methods (functions in some programming languages)

• Bundling code into individual software objects provides a number of benefits, including: – Modularity: The source code for an object can be written and maintained

independently of the source code for other objects. Once created, an object can be easily passed around inside the system.

– Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world.

– Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.

– Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.

2014.03.05 Valdas Rapševičius. Java Technologies 3

Page 4: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

OOP : Classes

• A class is the blueprint from which individual objects are created class Car {

int speed = 0; int gear = 1; void changeGear(int gear) { this.gear = gear; } void speedUp(int inc) { this.speed = this.speed + inc; } void applyBrakes(int dec) { this.speed = this.speed - dec; } void printStates() { System.out.println("speed:" + speed + " gear:" + gear);

} }

2014.03.05 Valdas Rapševičius. Java Technologies 4

Page 5: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

OOP: Classes

• Here's a CarDemo class that creates two separate Car objects and invokes their methods:

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

Car car1 = new Car(); Car car2 = new Car(); car1.speedUp(10); car1.changeGear(2); car1.printStates(); car2.speedUp(20); car2.changeGear(3); car2.printStates();

} }

• The output of this test prints speed and gear for the two cars:

speed:10 gear:2 speed:20 gear:3

2014.03.05 Valdas Rapševičius. Java Technologies 5

Page 6: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

OOP: Inheritance

• Object-oriented programming allows classes to inherit commonly used state and behavior from other classes.

• In this example, Car now becomes the superclass of OffroadCar, SportsCar, and ElectricCar.

• In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:

class SportsCar extends Car { // new fields and methods // defining a sports car }

Car

OffroadCar SportsCar ElectricCar

2014.03.05 Valdas Rapševičius. Java Technologies 6

Page 7: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

OOP: Interfaces

• Methods form the object's interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off.

interface Car { void changeGear(int newValue); void speedUp(int increment); void applyBrakes(int decrement); } class OffroadCar implements Car { // remainder of this class // implemented as before }

2014.03.05 Valdas Rapševičius. Java Technologies 7

Page 8: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

OOP: Packages

• A package is a namespace that organizes a set of related classes and interfaces.

• Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another. Because software written in the Java programming language can be composed of hundreds or thousands of individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages.

• The Java Platform API Specification contains the complete listing for all packages, interfaces, classes, fields, and methods supplied by the Java SE platform. Load the page in your browser and bookmark it. As a programmer, it will become your single most important piece of reference documentation:

• http://docs.oracle.com/javase/7/docs/api/index.html

2014.03.05 Valdas Rapševičius. Java Technologies 8

Page 9: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Variables

• Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one car is independent from the currentSpeed of another.

• Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of car could be marked as static since conceptually the same number of gears will apply to all instances. The code static int numGears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change.

• Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.

• Parameters You've already seen examples of parameters, both in the Car class and in the main method of the "Hello World!" application. Recall that the signature for the main method is public static void main(String[] args). Here, the args variable is the parameter to this method. The important thing to remember is that parameters are always classified as "variables" not "fields". This applies to other parameter-accepting constructs as well (such as constructors and exception handlers) that you'll learn about later in the tutorial.

2014.03.05 Valdas Rapševičius. Java Technologies 9

Presenter
Presentation Notes
class String { private final java.lang.String s; public String(java.lang.String s) { this.s = s; } public java.lang.String toString() { return s; } } public class StrungOut { public static void main(String[] args) { String s = new String("Hello world"); System.out.println(s); } }
Page 10: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Primitive Types • byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a

maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

• short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.

• int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else. This data type will most likely be large enough for the numbers your program will use, but if you need a wider range of values, use long instead.

• long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.

• float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.

• double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

• boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.

• char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

2014.03.05 Valdas Rapševičius. Java Technologies 10

Page 11: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Primitive Types Summary

Primitive Type Size Minimum Value Maximum Value Default Wrapper

Type char 16-bit Unicode 0 Unicode 216-1 '\u0000' Character byte 8-bit -128 +127 0 Byte

short 16-bit -215 (-32,768)

+215-1 (32,767) 0 Short

int 32-bit -231 (-2,147,483,648)

+231-1 (2,147,483,647) 0 Integer

long 64-bit -263 (-9,223,372,036,854,775,808)

+263-1 (9,223,372,036,854,775,807) 0L Long

float 32-bit 32-bit IEEE 754 floating-point numbers 0.0f Float double 64-bit 64-bit IEEE 754 floating-point numbers 0.0d Double boolean 1-bit true or false false Boolean void ----- ----- ----- ----- Void

2014.03.05 Valdas Rapševičius. Java Technologies 11

Presenter
Presentation Notes
Page 12: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Literal Variables boolean result = true; char capitalC = 'C'; byte b = 100; short s = 10000; int i = 100000; int decVal = 26; // The number 26, in decimal int hexVal = 0x1a; // The number 26, in hexadecimal int binVal = 0b11010; // The number 26, in binary double d1 = 123.4; double d2 = 1.234e2; // same value as d1, but in scientific notation float f1 = 123.4f;

Java SE7

long creditCardNumber = 1234_5678_9012_3456L; long socialSecurityNumber = 999_99_9999L; float pi = 3.14_15F; long hexBytes = 0xFF_EC_DE_5E; long hexWords = 0xCAFE_BABE; long maxLong = 0x7fff_ffff_ffff_ffffL; byte nybbles = 0b0010_0101; long bytes = 0b11010010_01101001_10010100_10010010;

2014.03.05 Valdas Rapševičius. Java Technologies 12

Presenter
Presentation Notes
println 12345 + 5432l ; always use capital L
Page 13: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Primitive Conversions

• Identity conversions – A conversion from a type to that same type is permitted

for any type. • Widening primitive conversions

– Does not lose information about the overall magnitude of a numeric value.

– Sign extension not always performed • Narrowing primitive conversions

– May lose information about the overall magnitude of a numeric value and may also lose precision and range.

• Widening and Narrowing Primitive Conversion – byte to char (byte int char)

2014.03.05 Valdas Rapševičius. Java Technologies 13

Presenter
Presentation Notes
println String.format("%032d", new BigInteger(Integer.toBinaryString(i))); println " " + String.format("%032d", new BigInteger(Integer.toBinaryString(b))).substring(Integer.SIZE - Byte.SIZE); // Problem int i = (int) (char) (byte) -1; println Integer.toBinaryString(i) // Fix int i = (int) (short) (char) (byte) -1;
Page 14: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Problems with numbers

• All signed • Float and Double

– Approximate precision (IEEE 754) • At Limits

– Silent Overflows – Not symmetric values

• If not sure use – BigInteger

• Immutable arbitrary-precision integers. Unscaled.

– BigDecimal • Immutable, arbitrary-precision signed decimal numbers.

Unscaled integer value and a 32-bit integer scale.

2014.03.05 Valdas Rapševičius. Java Technologies 14

Presenter
Presentation Notes
Negative number representation: Integer.toBinaryString(x); MSB (most significant bit/ left most bit) of negative numbers is always 1. println 2.0d – 1.1d problem (1.1d can not be represented exactly). Read http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html Avoid float and double where exact results are required Use BigDecimal(String) For monetary operations use int or long Overflow long MILLIS_PER_DAY = 24 * 60 * 60 * 1000; long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000; println MICROS_PER_DAY / MILLIS_PER_DAY Integer.MAX_VALUE + 1
Page 15: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Arrays

• An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed

class ArrayDemo { public static void main(String[] args) { // declares an array of integers int[] anArray; // allocates memory for 10 integers anArray = new int[10]; // initialize first element anArray[0] = 100; anArray[1] = 200; // etc. anArray[2] = 300; }

2014.03.05 Valdas Rapševičius. Java Technologies 15

Page 16: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Operators 1/2

• Simple Assignment Operator

= Simple assignment operator

• Arithmetic Operators

+ Additive operator (also used for String concatenation) - Subtraction operator * Multiplication operator / Division operator % Remainder operator

• Unary Operators

+ Unary plus operator; indicates positive value (numbers are positive without this) - Unary minus operator; negates an expression ++ Increment operator; increments a value by 1 -- Decrement operator; decrements a value by 1 ! Logical complement operator; inverts the value of a boolean

2014.03.05 Valdas Rapševičius. Java Technologies 16

Presenter
Presentation Notes
isOdd(int x): (x % 2 == 1); problem with negative numbers; should be x % 2 != 0; or better (x & 1) != 0; j = j++;
Page 17: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Operators 2/2

• Equality and Relational Operators

== Equal to != Not equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to • Conditional Operators

&& Conditional-AND || Conditional-OR ?: Ternary (shorthand for if- then-else statement)

• Type Comparison Operator

instanceof Compares an object to a specified type

• Bitwise and Bit Shift Operators

~ Unary bitwise complement << Signed left shift >> Signed right shift >>> Unsigned right shift & Bitwise AND ^ Bitwise exclusive OR | Bitwise inclusive OR

2014.03.05 Valdas Rapševičius. Java Technologies 17

Presenter
Presentation Notes
y = (x ^= (y ^= x)) ^ y // In pure Java only char x = 'X'; int i = 0; System.out.print(true ? x : 0); System.out.print(false ? i : x); println(-1 >> 1) println(-1 >>> 1)
Page 18: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Compound Assignment Operators

x += y; x -= y; x *= y; x /= y; x %= y; x <<= y; x >>= y; x >>>= y; x &= y; x ^= y; x |= y;

• Compound assignment expressions automatically cast the result of the computation to the type of the variable on the left

• Do not use compound operators for byte, short and char!

• For Objects left side must be String! Concatenation performed

• All above is fixed in Java 7 T i = (T)(i + j)

2014.03.05 Valdas Rapševičius. Java Technologies 18

Presenter
Presentation Notes
short x = 1; int y = 1; x += y; // OK x = x + y; // Not compile Object x = "labas"; String y = "rytas"; x += y; // OK in J7 not work in J6- x = x + y; // OK
Page 19: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Flow Control

• if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true.

• if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false.

• switch statement allows for any number of possible execution paths.

• while and do-while statements continually execute a block of statements while a particular condition is true. The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once.

• for statement provides a compact way to iterate over a range of values. It has two forms, one of which was designed for looping through collections and arrays.

2014.03.05 Valdas Rapševičius. Java Technologies 19

Page 20: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Classes: Declaration

class MyClass { // field, constructor, and // method declarations

} • This is a class declaration. The class body (the area between the braces)

contains all the code that provides for the life cycle of the objects created from the class: constructors for initializing new objects, declarations for the fields that provide the state of the class and its objects, and methods to implement the behaviour of the class and its objects.

• You can provide more information about the class, such as the name of its superclass, whether it implements any interfaces, and so on, at the start of the class declaration. For example,

class MyClass extends MySuperClass implements YourInterface {

// field, constructor, and // method declarations

}

2014.03.05 Valdas Rapševičius. Java Technologies 20

Page 21: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Classes: Fields and Methods

public class Car {

// Fields private int gear; private int speed; // Constructor public Car(int startSpeed, int startGear) {

gear = startGear; speed = startSpeed;

} // Method public int getGear() { return gear; } public void setGear(int gear) { gear= gear; }

}

2014.03.05 Valdas Rapševičius. Java Technologies 21

Page 22: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Classes: Methods

• Naming run

runFast

getBackground

getFinalData

compareTo

setX

isEmpty

• Overloading

public class DataArtist {

public void draw(String s) {...}

public void draw(int i) {...}

public void draw(double f) {...}

public void draw(int i, double f) {...}

}

2014.03.05 Valdas Rapševičius. Java Technologies 22

Presenter
Presentation Notes
public class Confusing { private Confusing(Object o) { System.out.println("Object"); } private Confusing(double[] dArray) { System.out.println("double array"); } public static void main(String[] args) { new Confusing(null); } }
Page 23: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Classes: Objects

Point originOne = new Point(23, 94); Rectangle rectOne = new Rectangle(originOne, 100, 200); Rectangle rectTwo = new Rectangle(50, 100);

• Variable declaration

Point originOne; • Instantiating a Class

new Point(23, 94); • Initializing an Object

Point(23, 94);

2014.03.05 Valdas Rapševičius. Java Technologies 23

Presenter
Presentation Notes
public class Type1 { public static void main(String[] args) { String s = null; System.out.println(s instanceof String); } } public class Type2 { public static void main(String[] args) { System.out.println(new Type2() instanceof String); } }
Page 24: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Classes: Using Objects, GC

int height = new Rectangle().height; objectReference.methodName(argumentList);

• Garbage Collector

– The Java platform allows you to create as many objects as you want (limited, of

course, by what your system can handle), and you don't have to worry about destroying them.

– The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection.

– An object is eligible for garbage collection when there are no more references to that object. References that are held in a variable are usually dropped when the variable goes out of scope. Or, you can explicitly drop an object reference by setting the variable to the special value null.

– The Java runtime environment has a garbage collector that periodically frees the memory used by objects that are no longer referenced. The garbage collector does its job automatically when it determines that the time is right.

2014.03.05 Valdas Rapševičius. Java Technologies 24

Page 25: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Classes: this Variable

public class Point {

public int x = 0; public int y = 0; //constructor public Point(int x, int y) {

this.x = x; this.y = y;

}

}

public class Rectangle {

private int x, y; private int width, height;

public Rectangle() { this(0, 0, 0, 0); } public Rectangle(int width, int height) { this(0, 0, width, height); } public Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; }

}

2014.03.05 Valdas Rapševičius. Java Technologies 25

Presenter
Presentation Notes
public class Thing { public Thing(int i) { } } public class MyThing extends Thing { private final int arg; /* * This constructor is illegal. Rewrite it so that it has the same * effect but is legal. */ public MyThing() { super(arg = (int)System.currentTimeMillis()); } } // Use alternative constructor invocation // Use private constructor capture
Page 26: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Classes: Visibility

Modifier Class Package Subclass World public Y Y Y Y protected Y Y Y N no modifier Y Y N N private Y N N N

2014.03.05 Valdas Rapševičius. Java Technologies 26

• Accessing class members

• Tips: – Use the most restrictive access level that makes sense for a

particular member. Use private unless you have a good reason not to.

– Avoid public fields except for constants. Public fields tend to link you to a particular implementation and limit your flexibility in changing your code.

Page 27: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Classes: Static Members

• Methods: public static int getNumberOfCars() { return numberOfCars; }

• Constants: static final double PI = 3.141592653589793;

• Static blocks: static { // whatever code is needed for initialization goes here }

• Rules: – Instance methods can access instance variables and instance methods directly. – Instance methods can access class variables and class methods directly. – Class methods can access class variables and class methods directly. – Class methods cannot access instance variables or instance methods directly—they must use an object reference.

Also, class methods cannot use the this keyword as there is no instance for this to refer to.

2014.03.05 Valdas Rapševičius. Java Technologies 27

Presenter
Presentation Notes
class Counter { private static int count = 0; public static final synchronized void increment() { count++; } public static final synchronized int getCount() { return count; } } class Dog extends Counter { public Dog() { } public void woof() { increment(); } } class Cat extends Counter { public Cat() { } public void meow() { increment(); } } public class Ruckus { public static void main(String[] args) { Dog dogs[] = { new Dog(), new Dog() }; for (int i = 0; i < dogs.length; i++) dogs[i].woof(); Cat cats[] = { new Cat(), new Cat(), new Cat() }; for (int i = 0; i < cats.length; i++) cats[i].meow(); System.out.print(Dog.getCount() + " woofs and "); System.out.println(Cat.getCount() + " meows"); } } class Dog { public static void bark() { System.out.print("woof "); } } ---- class Basenji extends Dog { public static void bark() { } } public class Bark { public static void main(String args[]) { Dog woofer = new Dog(); Dog nipper = new Basenji(); woofer.bark(); nipper.bark(); } }
Page 28: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Classes: nested Classes

• A class defined within another class is called a nested class. • A nonstatic nested class is called an inner class. • An instance of an inner class can exist only within an instance of its enclosing

class and has access to its enclosing class's members even if they are declared private

• Nested classes after compilation become normal classes with $ in the name class OuterClass { ... static class StaticNestedClass { ... } class InnerClass { ... } }

2014.03.05 Valdas Rapševičius. Java Technologies 28

Type Scope Inner

static nested class member no

inner [non-static] class member yes

local class local yes

anonymous class only the point where it is defined yes

Presenter
Presentation Notes
import java.util.Calendar; public class Elvis { public static final Elvis INSTANCE = new Elvis(); private final int beltSize; private static final int CURRENT_YEAR = Calendar.getInstance().get(Calendar.YEAR); private Elvis() { beltSize = CURRENT_YEAR - 1930; } public int beltSize() { return beltSize; } public static void main(String[] args) { System.out.println("Elvis wears a size " + INSTANCE.beltSize() + " belt."); } } ----- public static void greet() { System.out.println("Hello world!"); } public static void main(String[] args) { ((Null) null).greet(); } // Use static invocation Null.greet();
Page 29: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Interfaces

• An interface defines a protocol of communication between two objects.

• An interface declaration contains signatures, but no implementations, for a set of methods, and might also contain constant definitions.

• A class that implements an interface must implement all the methods declared in the interface.

• An interface name can be used anywhere a type can be used.

public interface GroupedInterface extends Interface1, Interface2 { double E = 2.718282; void doSomething (int i, double x); int doSomethingElse(String s);

}

2014.03.05 Valdas Rapševičius. Java Technologies 29

Page 30: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Interfaces: Mixin Definition

• Interfaces are ideal for defining mixins. A mixin is a type that a class can implement in addition to its “primary type” to declare that it provides some optional behavior.

• For example, Comparable is a mixin interface that allows a class to declare that its instances are ordered with respect to other mutually comparable objects.

• Abstract classes cannot be used to define mixins for the same reason that they can't be retrofitted onto existing classes: A class cannot have more than one parent, and there is no reasonable place in the class hierarchy to put a mixin.

2014.03.05 Valdas Rapševičius. Java Technologies 30

Page 31: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Interfaces: Non-hierarchical Type Frameworks

Type hierarchies are great for organizing some things, but other things don't fall neatly into a rigid hierarchy. For example, suppose we have an interface representing a singer and another representing a songwriter:

public interface Singer { AudioClip Sing(Song s); } public interface Songwriter { Song compose(boolean hit); }

In real life, some singers are also songwriters. Because we used interfaces rather than abstract classes to define these types, it is perfectly permissible for a single class to implement both Singer and Songwriter:

public interface SingerSongwriter extends Singer, Songwriter { AudioClip strum(); void actSensitive(); }

2014.03.05 Valdas Rapševičius. Java Technologies 31

Page 32: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Inheritance

public class Car { } public class OffroadCar extends Car { } public class SportsCar extends Car { }

Car b = new SportsCar(); Object o = new SportsCar(); if (o instanceof SportsCar) { SportsCar myCar = (SportsCar) o; }

• Overriding and Hiding Methods • Polymorphism • Hiding Fields

2014.03.05 Valdas Rapševičius. Java Technologies 32

Presenter
Presentation Notes
class Base { public String className = "Base"; } class Derived extends Base { private String className = "Derived"; } public class PrivateMatter { public static void main(String[] args) { System.out.println(new Derived().className); } } --- class Point { protected final int x, y; private final String name; // Cached at construction time Point(int x, int y) { this.x = x; this.y = y; name = makeName(); } protected String makeName() { return "[" + x + "," + y + "]"; } public final String toString() { return name; } } public class ColorPoint extends Point { private final String color; ColorPoint(int x, int y, String color) { super(x, y); this.color = color; } protected String makeName() { return super.makeName() + ":" + color; } public static void main(String[] args) { System.out.println(new ColorPoint(4, 2, "purple")); } } // Replace with lazy initialization
Page 33: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Object as Superclass

• The Object class, in the java.lang package, sits at the top of the class hierarchy tree. Every class is a descendant, direct or indirect, of the Object class.

• Standard methods inherited from Object are:

– protected Object clone() throws CloneNotSupportedException Creates and returns a copy of this object.

– public boolean equals(Object obj) Indicates whether some other object is "equal to" this one.

– protected void finalize() throws Throwable Called by the garbage collector on an object when garbage collection determines that there are no more references to the object

– public final Class getClass() Returns the runtime class of an object.

– public int hashCode() Returns a hash code value for the object.

– public String toString() Returns a string representation of the object.

2014.03.05 Valdas Rapševičius. Java Technologies 33

Presenter
Presentation Notes
MyClass t2 = (MyClass) new Object();
Page 34: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Object: Clone Usage

• The most probable reason for creating a local copy of an object is because you plan to modify the object, and you don't want to modify the method caller's object. If you decide that you need a local copy, you can perform the operation by using the clone() method of the Object class. The clone() method is defined as protected, but you must redefine it as public in all subclasses that you might want to clone.

• By default, classes in Java do not support cloning; the default implementation of the clone() method throws a CloneNotSupportedException. You should override implementation of the clone() method. Remember that you must make it public and, inside the method, your first action must be super.clone(). Classes that want to allow cloning must implement the marker interface Cloneable. class Test implements Cloneable { ... public Object clone() { try { return super.clone(); } catch( CloneNotSupportedException e ) { return null; } } ... }

• Solutions for deep copy: (1) use Serialization (covered later) or (2) specialized packages.

2014.03.05 Valdas Rapševičius. Java Technologies 34

Page 35: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Object: Equals Method

• Do not override Object.equals if: – Each instance of the class is inherently unique. This is true for classes that represent active entities

rather than values, such as Thread. The equals implementation provided by Object has exactly the right behavior for these classes.

– You don't care whether the class provides a “logical equality” test. For example, java.util.Random could have overridden equals to check whether two Random instances would produce the same sequence of random numbers going forward, but the designers didn't think that clients would need or want this functionality. Under these circumstances, the equals implementation inherited from Object is adequate.

– A superclass has already overridden equals, and the behavior inherited from the superclass is appropriate for this class. For example, most Set implementations inherit their equals implementation from AbstractSet, List implementations from AbstractList, and Map implementations from AbstractMap.

– The class is private or package-private, and you are certain that its equals method will never be invoked.

• When a class has a notion of logical equality that differs from mere object identity, and a superclass has not already overridden equals to implement the desired behavior. This is generally the case for value classes, such as Integer or Date.

• The equals method implements an equivalence relation: – reflexive: for any reference value x, x.equals(x) must return true. – symmetric: for any reference values x and y, x.equals(y) must return true if and only if y.equals(x) returns

true. – transitive: For any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true,

then x.equals(z) must return true. – It is consistent: For any reference values x and y, multiple invocations of x.equals(y) consistently return

true or consistently return false, provided no information used in equals comparisons on the object is modified.

– For any non-null reference value x, x.equals(null) must return false.

2014.03.05 Valdas Rapševičius. Java Technologies 35

Presenter
Presentation Notes
public class Conundrum { public static void main(String[] args) { Enigma e = new Enigma(); System.out.println(e.equals(e)); } } final class Enigma { // Provide a class body that makes Conundrum print false. // Do *not* override equals. }
Page 36: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Object: equals Method Example

public class Book { public boolean equals(Object obj) { if (obj instanceof Book) return ISBN.equals((Book)obj.getISBN()); else return false; } } • Use org.apache.commons utilities: public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } MyClass rhs = (MyClass) obj; return new EqualsBuilder() .appendSuper(super.equals(obj)) .append(field1, rhs.field1).append(field2, rhs.field2) .append(field3, rhs.field3).isEquals(); } public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj); }

2014.03.05 Valdas Rapševičius. Java Technologies 36

Page 37: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Object: finalize

• Finalizers are unpredictable, often dangerous, and generally unnecessary. Their use can cause erratic behavior, poor performance, and portability problems. Finalizers have a few valid uses, but as a rule of thumb, finalizers should be avoided [4]. – Nothing time-critical should ever be done by a finalizer. – You should never depend on a finalizer to update critical persistent state.

• Explicit termination methods are often used in combination with the try-

finally construct to ensure prompt termination:

// try-finally block guarantees execution of termination method Foo foo = new Foo(...); try { // Do what must be done with foo ... } finally { foo.terminate(); // Explicit termination method }

2014.03.05 Valdas Rapševičius. Java Technologies 37

Page 38: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Object: Explicit Termination in Java 7

class MyClass implements AutoCloseable { … @Override void close() throws Exception { // close resources, etc. } } … try (MyClass o = new MyClass()) { // Use o object as intended … } catch (Exception ex) { … }

2014.03.05 Valdas Rapševičius. Java Technologies 38

Page 39: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Object: hashCode Method

• You must override hashCode in every class that overrides equals. Failure to do so will result in a violation of the general contract for Object.hashCode, which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.

• The contract, copied from the java.lang.Object specification: – Whenever it is invoked on the same object more than once during an execution

of an application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

– If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

– It is not required that if two objects are unequal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

2014.03.05 Valdas Rapševičius. Java Technologies 39

Presenter
Presentation Notes
import java.util.*; public class Name { private String first, last; public Name(String first, String last) { this.first = first; this.last = last; } public boolean equals(Object o) { if (!(o instanceof Name)) return false; Name n = (Name)o; return n.first.equals(first) && n.last.equals(last); } public static void main(String[] args) { Set<Name> s = new HashSet<Name>(); s.add(new Name("Mickey", "Mouse")); System.out.println( s.contains(new Name("Mickey", "Mouse"))); } } ---- import java.util.*; public class Name { private String first, last; public Name(String first, String last) { this.first = first; this.last = last; } public boolean equals(Name n) { return n.first.equals(first) && n.last.equals(last); } public int hashCode() { return 31 * first.hashCode() + last.hashCode(); } public static void main(String[] args) { Set<Name> s = new HashSet<Name>(); s.add(new Name("Donald", "Duck")); System.out.println( s.contains(new Name("Donald", "Duck"))); } } // Add @Override to make sure
Page 40: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Object: hashCode Example

• Ideally, a hash function should distribute any reasonable collection of unequal instances uniformly across all possible hash values. In the real world this can be achieved by a fair approximation. public int hashCode() { int result = 17; result = 37 * result + areaCode; result = 37 * result + exchange; result = 37 * result + extension; return result; }

• If a class is immutable and the cost of computing the hash code is significant, you might

consider caching the hash code in the object rather than recalculating it each time it is requested.

• Use org.apache.commons (or other utilities): public int hashCode() { return new HashCodeBuilder(17, 37). append(areaCode).append(exchange).append(extension).toHashCode(); } } public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); }

2014.03.05 Valdas Rapševičius. Java Technologies 40

Page 41: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Object: toString Method

• java.lang.Object provides an implementation of the toString method and the output consists of the class name followed by an “at” sign (@) and the unsigned hexadecimal representation of the hash code, for example, “PhoneNumber@163b91.”

• Providing a good toString implementation makes your class much more pleasant to use. The toString method is automatically invoked when your object is passed to println, the string concatenation operator (+) or assert.

• The toString method should return all of the interesting information contained in the object.

• Use StringBuilder or similar utilities to construct the output.

2014.03.05 Valdas Rapševičius. Java Technologies 41

Page 42: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Object: project Lombok

• http://projectlombok.org/

• Annotations (and more!) – @ToString

No need to start a debugger to see your fields: Just let lombok generate a toString for you!

– @EqualsAndHashCode Equality made easy: Generates hashCode and equals implementations from the fields of your object.

– @NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor

Constructors made to order: Generates constructors that take no arguments, one argument per final / non-null field, or one argument for every field.

– @Data All together now: A shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, and @Setter on all non-final fields, and @RequiredArgsConstructor!

2014.03.05 Valdas Rapševičius. Java Technologies 42

Page 43: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Inheritance: Final Classes and Methods

• Use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses

• A class that is declared final cannot be subclassed class ChessAlgorithm { enum ChessPlayer { WHITE, BLACK } ... final ChessPlayer getFirstPlayer() { return ChessPlayer.WHITE; } ... }

2014.03.05 Valdas Rapševičius. Java Technologies 43

Presenter
Presentation Notes
final String pig = "length: 10"; final String dog = "length: " + pig.length(); System.out.println("Animals are equal: “ + pig == dog);
Page 44: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Immutable Classes

• An immutable class is simply a class whose instances cannot be modified. To make a class immutable, follow these rules:

– Don't provide any methods that modify the object (known as mutators). – Ensure that no methods may be overridden. – Make all fields final. – Make all fields private. This prevents clients from modifying fields directly. – Ensure exclusive access to any mutable components. If your class has any

fields that refer to mutable objects, ensure that clients of the class cannot obtain references to these objects. Make defensive copies in contructors, accessors, and readObject methods.

• Features of immutable objects:

– Immutable objects are simple. – Immutable objects are inherently thread-safe; they require no synchronization. – Not only can you share immutable objects, but you can share their internals. – Immutable objects make great building blocks for other objects. – The only real disadvantage of immutable classes is that they require a separate

object for each distinct value.

2014.03.05 Valdas Rapševičius. Java Technologies 44

Presenter
Presentation Notes
import java.math.BigInteger; public class BigProblem { public static void main(String[] args) { BigInteger fiveThousand = new BigInteger("5000"); BigInteger fiftyThousand = new BigInteger("50000"); BigInteger fiveHundredThousand = new BigInteger("500000"); BigInteger total = BigInteger.ZERO; total.add(fiveThousand); total.add(fiftyThousand); total.add(fiveHundredThousand); System.out.println(total); } }
Page 45: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Inheritance: Abstract Classes/Methods

• An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.

• An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this: abstract void moveTo(double deltaX, double deltaY);

• If a class includes abstract methods, the class itself must be declared abstract,

as in: public abstract class GraphicObject { // declare fields // declare non-abstract methods abstract void draw(); }

• When an abstract class is subclassed, the subclass usually provides

implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract.

2014.03.05 Valdas Rapševičius. Java Technologies 45

Page 46: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Numbers

• You use one of the wrapper classes – Byte, Double, Float, Integer, Long, or Short – to wrap a number of primitive type in an object. The Java compiler automatically wraps (boxes) primitives for you when necessary and unboxes them, again when necessary.

• The Number classes include constants and useful class methods. The MIN_VALUE and MAX_VALUE constants contain the smallest and largest values that can be contained by an object of that type. The byteValue, shortValue, and similar methods convert one numeric type to another. The valueOf method converts a string to a number, and the toString method converts a number to a string.

• To format a string containing numbers for output, you can use the printf() or format() methods in the PrintStream class. Alternatively, you can use the NumberFormat class to customize numerical formats using patterns.

• The Math class contains a variety of class methods for performing mathematical functions, including exponential, logarithmic, and trigonometric methods. Math also includes basic arithmetic functions, such as absolute value and rounding, and a method, random(), for generating random numbers.

2014.03.05 Valdas Rapševičius. Java Technologies 46

Page 47: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Character

char ch = 'a'; // Unicode for uppercase Greek omega character char uniChar = '\u039A'; // an array of chars char[] charArray = { 'a', 'b', 'c', 'd', 'e' };

Character ch = new Character('a');

• Boxing and unboxing

Character ch = 'a'; char c = a;

2014.03.05 Valdas Rapševičius. Java Technologies 47

Page 48: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

String • Strings are a sequence of characters and are widely used in Java programming. In the Java

programming language, strings are objects. The String class has over 60 methods and 13 constructors.

• Most commonly, you create a string with a statement like

String s = "Hello world!"; • The String class has many methods to find and retrieve substrings; these can then be easily

reassembled into new strings using the + concatenation operator.

• The String class also includes a number of utility methods, among them split(), toLowerCase(), toUpperCase(), and valueOf(). The latter method is indispensable in converting user input strings to numbers. The Number subclasses also have methods for converting strings to numbers and vice versa.

• In addition to the String class, there is also a StringBuilder class. Working with StringBuilder objects can sometimes be more efficient than working with strings. The StringBuilder class offers a few methods that can be useful for strings, among them reverse(). In general, however, the String class has a wider variety of methods.

• A string can be converted to a string builder using a StringBuilder constructor. A string builder can be converted to a string with the toString() method.

2014.03.05 Valdas Rapševičius. Java Technologies 48

Presenter
Presentation Notes
System.out.println(Me.class.getName().replaceAll(".", "/") + ".class"); System.out.println(Me.class.getName().replaceAll(Pattern.quote(".“), "/") + ".class"); System.out.println(Me.class.getName().replaceAll(Pattern.quote(".“), File.separator) + ".class"); System.out.println(Me.class.getName().replaceAll(Pattern.quote(".“), Matcher.quoteReplacement(File.separator)) + ".class"); System.out.print("iexplore:"); http://www.google.com; System.out.println(":maximize"); String s = "Labas"; s.concat(" "); s.concat("rytas"); println s
Page 49: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Enum

An enum type is a special data type that enables for a variable to be a set of predefined constants. Declaration: public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } Usage: Day day = Day.MONDAY; switch (day) { case MONDAY: System.out.println("Mondays are bad."); break; case FRIDAY: System.out.println("Fridays are better."); break; } for (Day d: Day.values()) { System.out.println(d.name()); }

2014.03.05 Valdas Rapševičius. Java Technologies 49

Page 50: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Enum: Example @Getter @RequiredArgsConstructor public enum Planet { MERCURY (3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), EARTH (5.976e+24, 6.37814e6), MARS (6.421e+23, 3.3972e6), JUPITER (1.9e+27, 7.1492e7), SATURN (5.688e+26, 6.0268e7), URANUS (8.686e+25, 2.5559e7), NEPTUNE (1.024e+26, 2.4746e7); private final double mass; // in kilograms private final double radius; // in meters // universal gravitational constant // (m3 kg-1 s-2) public static final double G = 6.67300E-11; double surfaceGravity() { return G * mass / (radius * radius); } double surfaceWeight(double otherMass) { return otherMass * surfaceGravity(); } }

void getYourWeight(double earthWeight) { double mass = earthWeight/EARTH.surfaceGravity(); for (Planet p : Planet.values()) System.out.printf( "Your weight on %s is %f%n", p, p.surfaceWeight(mass)); }

2014.03.05 Valdas Rapševičius. Java Technologies 50

Page 51: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Enum: Extensible interface

public interface Operation { public int apply(int x, int y); } public enum BasicOperation implements Operation { PLUS { public int apply(int x, int y) { return x + y; } }, MINUS { public int apply(int x, int y) { return x - y; } }; public static void main(String[] args) { for (Operation op: BasicOperation.values()) { System.out.println(op.apply(12,34)); } } }

2014.03.05 Valdas Rapševičius. Java Technologies 51

Page 52: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Enum: ordinal()

Do not use ordinal(), store it in field instead

public enum Day implements IndexedDay { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; @Override public int dayIndex() { return ordinal() + 1; } } public enum Day implements IndexedDay { SUNDAY(1), MONDAY(2), TUESDAY(3), WEDNESDAY(4), THURSDAY(5), FRIDAY(6), SATURDAY(7); private final int idx; Day(int idx) { this.idx = idx; } @Override public int dayIndex() { return idx; } }

2014.03.05 Valdas Rapševičius. Java Technologies 52

Page 53: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Generics: The Problem

public class Box {

private Object object;

public void add(Object object) { this.object = object; }

public Object get() { return object; }

}

public class BoxDemo1 {

public static void main(String[] args) {

Box integerBox = new Box();

integerBox.add(new Integer(10));

Integer i1 = (Integer) integerBox.get();

integerBox.add("10");

Integer i2 = (Integer) integerBox.get();

}

}

2014.03.05 Valdas Rapševičius. Java Technologies 53

Page 54: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Generics: Example

/** * Generic version of the Box class. * @param <T> the type of value being boxed */

public class Box<T> { // T stands for "Type"

private T t; public void add(T t) { this.t = t; } public T get() { return t; } }

public class BoxDemo2 {

public static void main(String[] args) {

Box<Integer> integerBox = new Box<Integer>();

integerBox.add(new Integer(10));

Integer i1 = integerBox.get(); // no cast!

System.out.println(someInteger);

}

}

2014.03.05 Valdas Rapševičius. Java Technologies 54

Page 55: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Generics: Bounded Types

• Bounded Type Parameters public <T extends Number> void inspect(T t){ ... • Wildcards

Cage<? extends Animal> someCage = ...; Read "? extends Animal" as "an unknown type that is a subtype of Animal, possibly Animal itself", which boils down to "some kind of animal".

2014.03.05 Valdas Rapševičius. Java Technologies 55

Page 56: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Generics: criticism

• Type erasure after compilation! • Type parameters cannot be determined at run-time

public class MyClass<E> {

public static void myMethod(Object item) {

if (item instanceof E) { //Compiler error

...

}

E item2 = new E(); //Compiler error

E[] iArray = new E[10]; //Compiler error

}

}

2014.03.05 Valdas Rapševičius. Java Technologies 56

Page 57: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Reference Conversions

• Widening reference conversions From any reference type S to any reference type T, provided S is a subtype of T.

• Narrowing reference conversions 6 cases. Require a test at run-time to find out whether the actual reference value is a legitimate value of the new type. If not, then a ClassCastException is thrown.

• Boxing conversions Converts expressions of primitive type to corresponding expressions of reference type.

• Unboxing conversions Converts expressions of reference type to corresponding expressions of primitive type.

• Unchecked conversions From the raw class or interface type G to any parameterized type of the form G<T1,...,Tn>.

• Capture conversions From a parameterized type G<T1,...,Tn> to a parameterized type G<S1,...,Sn>

• String conversions Any type may be converted to type String.

• Value set conversions

2014.03.05 Valdas Rapševičius. Java Technologies 57

Page 58: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Annotations

• Annotations provide data about a program that is not part of the program itself. They have no direct effect on the operation of the code they annotate.

• Annotations have a number of uses, among them: – Information for the compiler — Annotations can be used by the

compiler to detect errors or suppress warnings.

– Compiler-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.

– Runtime processing — Some annotations are available to be examined at runtime.

• Annotations can be applied to a program's declarations of classes, fields, methods, and other program elements.

2014.03.05 Valdas Rapševičius. Java Technologies 58

Page 59: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Annotations: Usage

@EqualsAndHashCode(callSuper = true, exclude = { "row" }) public class LobHandler extends PagedHandler<CcLob, LobExporter> { @Getter @Setter private Integer row; @Getter @Setter private Integer column; @Setter private MediaType mediaType; @Inject public LobHandler(@Assisted Query query) throws ResourceException { super(query, form); } @Override public LobExporter createExporter() { return rf.createLobExporter(this); } }

2014.03.05 Valdas Rapševičius. Java Technologies 59

Page 60: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Annotations: JSR 308: Annotations on Java Types (1)

• Method receivers: public int size() @Readonly { ... }

• generic type arguments: Map<@NonNull String, @NonEmpty List<@Readonly Document>> files; • Arrays: Document[@Readonly] docs1; Document[][@Readonly] docs2 = new Document[2][@Readonly 12]; • Typecasts: myString = (@NonNull String)myObject;

2014.03.05 Valdas Rapševičius. Java Technologies 60

Page 61: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Annotations: JSR 308: Annotations on Java Types (2)

• Type tests: boolean isNonNull = myString instanceof @NonNull String; • Object creation: new @NonEmpty @Readonly List(myNonEmptyStringSet) • Class inheritance: class UnmodifiableList implements @Readonly List<@Readonly T> { ... } • Throws clauses: void monitorTemperature() throws @Critical TemperatureException { ... }

2014.03.05 Valdas Rapševičius. Java Technologies 61

Page 62: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Annotations: Compiler @Deprecated—the @Deprecated annotation indicates that the marked element is deprecated and should no longer be used. The compiler generates a warning whenever a program uses a method, class, or field with the @Deprecated annotation. When an element is deprecated, it should also be documented using the Javadoc @deprecated tag, as shown in the following example. @Deprecated static void deprecatedMethod() { } @Override—the @Override annotation informs the compiler that the element is meant to override an element declared in a superclass (overriding methods will be discussed in the the lesson titled "Interfaces and Inheritance"). @Override int overriddenMethod() { } @SuppressWarnings—the @SuppressWarnings annotation tells the compiler to suppress specific warnings that it would otherwise generate. In the example below, a deprecated method is used and the compiler would normally generate a warning. In this case, however, the annotation causes the warning to be suppressed. @SuppressWarnings("deprecation") void useDeprecatedMethod() { objectOne.deprecatedMethod(); }

2014.03.05 Valdas Rapševičius. Java Technologies 62

Page 63: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Annotations: Custom

Definition: @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @interface Test { String info() default ""; } Usage: class Annotated { @Test(info = "AWESOME") public void foo(String myParam) { System.out.println("This is " + myParam); } }

2014.03.05 Valdas Rapševičius. Java Technologies 63

Page 64: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Packages

• To create a package for a type, put a package statement as the first statement in the source file that contains the type (class, interface, enumeration, or annotation type).

• To use a public type that's in a different package, you have three choices: (1) use the fully qualified name of the type, (2) import the type, or (3) import the entire package of which the type is a member.

• The path names for a package's source and class files mirror the name of the package.

• You might have to set your CLASSPATH so that the compiler and the JVM can find the .class files for your types.

• Naming Conventions – Package names are written in all lower case to avoid conflict with the names of

classes or interfaces. – Companies use their reversed Internet domain name to begin their package

names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.

– Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.example.region.mypackage).

– Packages in the Java language itself begin with java. or javax.

2014.03.05 Valdas Rapševičius. Java Technologies 64

Page 65: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Naming Convention: Typographical

2014.03.05 Valdas Rapševičius. Java Technologies 65

Identifier Type Examples

Package com.sun.medialib, com.sun.jdi.event

Class or Interface Timer, TimerTask, KeyFactorySpi, HttpServlet

Method or Field remove, ensureCapacity, getCrc

Constant Field VALUES, NEGATIVE_INFINITY

Local Variable i, xref, houseNumber

• The Java platform has a well-established set of naming conventions, many of which are contained in The Java Language Specification. Naming conventions fall into two categories: typographical and grammatical.

• Typographical convention examples:

Page 66: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Naming Convention: Grammatical (1)

Classes • Classes are generally named with a noun or noun phrase, for example,

Timer or BufferedWriter. Interfaces are named like classes, for example, Collection or Comparator, or with an adjective ending in “-able” or “-ible,” for example, Runnable or Accessible.

Fields • Grammatical conventions for field names are less well established and

less important than those for class, interface, and method names, as well-designed APIs contain few if any exposed fields. Fields of type boolean are typically named like boolean accessor methods with the initial “is” omitted, for example, initialized, composite.

• Fields of other types are usually named with nouns or noun phrases, such as height, digits, or bodyStyle.

• Grammatical conventions for local variables are similar to those for fields but are even weaker.

2014.03.05 Valdas Rapševičius. Java Technologies 66

Presenter
Presentation Notes
public class StrungOut { public static void main(String[] args) { String s = new String("Hello world"); System.out.println(s); } } class String { private final java.lang.String s; public String(java.lang.String s) { this.s = s; } public java.lang.String toString() { return s; } }
Page 67: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Naming Convention: Grammatical (2)

Methods • Methods that perform some action are generally named with a verb or verb

phrase, for example, append or drawImage. • Methods that return a boolean value usually have names that begin with the

word “is,” followed by a noun, a noun phrase, or any word or phrase that functions as an adjective, for example, isDigit, isProbablePrime, isEmpty, isEnabled, isRunning.

• Methods that return a nonboolean function or attribute of the object on which they're invoked are usually named with a noun, a noun phrase, or a verb phrase beginning with the verb “get,” for example, size, hashCode, or getTime. The form beginning with “get” is mandatory if the class containing the method is a Bean. In this case, the two methods should be named getAttribute and setAttribute.

• Methods that convert the type of an object, returning an independent object of a different type, are often called toType, for example, toString, toArray.

• Methods that return a view whose type differs from that of the receiving object, are often called asType, for example, asList.

• Methods that return a primitive with the same value as the object on which they're invoked are often called typeValue, for example, intValue. Common names for static factories are valueOf and getInstance.

• for local variables are similar to those for fields but are even weaker.

2014.03.05 Valdas Rapševičius. Java Technologies 67

Page 68: Java Technologies. JAVA basics - klevas.mif.vu.ltvaldo/jate2014/JavaTech.L01.pdf · • Basic understanding of Java type system including – Numbers – Character – String –

Session Conclusions

• You must have refreshed your memories about the principles of Object-Oriented Programming and Java programming language

• You must be familiar with Java types and you can always refer to the references and the slides while working

• You should know what Generics and Annotations are and where to you it

• Please from now on you the standard Java Naming Convention for your prototypes, tasks

• You must have the basic environment setup for the small programming exercises during the session and for your project

2014.03.05 Valdas Rapševičius. Java Technologies 68