Java Course 2: Basics

14

Click here to load reader

description

Lecture 2 from the IAG0040 Java course in TTÜ. See the accompanying source code written during the lectures: https://github.com/angryziber/java-course

Transcript of Java Course 2: Basics

Page 1: Java Course 2: Basics

Java Basics,Java Basics,Program FlowProgram Flow

Java course - IAG0040Java course - IAG0040

Anton Keks 2011

Page 2: Java Course 2: Basics

Lecture 2Lecture 2Slide Slide 22

Java course – IAG0040Anton Keks

Java type systemJava type system● static type checking

– by compiler, type declarations required

● strongly typed

– runtime checking

– automatic conversions allowed only when not loosing information

● memory-safe

– array bounds checking, no pointer arithmetic

● provides (benefits)– safety

● many bugs are type errors

– documentation– abstraction

● high-level thinking

– optimization (performance)

Page 3: Java Course 2: Basics

Lecture 2Lecture 2Slide Slide 33

Java course – IAG0040Anton Keks

Objects and ClassesObjects and Classes

● Classes introduce new types into a program● First appeared in Simula-67 to define 'classes of

objects'● In OOP, Objects are instances of Classes

● All objects of the same class share – same properties:

● fields hold internal state

– same behavior, dependent on the state: ● methods used for communication with objects

Page 4: Java Course 2: Basics

Lecture 2Lecture 2Slide Slide 44

Java course – IAG0040Anton Keks

ReferencesReferences● You manipulate objects with references

– Like remote control of a TV is a reference to the TV● Objects are stored on the heap, independently

– String s; // is a reference to nothing

– s = “hello”; // now s points to a newly created// String object on the heap

● You must create all the objects before using them– s = new Date();

● There are many other built-in types (classes), like Integer, Date, Currency, BigDecimal, etc, and making your own types is the point of OOP

Page 5: Java Course 2: Basics

Lecture 2Lecture 2Slide Slide 55

Java course – IAG0040Anton Keks

Variables and FieldsVariables and Fields

● Local variables– inside of methods– final variables can't change their values

● Class members (fields)– inside of classes, outside of methods

● Global variables– don't exist in Java– can be simulated with static class members

● Constants are static final fields

Page 6: Java Course 2: Basics

Lecture 2Lecture 2Slide Slide 66

Java course – IAG0040Anton Keks

Primitive typesPrimitive types

● Only primitives are not objects in Java– But, there are wrapper classes. Unlike in C, formats and

sizes are standardized and are always the same.Primitive Size Min Max Wrapper Defaultboolean 1 bit? false true Boolean falsechar 16 bit Unicode 0 Character '\u0000'byte 8 bit -128 127 Byte (byte)0short 16 bit Short (short)0int 32 bit Integer 0long 64 bit Long 0Lfloat 32 bit IEEE 754 IEEE 754 Float 0.0fdouble 64 bit IEEE 754 IEEE 754 Double 0.0dvoid - - - Void -

216-1 (UTF-16)

-215 215-1-231 231-1-263 263-1

Page 7: Java Course 2: Basics

Lecture 2Lecture 2Slide Slide 77

Java course – IAG0040Anton Keks

High-precision numbersHigh-precision numbers

● BigInteger and BigDecimal– these are classes, not primitives– immutable– cannot be used with operators, operations are

methods– slower, but long and precise

● BigInteger – arbitrary long integers● BigDecimal – arbitrary precision fixed point

numbers

Page 8: Java Course 2: Basics

Lecture 2Lecture 2Slide Slide 88

Java course – IAG0040Anton Keks

Fields (Members)Fields (Members)

● A field (or member) is a class variable, holds its state

● Field names are in “lowerCamelCase”

● Constant names are in UPPER_CASE

● Initialized either automatically or manually● class MyClass {

boolean isEmpty; // a fieldint count; // a second field

static String foo = “bar”; // a static fieldstatic final double E = Math.E; // a constant

static {foo = “fooBar”; // static block

}}

Page 9: Java Course 2: Basics

Lecture 2Lecture 2Slide Slide 99

Java course – IAG0040Anton Keks

MethodsMethods● A method is a class function, used to execute

an operation on a class (aka send a message)● class MyClass {

int count; // a fieldvoid doStuff(int count, short b) { // a method

this.count = count * b; // method body}int getCount() { // second method,

return count; // returning a value}

}

● Methods can be overloaded

● Parameters are passed as references

● Local variables are enforced to be manually initialized

Page 10: Java Course 2: Basics

Lecture 2Lecture 2Slide Slide 1010

Java course – IAG0040Anton Keks

Accessing fields and methodsAccessing fields and methods

● Java uses a dot '.' as an accessor operator– MyClass myObject = new MyClass();myObject.isEmpty = true; // field access

– myObject.setCount(5); // method call

– int j = new MyClass().getCount(); // also allowed

● Static fields and methods are accessed through the class itself, not instance variables– int i = Integer.MAX_VALUE;

● “Deep” access is possible– System.out.println(“Hello!”);

Page 11: Java Course 2: Basics

Lecture 2Lecture 2Slide Slide 1111

Java course – IAG0040Anton Keks

Access Modifiers and VisibilityAccess Modifiers and Visibility

● Several access modifiers are in use (keywords):

– private – accessible only in the same class

– default, no keyword (package local) – accessible only in the same package

– protected – accessible in the same package and subclasses

– public – accessible from anywhere● public class HelloWorld {

int a;private int b;protected void doStuff() {}private HelloWorld() {}

}

// public class// package local field// private field// protected method// private constructor

Page 12: Java Course 2: Basics

Lecture 2Lecture 2Slide Slide 1212

Java course – IAG0040Anton Keks

EncapsulationEncapsulation

● Use the most restrictive access modifiers as possible

● Classes 'hide' implementations and internal details from their users

– This allows changing of internals any times without breaking any usages

– The less internals exposed, the easier is to change them

● Public/accessible interface must be obvious to use; don't do anything unexpected!

Page 13: Java Course 2: Basics

Lecture 2Lecture 2Slide Slide 1313

Java course – IAG0040Anton Keks

OperatorsOperators

● Arithmetical: + - * / %

● Bitwise: ~ & | ^ << >> >>>

● Boolean: ! & | ^

● Relational: < > <= >= == !=

● Conditional: && || ^^ ternary: ? :

● Assignment: = += -= *= /= %= <<= >>= &= |= ^=

● String concatenation: +

● Unary: + - ++ -- ! ~ (cast)

● Type comparision: instanceof

Page 14: Java Course 2: Basics

Lecture 2Lecture 2Slide Slide 1414

Java course – IAG0040Anton Keks

Naming conventionNaming convention● Packages: lower case, reversed domain name as prefix

– net.azib.hello, java.util, com.sun.internal

● Classes: camel case, should contain a noun

– String, ArrayList, System, VeryAngryDogWithTeeth

● Interfaces: camel case, often adjectives

– Collection, List, Comparable, Iterable

● Variables and fields: lower camel case, often include the class name

– isEmpty, count, i, veryLongArrayList

● Methods: lower camel case, contain verbs

– doStuff, processRequest, length, getLength

● Constants: underscore ('_') separated upper case

– Math.PI, MAX_VALUE, NAME_PREFIX

● Names should be obvious and descriptive!!!

– System.currentTimeMillis(), s.substring(0, 3), s.toCharArray()