java technologies. java basicsvaldo/jate2016/javatech.l01.pdfjava technologies lecture i 2016.02.22...
TRANSCRIPT
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
2016.02.22
Java Technologies Lecture I
2016.02.22 Valdas Rapševičius. Java Technologies 1
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
2016.02.22 Valdas Rapševičius. Java Technologies 2
OOP: Objects
• Real-world objects: – state – behaviour
• An object: – stores its state in fields (aka variables) – exposes its behaviour through methods (aka functions)
• Benefits: – Modularity – Information-hiding – Code re-use – Plug-ability and debugging ease
2016.02.22 Valdas Rapševičius. Java Technologies 3
OOP : Classes 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);
} }
2016.02.22 Valdas Rapševičius. Java Technologies 4
OOP: Classes
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();
} }
speed:10 gear:2 speed:20 gear:3
2016.02.22 Valdas Rapševičius. Java Technologies 5
OOP: Inheritance
class Car { // Common car fields and // methods variables } class SportsCar extends Car { // new fields and methods // defining a sports car }
Car
OffroadCar SportsCar ElectricCar
2016.02.22 Valdas Rapševičius. Java Technologies 6
OOP: Interfaces
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
}
2016.02.22 Valdas Rapševičius. Java Technologies 7
OOP: Packages
• A package is a namespace that organizes a set of related classes and interfaces. java.io java.lang java.math java.net java.nio java.rmi java.security java.sql java.text java.time
• http://docs.oracle.com/javase/8/docs/api/index.html
2016.02.22 Valdas Rapševičius. Java Technologies 8
java.util javax.naming javax.net javax.sql javax.swing javax.xml org.omg.CORBA org.w3c.dom org.xml.sax
Variables
• Instance Variables (Non-Static Fields) class Car { private String model; }
• Class Variables (Static Fields)
class Car { private static int NUM_WEELS = 4; }
• Local Variables class Car { public int changeGear() { int c = 0; } }
• Parameters
class Car { public int changeGear(boolean up) { } }
2016.02.22 Valdas Rapševičius. Java Technologies 9
Primitive Types
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
2016.02.22 Valdas Rapševičius. Java Technologies 10
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;
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;
2016.02.22 Valdas Rapševičius. Java Technologies 11
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)
2016.02.22 Valdas Rapševičius. Java Technologies 12
Problems with Primitive Numbers
• All signed • Float and Double
– Approximate precision (IEEE 754) • At Limits
– Silent Overflows – Not symmetric values
• If not sure use – java.math.BigInteger
• Immutable arbitrary-precision integers. Unscaled. – java.math.BigDecimal
• Immutable, arbitrary-precision signed decimal numbers. Unscaled integer value and a 32-bit integer scale.
2016.02.22 Valdas Rapševičius. Java Technologies 13
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; }
2016.02.22 Valdas Rapševičius. Java Technologies 14
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
2016.02.22 Valdas Rapševičius. Java Technologies 15
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
2016.02.22 Valdas Rapševičius. Java Technologies 16
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)
2016.02.22 Valdas Rapševičius. Java Technologies 17
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.
2016.02.22 Valdas Rapševičius. Java Technologies 18
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
}
2016.02.22 Valdas Rapševičius. Java Technologies 19
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; }
}
2016.02.22 Valdas Rapševičius. Java Technologies 20
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) {...}
}
2016.02.22 Valdas Rapševičius. Java Technologies 21
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);
2016.02.22 Valdas Rapševičius. Java Technologies 22
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; }
}
2016.02.22 Valdas Rapševičius. Java Technologies 23
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
2016.02.22 Valdas Rapševičius. Java Technologies 24
• 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.
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.
2016.02.22 Valdas Rapševičius. Java Technologies 25
Classes: nested Classes
• A class defined within another class is called a nested class. • A non-static 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 { ... } }
2016.02.22 Valdas Rapševičius. Java Technologies 26
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
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);
}
2016.02.22 Valdas Rapševičius. Java Technologies 27
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.
2016.02.22 Valdas Rapševičius. Java Technologies 28
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(); }
2016.02.22 Valdas Rapševičius. Java Technologies 29
Default methods (Java SE 8)
public interface Moveable { int getX(); void setX(int x); default void moveHorizontally(int distance) { setX(getX() + distance); } } public interface Sized { int getSize(); default boolean isEmpty() { return getSize() == 0; } }
• Reusable code in mixins • Interfaces still can not have state
2016.02.22 Valdas Rapševičius. Java Technologies 30
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
2016.02.22 Valdas Rapševičius. Java Technologies 31
Object as Superclass
– 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.
2016.02.22 Valdas Rapševičius. Java Technologies 32
Object: Clone Usage
• 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: – Serialization (covered later) – specialized packages.
2016.02.22 Valdas Rapševičius. Java Technologies 33
Object: Equals Method (1)
• 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.
2016.02.22 Valdas Rapševičius. Java Technologies 34
Object: Equals Method (2)
• The equals method implements an equivalence relation: – reflective: 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.
2016.02.22 Valdas Rapševičius. Java Technologies 35
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); }
2016.02.22 Valdas Rapševičius. Java Technologies 36
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. – 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 }
2016.02.22 Valdas Rapševičius. Java Technologies 37
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) { … }
2016.02.22 Valdas Rapševičius. Java Technologies 38
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.
2016.02.22 Valdas Rapševičius. Java Technologies 39
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); }
2016.02.22 Valdas Rapševičius. Java Technologies 40
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.
2016.02.22 Valdas Rapševičius. Java Technologies 41
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!
2016.02.22 Valdas Rapševičius. Java Technologies 42
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 final class ChessAlgorithm { enum ChessPlayer { WHITE, BLACK } ... ChessPlayer getFirstPlayer() { return ChessPlayer.WHITE; } ... }
2016.02.22 Valdas Rapševičius. Java Technologies 43
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.
2016.02.22 Valdas Rapševičius. Java Technologies 44
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.
2016.02.22 Valdas Rapševičius. Java Technologies 45
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.
2016.02.22 Valdas Rapševičius. Java Technologies 46
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;
2016.02.22 Valdas Rapševičius. Java Technologies 47
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.
2016.02.22 Valdas Rapševičius. Java Technologies 48
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()); }
2016.02.22 Valdas Rapševičius. Java Technologies 49
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)); }
2016.02.22 Valdas Rapševičius. Java Technologies 50
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)); } } }
2016.02.22 Valdas Rapševičius. Java Technologies 51
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; } }
2016.02.22 Valdas Rapševičius. Java Technologies 52
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();
}
}
2016.02.22 Valdas Rapševičius. Java Technologies 53
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<>();
integerBox.add(new Integer(10));
Integer i1 = integerBox.get(); // no cast!
System.out.println(someInteger);
}
}
2016.02.22 Valdas Rapševičius. Java Technologies 54
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".
2016.02.22 Valdas Rapševičius. Java Technologies 55
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
}
}
2016.02.22 Valdas Rapševičius. Java Technologies 56
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
2016.02.22 Valdas Rapševičius. Java Technologies 57
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.
2016.02.22 Valdas Rapševičius. Java Technologies 58
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); } }
2016.02.22 Valdas Rapševičius. Java Technologies 59
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;
2016.02.22 Valdas Rapševičius. Java Technologies 60
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 { ... }
2016.02.22 Valdas Rapševičius. Java Technologies 61
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(); }
2016.02.22 Valdas Rapševičius. Java Technologies 62
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); } }
2016.02.22 Valdas Rapševičius. Java Technologies 63
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.
2016.02.22 Valdas Rapševičius. Java Technologies 64
Naming Convention: Typographical
2016.02.22 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:
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.
2016.02.22 Valdas Rapševičius. Java Technologies 66
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.
2016.02.22 Valdas Rapševičius. Java Technologies 67
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
2016.02.22 Valdas Rapševičius. Java Technologies 68