Memory Monitor

Memory Monitor Workflow


To profile and optimize memory use, the typical workflow is to run your app and do the following:

  1. Profile the app using the Memory Monitor to find out whether undesirable garbage collection event patterns might be causing performance problems.
  2. If you see many garbage collection events in a short amount of time, dump the Java heap to identify candidate object types that get or stay allocated unexpectedly or unnecessarily.
  3. Start allocation tracking to determine where any problems are happening in your code.

The Java heap data shows in real-time what types of objects your application has allocated, how many, and their sizes on the heap. Viewing the heap helps you to:

  • Get a sense of how your app allocates and frees memory.
  • Identify memory leaks.

Allocation tracking records app memory allocations and lists all allocations for the profiling cycle, including the call stack, size, and allocating code. It helps you to:

  • Identify where many similar object types, from roughly the same call stack, are allocated and deallocated over a very short period of time.
  • Find the places in your code that may contribute to inefficient memory use.

Resource: https://developer.android.com/studio/profile/am-memory.html?utm_source=udacity&utm_medium=course&utm_campaign=android_basics

 

Array Implementation of Queue (Fixed size)

github:arrayQueue.java

Purpose:

reuse a fixed size array. —-> Tracking 2 variables frontIndex for deletion and rearIndex for insertion.

CheckPoint:

  1. array size > 0.
  2. isEmpty()
  3. Check rearIndex == frontIndex.
  4. Enqueue –> queue is full.
  5. Dequeue –> queue is empty.

Complexity Analysis:

Time complexity :
enqueue: O(1)
assign the value to array[rearIndex]

dequeue: O(1)
move frontIndex to next index.

Space complexity : O(n)

 

The result:

Screen Shot 2017-04-12 at 9.48.43 PM

Exception checking:

Screen Shot 2017-04-12 at 9.56.48 PMScreen Shot 2017-04-12 at 9.57.41 PMScreen Shot 2017-04-12 at 9.58.28 PM

 

Implement Queue using Stacks

github: ImplementQueueusingStacks.java

Using 2 stacks- s1 and s2 to implement a queue.

Purpose: keep the input on the bottom of s1.

The idea is that when an input comes, we push the input to s1, BUT only if the s1 is empty. If s1 is not empty then we pop out all element from s1 and push into s2,
so that we always keep the input on the bottom of s1.

Complexity Analysis:

Time complexity :
PUSH: O(n)
Since we need pop out all elements in s1 and push in that elements in s2 before we push the input in the s1 also pop out s2 and push back s1. so it should be O(n).
POP: O(1)
We only pop out the top of s1. So it is O(1).

Space complexity :
PUSH: O(n). We need n space to store the coming queue elements.
POP: O(1). We only keep one element- the top of s1 which pop out from s1. So it is O(1).

void push(int x):
check
a while loop , if s1 is not empty,
pop all elements in the s1 and also push the elements to s2
so s2 contains the reverse of s1.

then push x to s1

a while loop, if s2 is not empty,
pop all elements in the s2 and also push the elements to s1

assign x to the integer-front

int pop():
assign the element from pop s1 to x
assign s1.peek() to the integer-front
return x.

int peek():
return front.

boolean empty():
return s1.empty();

Palindrome Checker

Screen Shot 2017-03-26 at 10.53.54 PM

github: Palindrome.java

A few good ways to remove space from a string.

Method 1

private static String removeSpace(String aword) {
     StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < aword.length(); i++)   {
         if (aword.charAt(i) != ' ')) {
             buffer.append(aword.charAt(i));
         }
     }
     return buffer.toString();
}

Method 2

        //Removing all white spaces from s1 and s2
        String copyOfs1 = s1.replaceAll("\\s", "");
        String copyOfs2 = s2.replaceAll("\\s", "");

Java – Encapsulation

 

Class

  1. Property and Method
  2. Class member: Field member, and Method member.
  3. public, private and protected.

