Issuu on Google+

Back to Basics Advanced Programming 2014


Ghosts of Lessons Past • Data types and internal representations – Primitive types – Objects – Literals

• Operators • Polymorphism – Interfaces, Classes, Inheritance

• Useful Java Syntax – – – –

Inner classes Anonymous classes Enumerations Special Array methods

2


Primitive Data Types

• byte, short, int, long • char

64 bit signed integer 32 bit signed integer 16 bit signed integer

• What is an x-bit integer?

8 bit signed integer

– can be written with x binary digits 185 = 128+32+16+8+1 =

• Signed?

-71 =

185-28

=

16 bit unsigned integer 27

26

25

24

23

22

21

20

1

0

1

1

1

0

0

1

±

26

25

24

23

22

21

20

1

1

1

0

0

1

1 0 – Can hold negative values – Represented  in  “two’s  complement”

3


Primitive Data Types • boolean • float, double

true or false (1 bit) 64-bit floating-point 32-bit floating-point

– Representation:  “scientific  notation”  (base  2): ±

Exponent

Significand (Mantissa)

1 1 0 0 0 0 0 0 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

8 bit signed integer: Subtract 127 (bias) Exponent=129-127=2

24 bit unsigned fraction: Assume  leading  “1.”

Significand=1.101=1+1/2+1/8

Value: 2Exp.*Sig.=110.1=6.5

– Special values: 0, NaN,  +∞,  -∞ 4


Reference Data Types • More complex than primitive types • Object-type variable contains a reference – References point to object location in memory – Representation: depends on JVM • Can be actual 32/64-bit memory address • You should never need to use the internal representation.

• Special predefined object types: – – – –

Object arrays (a type of Object) String (a type of Object) null (has a special null type) 5


Numeric Literals

• “literal”  values

Java 7 and up

– Also have types

• int:

Decimal literal int x = 1025; int y = -8; int z = 34;

Hex literal int x = 0x401; int y = -0x8; int z = 0x22

Octal literal int x = 02001; int y = -010; int z = 042;

Binary literal int x = 0b10000000001; int y = -0b1000; int z = 0b000100010;

• long: add an L or an l as suffix Decimal literal long x = 9223372036854775807L;

Hex literal long x = 0x7fffffffffffffffL;

• double, float: double d = 1.; double d = 1d; double d = 320.432; double d = 3.204e3; double d = 0.0032; double d = 3.2e-3;

float f = 1.f; float f = 1f; float f = 320.432f; float f = 3.204e3f; float f = 0.0032f; float f = 3.2e-3f;

// Infinity double d =1d/0; // -Infinity double d = -1d/0; // NaN double d = 0d/0;

6


String and Char Literals • Java uses UTF16 internally – UTF16: 16-bit-per-character encoding for Unicode – Unicode:  gives  every  “character”  a  unique  code – Currently defines more than 110,000 characters

• Char literal:

Char literals char  x  =  ‘a’; char  y  =  ‘\u0061’; ch\u0061r  z  =  ‘a’;

Character Escape codes char  newline  =  ‘\n’; char  backslash  =  ‘\\’; char  quote  =  ‘\’’;

• String  literal:  “quoted  text”   – Internally, String is a sequence of char values

• Can you spot the contradiction on this page? 7


Array Literals? • No array literals. But you can use array initializers: Array Initializers int[] intsArray = {1, 2, 3}; Object[] objArray = {new String() };

• Can only be used in variable declaration • Evaluated at runtime, not compile time 8


Java Operators Assignment

=

Arithmetic

+

-

*

/

%

++

--

Relational

<

>

<=

>=

==

!=

instanceof

Logical

&&

||

!

Bitwise

&

|

~

^

<<

>>

>>>

Compound assignment

+=

-= *= /=

&=

|=

>>>=

Conditional

?:

prefix++/postfix++ j = 5; k = ++j; // j is 6, k is 6 j = 5; k = j++; // j is 6, k is 5

bitwise shift j = -0b101; j >>= 1; // j is -0b10 j = -0b101; j >>>= 1; // what is j?

-0b101 in  two’s  complement: 232-5=0xFFFFFFFB=0b111…1011 shift right 1: 0b0111…101=0x7FFFFFFD

bitwise negation j = -0b101; k = ~j; // flipped all bits // what is j now?

<<= >>= ^=

conditional // like if/then j = (5 > 4) ? 1 : 2 // what is j now?

negate -0b101 bitwise: ~0b111…1011=0b100=4 General rule: ~x==(-x)-1 9


Java Operators â&#x20AC;˘ More bit operations: â&#x20AC;&#x201C; Isolating bits: bitwise and j = 0b11101001; j &= 0b11110000; // j is 0b11100000 (bitwise-and isolates 1 bits) j >>>= 4; // j is 0b00001110

â&#x20AC;&#x201C; Setting bits

bitwise or j = 0b11101001; j &= ~0b11110000; // clear bits // j is 0b00001001 j |= 0b10110000; // set bits // j is 0b10111001 10


Classes

• All java objects have a Class type. • Classes have: – fields – methods

• A class is a definition – Only its static fields/methods exist at first

