본문 바로가기
What I Learned/Java

Hybrids (1~7) Summary

by 단풍국범생이 2019. 4. 21.

Hybrid 1 - UML

 

+ public
- private
# protected
INTEREST_RATE final
<< >> interface
numberOfAccounts static
calculatePat() abstract

<Order of diagram>

1. class name

2. class field

3. constructor(s)

4. methods

 

<Relationships>

1. interface

2. composition

3. inheritance

4. aggregation

aggregation - composition

 


 

Hybrid 2 - Debug

 


Hybrid 3 - Java Static Members (Part1)

A class is loaded once into memory, and it is always the same

class member: anything static that is loaded with the class only, members declared static are loaded first, and only once as part of the class, not the object

Static methods can talk only to other static members, cannot talk to uninstantiated members

instance member: initially with the class and again with instantiated objects, can talk to both instance and static members

 

fully qualified name: it is needed to call a static method located in a different package

utility classes: classes consist of nothing but static members; Arrays, Collections, Objects

 

Hybrid 3 - Reference Type (Part1)

Eight primitive type

1. boolean

2. byte

3. short

4. char

5. int

6. long

7. float

8. double

 

 

Three reference type

1. arrays

2. classes

3. interfaces

 

passing mechanism

- pass-by-value

- pass-by-reference

 

reference value: rather than pass an actual address to a method, Java passes a number which is a reference value

you are only passing the reference value into the variable, but you are not making a copy of the object itself.

i.e. Scanner input = new Scanner(System.in); => input does not contain a Scanner object but only reference value

 


Hybrid 4 - FILE I/O (Part1)

File class: machine-dependent details of files manipulation; renaming, deleting, obtaining file directories

Does not contain reading and writing file contents

An absolute path

A relative path

The single backslash indicates an escape sequence (i.e. \t) => Use double slashes

The single forward slash is compatible with Windows and UNIX path naming format 

 

Scanner: typically read data from the input stream, also overloaded to read in a File type

i.e.

(1) File myFile = new File("SomeFileName.ext");

    Scanner fileIn = new Scanner(myFile);

(2) Scanner fileIn = new Scanner(new File("SomeFileName.ext"));

 

PrintWriter: Scanner's output counterpart

i.e.

// File object instatiated

PrintWriter ouput = new PrintWriter(file);

ouput.print("John Smith");

ouput.close();

 

 

Hybrid 4 - FILE I/O (Part2)

File I/O with objects: replace string classes(Scanner, PrintWriter) with the stream classes

 

i.e.

(1) FileOutputStream objectFileStream = new FileOutputStream("Employee.obj");

ObjectOutputStream oos = new ObjectOutputStream(objectFileStream);

oos.writeObject(emp); // emp is an Employee object

 

(2) Employee[] emp = new Employee[numOfEmps]; // assume that numOfEmps is constant integer 24

FileOutputStream objectFileStream = new FileOutputStream("Employee.obj");

ObjectOutputStream oos = new ObjectOutputStream(objectFileStream);

for(Employee thisEmp: emp)

     oos.writeObject(thisEmp);

 

(3) try( FileOutputStream objectFileStream = new FileOutputStream("Employee.obj");

          ObjectOutputStream oos = new ObjectOutputStream(objectFileStream); ); {

    for(Employee thisEmp: emp)

     oos.writeObject(thisEmp);

    }catch(IOException e){...}

=> try-with-resources


Hybrid 5 - Exception and Exception Handling

1. Try-with-resources

(try-with-resources is not same with try-catch)

Form:

try (declare and instantiate resources) {

   // Use the new resources here

}

// no catch required

 

i.e.

try(FileInputStream fis = new FileInputStream(path);

    ObjectInputStream ois = new ObjectInputStream(fis); ){

    while(true)

        ObjArray.add((ObjType) ois.readObject());

}catch(IOException ex){

        // handle file IO errors here

}

 

It only works with objects that have a close() method declared

 

2. Exception class methods

a) getMessage()

b) toString()

c) printStackTrace()

d) getStackTrace()

 

3. finally

a) (a)error in the try statement or (b)wrong type in the catch statement

-> finally statements executed regardless of which of the two blocks of code get executed

(even when a return statement is encountered prior to reaching finally)

b) catch may be omitted when finally is used

c) may re-thrown inside catch statement

d) Declare exception using throws; required for checked exceptions, Unchecked exceptions do not need to be declared

 



Hybrid 6 - Polymorphism

1. Polymorphism Details

Circle geoObj = new Circle(5);

LHS: geoObj stores an ID value and associated it with an object of type Circle

RHS: reserve a place in memory for the fields and methods associated with an object of type Circle

Circle: a subclass that extends from GeometricObject and Object -> contains the methods and fields of its two parent classes

 

2. Casting

GeometricObject geoObj = new Circle(5);

Possible: Java allows this because it recognizes that a Circle object is a GeometricObject

 

superClassType initializer = new subClassType();    => OK, upcast: to cast upward in the object hierarchy from greater complexity to less complexity

subClassType initializer = new superClassType();    => Problematic, must downcast to avoid problems

(i.e. every Superman(Sub) is a human(Super) but not every human is a Superman)

 

(Primitive type casting difference)

int myInt = (short)2015;    => upcasting OK (smaller data type into larger data type)

short myInt = 20150917;    => downcasting ERROR

기본형에서는 작은 것에서 큰 것으로 끼울 때 문제가 없었지만

객체에서는 작은 것(Super)에서 큰 것(Sub)으로 끼울 때 문제가 생긴다.

 

Not squeezing large data type into a smaller data type

But, about the complexity of the information that can be accessed by a reference value of a particular type

 


Hybrid 7 - CompareTo

<Binary Search of a Sorted ArrayList>

Big O: On the order of, the time take to perform this algorithm increases linearly with the number of items available to search through

 

- Code for binary search Using Array

public static int binarySearch(int key, int[] list){

   int low = 0; high = list.length-1;

   while(high >= low){

      int mid = (low + high)/2;

      if(key < list[mid])

           high = mid - 1;

      else if(key == list[mid])

           return mid;

      else

           low = mid + 1;

   }

   return - 1;

}

 

- Code for binary search Using ArrayList

public static int binarySearch(int key, ArrayList<Integer> list){

   int low = 0; high = list.size()-1;

   while(high >= low){

      int mid = (low + high)/2;

      if(key < list.get(mid))

           high = mid - 1;

      else if(key == list.get(mid))

           return mid;

      else

           low = mid + 1;

   }

   return - 1;

}

 

<T extends Comparable<T>>

= "The class T is guaranteed to implement compareTo()"

 

CompareTo() method is fundamental to the algorithms used for searching and sorting.

Ensure that Comparable or Comparator have been implemented first.

 

 

'What I Learned > Java' 카테고리의 다른 글

Java Final Summary  (0) 2019.04.21
Java Quiz Summary  (0) 2019.04.08