We call public member, meaning we can directly call Class Members by ‘ . ‘ . On the other hand, we cannot directly call private member by ‘ . ‘ .

 Constructor

  1. Overloading Methods

The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled “Interfaces and Inheritance”).

Suppose that you have a class that can use calligraphy to draw various types of data (strings, integers, and so on) and that contains a method for drawing each data type. It is cumbersome to use a new name for each method—for example, drawString, drawInteger, drawFloat, and so on. In the Java programming language, you can use the same name for all the drawing methods but pass a different argument list to each method. Thus, the data drawing class might declare four methods named draw, each of which has a different parameter list.

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) {
        ...
    }
}

Overloaded methods are differentiated by the number and the type of the arguments passed into the method. In the code sample, draw(String s) and draw(int i) are distinct and unique methods because they require different argument types.

You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.

The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.


Note: Overloaded methods should be used sparingly, as they can make code much less readable.

2. this

IMG_20170328_150844.jpg

OOP concepts

Four fundamental OOP concepts:

1. Inheritance

Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance the information is made manageable in a hierarchical order.

The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).

Overriding

In the previous chapter, we talked about superclasses and subclasses. If a class inherits a method from its superclass, then there is a chance to override the method provided that it is not marked final.

The benefit of overriding is: ability to define a behavior that’s specific to the subclass type, which means a subclass can implement a parent class method based on its requirement.

In object-oriented terms, overriding means to override the functionality of an existing method.

2. Polymorphism

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.

It is important to know that the only possible way to access an object is through a reference variable. A reference variable can be of only one type. Once declared, the type of a reference variable cannot be changed.

The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object.

A reference variable can refer to any object of its declared type or any subtype of its declared type. A reference variable can be declared as a class or interface type.

3. Abstraction

As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of e-mail, complex details such as what happens as soon as you send an e-mail, the protocol your e-mail server uses are hidden from the user. Therefore, to send an e-mail you just need to type the content, mention the address of the receiver, and click send.

Likewise in Object-oriented programming, abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information on what the object does instead of how it does it.

In Java, abstraction is achieved using Abstract classes and interfaces.

Abstract Class

A class which contains the abstract keyword in its declaration is known as abstract class.

  • Abstract classes may or may not contain abstract methods, i.e., methods without body ( public void get(); )
  • But, if a class has at least one abstract method, then the class must be declared abstract.
  • If a class is declared abstract, it cannot be instantiated.
  • To use an abstract class, you have to inherit it from another class, provide implementations to the abstract methods in it.
  • If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.

Interface

An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.

Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods.

Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.

An interface is similar to a class in the following ways −

  • An interface can contain any number of methods.
  • An interface is written in a file with a .java extension, with the name of the interface matching the name of the file.
  • The byte code of an interface appears in a .class file.
  • Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name.

However, an interface is different from a class in several ways, including −

  • You cannot instantiate an interface.
  • An interface does not contain any constructors.
  • All of the methods in an interface are abstract.
  • An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.
  • An interface is not extended by a class; it is implemented by a class.
  • An interface can extend multiple interfaces.

4. Encapsulation

in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.

To achieve encapsulation in Java −

  • Declare the variables of a class as private.
  • Provide public setter and getter methods to modify and view the variables values.

Packages

Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.

A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations ) providing access protection and namespace management.

Some of the existing packages in Java are −

  • java.lang − bundles the fundamental classes
  • java.io − classes for input , output functions are bundled in this package

Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a good practice to group related classes implemented by you so that a programmer can easily determine that the classes, interfaces, enumerations, and annotations are related.

Since the package creates a new namespace there won’t be any name conflicts with names in other packages. Using packages, it is easier to provide access control and it is also easier to locate the related classes.

The import Keyword

If a class wants to use another class in the same package, the package name need not be used. Classes in the same package find each other without any special syntax.

Note − A class file can contain any number of import statements. The import statements must appear after the package statement and before the class declaration.