• A class can be instantiated – Memory is allocated – The  class’s  constructor is called • performs initialization (e.g., initialize member fields)

• Every instance of a class has its own field values – (static field values are shared) – special field named this • reference to this instance of the class 11


Abstract Classes, Interfaces • Methods can be declared abstract • Abstract methods have no implementation – A class with an abstract method cannot be instantiated! – must declare the class abstract

• An interface is a collection of method signatures – interfaces define an API – don’t  contain  any  implementation – May contain constants • final static variables with initializer

Signature: name, parameter types, return types

12


Subclassing and Implementing • A class can declare that it implements an interface – This  is  a  “promise”  that  it  implements  the  API

• Classes can implement multiple interfaces • A class can declare that it extends another class – This  means  it  “inherits”  all  its  fields  and  methods   – Can overload methods • new method with same name but different signature

– Can override methods: • new method with same name and signature • Changes the implementation of the method. 13


Inheritance and Polymorphism • B extends A B “is-an”  A • Reference to A can contain actual type B • Methods in Java are virtual – When a method is called JVM looks for actual type at runtime – Even if reference is to super class

public class Bar { public void doPrint() { System.out.println("Hello Bar"); } } public class Baz extends Bar { @Override public void doPrint() { System.out.println("Hello Baz"); } } public static void main(String[] args) { Bar bar = new Baz(); bar.doPrint(); }

What will this print?

14


Classes, Interfaces, Inheritance • Classes can be arranged in a tree • Every class has one superclass (parent)

I1

I4

– Except Object: it is the root of the class tree

• If A is a superclass of B, B is a subclass of A – A class can have many subclasses. – B is a subclass of A B extends A

I2

I6

C1

I3

I5

I7

C2

I8

C3

• Interfaces can be arranged in a DAG – An interface can extend multiple interfaces – A class can implement multiple interfaces

C4

15


Casting and Overriding Methods • Casting is moving between types. – For primitive types, needed explicitly if data could be lost: • int a = (int) 4.5; // explicit • double d = 1.43e4f; // implicit

– For reference types: • A a = new B(); // if B is-an A • B b = (B) a; // explicit otherwise

public class Bar { public Bar test() { return new Bar(); } } public class Baz extends Bar { @Override public Baz test() { return new Bar(); } } public static void main(String[] args) { Bar bar = new Baz(); System.out.println(bar.test()); }

• When overriding methods, return type can be narrower (if B is-an A then B is narrower than A) – why not wider? 16


Subclasses and Constructors • Every class has a constructor – If  you  don’t  define  one,  has  default • If you do define one, there is no default

• When instantiating, all the constructors are called – What is the order?

• You can call specific superclass constructor using super()

public class Bar { int a; public Bar() { a = 1; } } public class Baz extends Bar { public Baz() { a = 2; } } public static void main(String[] args) { Bar bar = new Baz(); }

– Must be first call in constructor 17


Inner Classes • Class declaration inside another class • Static member class: – Just a regular class – Full class name:

/** * A class that implements a concrete Entry (used to return word/deflist values). * @author talm * */ public static class StaticEntry implements Entry<String,String> { String word;

String def; public StaticEntry(String word, String def) { this.word = word; this.def = def; } . . . @Override public String setValue(String value) { String oldDef = def; def = (String) value; return oldDef; }

• Outer.Inner

– Used to create more refined namespaces

}

• Java compiler creates Outer$Inner.class file 18


Inner Classes

• non-static member class

– Can only be instantiated with instance of outer public class Foo { class String hello = "hello world"; • Has access to outer member variables • Can explicitly refer to outer class’s  members:     – Outer.member – Outer.this

public class Bar { public void doPrint() { System.out.println(hello); } } public static void main(String[] args) { Foo foo = new Foo(); Bar bar = foo.new Bar(); bar.doPrint(); } }

– Has reference to instance of outer class • But is not a subclass or superclass! • e.g.: (bar instanceof Foo)  →  false; 19


Anonymous Classes • Create  a  “single-use”  class  without  a  name class A { public interface IntGetter { public int get(); }

private int value; public IntGetter getter = new IntGetter() { public int get() {return value; } }; }

• Special syntax for new operator • Behaves just like regular inner class – (extends/implements the argument to new) – Can access member variables. – Can access final method variables

20


Enumerations • Special type of member class • Used when a variable can have a finite set of values. • More descriptive than integers • Can be used in switch statements • More type-safe than strings (and integers)

/** * Possible Suits in a card game. * @author talm * */

public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES } Suit suit;

– Compiler checks assignments

• Defines default toString(), hashCode(), methods; implements Comparable – Can override and also define your own custom methods

SPADES is an instance of Suit

Suit is a static inner class

• Efficient implementations of EnumSet and EnumMap 22


Useful Array Methods • In java.util.Arrays: public static <T> List<T> asList(T... a) provides a convenient way to create a fixed-size list initialized to contain several elements: List stooges = Arrays.asList("Larry", "Moe", "Curly");

– Also methods for sorting, comparing, searching.

• In java.lang.System: public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

23


20140224 review