Exceptions

Introduction

  • An exception represents an error condition that can occur during the normal course of program execution.
  • When an exception occurs, it is said to be thrown. When it is thrown, the normal flow of the program terminates and the exception handling block will be executed.
  • The execution handling block is the catch block. This block will be contain instruction on what to do when an exception is caught. Caught means that when an exception is thrown, the exception handling block will catch the exception thrown.

Methods to use with Exceptions

The following methods will be used to get more information about the thrown exception.

printStackTrace()
getMessage()

throws clause

The throws keyword is used to throw an exception similar to a try & catch block.

How to throw multiple exceptions?

You can use a comma between each exception when declaring them.

Difference between throw & throws

  1. You can throw only one exception at a time while you can handle multiple exemptions using a throws clause.
  2. throw is present in the method body where it will throw an error while the throws is used in the method signature and declares any exceptions that may occur during the execution of the statement in the method body.

finally block

  • The finally block is part of the try catch block where the statements or instruction in the finally block will execute regardless of whether an exception is handled/thrown or not
  • Java finally block is a block that is used to execute important code such as closing connection, stream etc.
  • The finally block follows the try &b catch block.

Layman’s Terms

An exception is like an error that occurs while playing a video game. When that error occurs, the game usually crashes and shuts down. What is happening there? When it crashes, an exception is thrown which can be missing files, bugs or anything. The catch block would either give the player instruction of what to do to fix the error, like missing file or something, or restart the game to fix the error.

References

https://www.javatpoint.com/exception-handling-in-java

Multithreading in Java

What is a thread?

It is a unit of a process.

Example:
Let use take a scenario where multiplying an array of a thousand numbers with 2. If each operation takes 1 second, it would take a 1000 seconds to complete the whole task.

With the help of threads, we can cut the time significantly. Threads allow a program to be run concurrently working on different process at the same time. This concept is called Multithreading.

How to create a thread and perform multithreading?

  1. Create a class that specifies the task that must be accomplished
  2. Everything has the method called run and run is responsible for the task that must be accomplished.
  3. To use a thread, the class must extend thread
  4. Then make an instance of the thread by declaring the following
    1. Thread threadObject = new ThreadClassName();
    2. threadObject.run();
      1. run() will execute one thread
  5. start() will automatically call the run method and achieve parallel processing or multithreading.

Why use the runnable interface?

Runnable does the same as the thread class but using an interface, another class can be extended which is not possible when extending the thread class. This is due to the fact that java doesn’t allow extension of more than one class.

Interview Questions Part 2

Whats a status code?

A status code is a part of the result of an http request that contains a 3-digit integer where the first digit of the Status-Code defines the class of response and the last two digits do not have any categorization role.

Why String class is immutable in Java?[Good]

String class is immutable because Java stores only a single copy of the string in a string pool in a special region in the JVM so memory is conserved. It does so to provide the following benefits: caching, security & synchronization.

Immutable: An immutable object is an object whose internal state remains constant after it has been entirely created

Caching – Only a single copy of the string is stored in a string pool in a special region in the JVM so memory is conserved. This process is called interning

Security – It is easier to work with immutable object when sensitive information is passed. Avoids SQL injection.

Synchronization – Immutable objects can be accessed by multiple threads since the value of the string doesn’t really change hence strings are thread-safe.

What is the difference between method overriding and method overloading?

Method overriding occurs when a method is inherited from a parent class but the programmer changes its behavior to something else
Method overloading occurs when two methods with the same name but different parameters in the same class perform different operations.

What is the difference between a Hashmap and Hashtable?

  1. HashMap is non synchronized. It is not-thread safe and can’t be shared between many threads without proper synchronization code whereas Hashtable is synchronized. It is thread-safe and can be shared with many threads.
  2. HashMap allows one null key and multiple null values whereas Hashtable doesn’t allow any null key or value.
  3. HashMap is generally preferred over HashTable if thread synchronization is not needed

Interview Questions Part 1

Can you give me an example of method overriding?

  • Method overriding occurs when a method is inherited from a parent class but the programmer changes its behavior to something else.
  • An animal class has the method eat(). A dog class extending the animal class and will inherit the method eat(). But the dog however will change how it eats hence changing the behavior and overriding the eat() method.

How do you connect to a database using spring boot? [Good]

  1. Create a database with a username and password
  2. Insert tables and values into the database
  3. Create an application.yml file
  4. In the yml file, specify the url, username and password
  5. Your database is connected!!!! Yahooo!!!!!

How do you create a Rest API using spring boot?

  1. Create a Maven project and enter your GroupId and ArtifactId to reflect your project
  2. In the POM.xml file, create a parent and any other dependencies that you might need for your project
  3. Create a Model to represent your data [JPA]
  4. Create a REST controller to delegate http requests
  5. Create a service to provide any business logic.
  6. Create a repository marker interface which extends the jpaRepository to get access to methods to interact with the database
  7. Create a security config if you need it (Optional)

How to create a custom exception?

  1. You need to extend a the exception class
  2. If you need a runtime exception, then extend the RuntimeException

Service Module

  • Used for duplication of code
    • The same code can be used in multiple components
  • Providing data
    • If certain data in a component needs to be accessed
  • Should NOT create services manually.  By that I mean, do not import and create instances of the service to use it. Why?
  • Angular’s Dependency Injector (Hierarchical Injector)
    • Used to inject the instance of a class to a component automatically
    • Remember, when you provide a service to a certain component, that component and all its children will receive the same instance of that service.
    • How to tell the component that you need that class?
      • Import the service
      • Create the constructor to tell angular what we what. But how?
        • constructor(private anyName: ClassName){}
      • Provide the service. How?
        • Add a providers array in the @Component located at the top of any component
      • Then access the method you created.
      • Why is it better to use Angular’s Dependency Injector.
        • It does it automatically
        • Let’s you stay in the Angular ecosystem.

How to inject a service into another service?

  • add a constructor with the service you want to inject as a parameter
    • constructor(private anyName: ClassName){}
  • Use the methods of the service class
  • @Injectable – add it to the service where you injecting the service. The service which will receive the service should have the annotation, injectable.

Routing

  • Steps to create a route
    • Import Routes into app.module.ts
      • Import { Routes } from ‘@angular/router”;
    • Create a constant of type Routes in to the app.module.ts
      • const appRoutes: Routes = [];
      • Insert an array of your routes
      • { path: ‘name’, component: ComponentName }
      • Path – What path do you want to route to?
      • Component – defines which component gets loaded/ the page that gets loaded
  • To register a router you created,
    • add RouterModule.forRoot(CONSTANT_NAME_OF_ROUTES) to the imports[] array in the app.module.ts
  • Where to insert the routes
    • In your app.component.html, you have add a special directive called <router-outlet>
  • How should you implement the Navigation bar in Angular?
    • Use the special directive called routerLink = “/”
    • Array structure – [routerLink] = [‘/something’, ‘something’]
    • Using property binding
  • Navigating Programmatically
    • In a component, add the constructor for Router
      • Syntax: constructor(private router: Router){}
      • Create a method
        • Use navigate method from Router
        • Syntax: this.router.navigate([‘/mappingName’])
      • Navigate method
        • The navigate method doesn’t do relative path
          • Use ActivatedRoute to get the relative path
          • Add it to the constructor
          • Syntax: this.router.navigate([‘mapping’], {relativeTo: this. Route});
  • Fetching Route Parameters
    • Parameters can be set in the path of a certain component
      • { path: ‘name/:parameter1/:parameter2’, component: ComponentName }
      • In a ngOnInit, you can have access that have been defined in the route path
      • Syntax: parameterName: this.route.snapshot.params[‘parameterName’]
      • Angular will only initialize its component once so any new changes in the current component will not reflect to the page. How to solve it?
        • Use the route .params.subscribe() method
        • Then assign each of them to the params

Databinding in Angular

Definition

  • Databinding = communication
  • Communication between the TypeScript code of your
    • component,
    • business logic &
    • template
  • Using databinding you can
    • output data
    • respond to the user by event biding
    • two-way databinding (respond as well as out output data)

String Interpolation

  • Any expression that returns a string
  • Example: {{property}}

Property binding

  • [] indicate a property is being bound
  • Example:

[disabled]

= “propertyName (has to be a TypeScript expression)

  • Can bind to all the HTML properties

String Interpolation vs Property binding

  • If you want to print out an output to the webpage, use string interpolation.
  • If you want to change the property of an attribute, use property binding.

Event Binding

  • Binding a function to a event that will occur when a user interacts with the webpage
  • (Event_Name) = “Method to be used“

Two-way Binding

  • It is the way to change the input as well as output data at the same time
  • Example: [(ngModel)] = “property”

Directives

ngIf

  • Use * to represent that it is a structural directive. A structural directive is a directive that changes the structure of the angular project
  • Example: <p*ngIf = “property that returns true/false”> whatever text </p>
  • Else
    • Or use ngIf with a reverse alternative
      • Example: <p*ngIf = “!property that returns true/false”> …. </p>
    • Create a ng-template
      • <ng-template #any_name>  HTML code <ng-template>
      • Example: <p*ngIf = “property that returns true/false”; else any_name> whatever text </p>

ngStyle

  • Use [] on the directive in order to configure using property binding
  • Pass a JavaScript object to configure ngStyle
  • Example: <p [ngStyle] = “{JavaScript syntax: methodName()}”> …. </p>

ngClass

  • Allows dynamic use of CSS classes
  • Use [] on the directive in order to configure using property binding
  • Example: <p [ngClass] = “Class_Name: some condition”
  • ngClass will only add that class if a certain statement is true

ngFor

  • It is used as a loop
  • Example: <p *ngFor = “let anyName of array_from_component; let i = index”> …. </p>
    • Let any variable read from an array defined in the component class

Debugging

  • Using the console
  • Error in your logic
    • Go to sources
    • TypeScript can be found in the webpack
    • The browser cannot read TypeScript so it transforms it into JavaScript
    • Place breakpoints where the error could be
    • Run the code and see how the values change to find the error
  • Augury

Layout of the Project

  • App
    • app.module.ts
      • It is a TypeScript file. There is where we tell Angular which pieces belong to our app.
      • Declarations
        • all the components are declared here
      • Imports
      • Provides
      • Bootstrap
        • tells angular which components should be recognized by angular
    • app.component.ts

Building an Angular Project

Commands to create an Angular projec

  • sudo install -g @angular/cli
    • Installs the command line interface for angular
  • ng new application_name
    • Creates an angular project with the template of the project built in

How does an Angular App load and start

  1. Main is the first code that gets executed
  2. Check the imports
  3. The line platformBrowserDynamic().bootstrapModule(AppModule) refers to the AppModule
  4. In the app.module.ts, the bootstrap array lists all the components that should be known by angular at the time of start of the application. So it reads the AppComponent.
  5. Then, Angular looks at the app.component.ts and sees the selector app-root.
  6. The app-root in the index.html file is where the AppComponent is inserted into.

Component

            Component is simply a TypeScript class so that angular can instantiate it to create objects based in the blueprint that is set up.

  • Component contains
    • Template
    • HTML
    • Styling
    • Business Logic
  • Components allow to split a complex webpage into reusable parts
  • All the other component selectors will be added to the app.component.html file rather than the index.html
  • Components are reusable

Creating a new component

  • Manual
    • Naming Convention
      • Component_Name.component.ts
    • Create a class
    • Add a @Component({}) decorator
      • Parameters inside the component
        • selector
          • selector name to be used to point to this component
          • ways to write a selector
            • ‘app-component’ – Element
            • [app-component] – attribute
            • ‘.app-component’ – class
        • templateURL
          • HTML file location.
          • Back ticks (`) can be used to write HTML code inside the TypeScript file.
        • styleUrls
          • location of the stylesheets
          • it is an array so multiple stylesheets can be referenced
          • Back ticks (`) can be used to write HTML code inside the TypeScript file.
    • Register a new component in the declarations array in the app.module.ts
    • Use the new component inside the root component HTML file
  • CLI command for creating a component
    • ng generate component / ng g c component_name
    • CLI automatically adds all the imports

Selectors in Components

  • selector name to be used to point to this component
  • ways to write a selector
    • <app-component>
    • [app-component] – attribute
    • ‘.app-component’ – class

Nesting Components

            Components can be nested by placing the selector of a component inside another one.

Angular Introduction

  • Has a component-based structure
    • Ease of reuse
    • Ability of modularity
  • Allows you to create a Single Page Applications
  • Uses TypeScript which uses strong typing.
    • Benefits of typescript
      • Simplicity
      • Angular Source code (Pattern of writing code)

Components in Angular

  • A component in Angular is used to render a portion of HTML and provide functionality to that portion. It does it from a component class in which the programmer can define the application logic of the component.

Directives

  • Directives provide functionality and can transform the DOM.
    • Types of directives
      • Structural
        • Modify layout by altering the elements in the DOM
      • Attribute
        • Change the behavior or appearance of a existing DOM element
  • How to apply a directive?
    • Writing an attribute on an element
      • <div selectorName>
      • <div [selectorName = “true]
  • Directives in Angular
    • ngIf
    • ngFor
    • routerLink

Pipes

  • A pipe takes in data, like a string or an array and runs some logic to transform it to a new output.
  • Common pipes
    • Date
    • Uppercase
    • Lowercase
  • Pipes are a great way to change the data in a reusable way.

Data Binding

  • Interpolation
    • Interpolation is the most common way of displaying data in view template where a set of curly braces around a component property to tell angular to render the content of that property.

Dependency Injection

  • Allows the ability to write decoupled code
    • This means that modules do not depend on each other to work
  • In essence, you can create these modular component and services and simply tell angular what and where you want to use them.
    • It will handle making instances of those components and services and send the code where it is needed.

Services and other Business Logic in Angular

  • A JavaScript fie of function that is written to contain some sort of logic can be considered as a service of an application.
  • They are just plain old JavaScript logic code.
  • The framework is designed to any JavaScript code.
    • This allows the programmer to write modular & decoupled code.

Data Persistence

  • In-Memory Data Store
    • If the data only needs to exist for the time period that the user uses the program for
    • How to do so?
      • Create a JavaScript object to store the data
      • Provide it to the app
      • Do constructor injection wherever needed.
  • Data Stored in Browser/Local storage
    • The programmer would need to write their own JavaScript service code and leveraging angular’s dependency injection to work with the application
  • Data Store service using an API
    • Using the http protocol
    • JSONP
      • Make get and post calls

Routing

  • You want to handle the URL requests in the client, adjusting the UI and displaying the data accordingly.
  • It provides a way to load different components through a set of configuration instructions and links

Decorator

  • An expression that evaluates to a function allowing annotation of classes at design time
  • @DecoratorName()
  • ngModel      à Syntax: [(ngModel)] = “anyName”
    • Angular will store anything that will be entered into anyName.

Spring Data JPA

It is one of the projects from the spring.io/projects. It reduces writing a lot of the boilerplate code.

What does it do?

  1. Creates a DAO (Data Access object). DAO is a design pattern.
    A DAO is an object that provides an abstract interface to some type of database. By mapping application calls to the persistence layer (a group of files that are used to communicate between the application and the Database), DAOs provide some specific data operations without exposing details of the database.
    This isolation supports the Single responsibility principle. It separates what data accesses the application needs, in terms of domain-specific objects and data types (the public interface of the DAO), and how these needs can be satisfied with a specific DBMS, database schema, etc. (the implementation of the DAO).
  2. From that, Spring will give you CRUD implementation for free hence reduces the DAO code to write.
The entity can be replaced with any other entity and it will work the same. This eliminates the creation of a new DAO every time a new a entity needs to be used

JpaRepository

Development Process

  1. Extend jpaRepository
  2. Use your Repository in your application
  3. Now you have access to all the methods form the jpaRepository

import org.springframework.data.jpa.repository.JpaRepository;

public interface PersonRepository extends JpaRepository<PersonModel,Long>{

//no need to write anymore code and all the methods are inherited


}

References

https://www.kelltontech.com/kellton-tech-blog/spring-and-data-access-object-dao-part-1
Check out the full list of available at the java doc for JpaRepository
Udemy: Spring 5 by Chad Derby: https://www.udemy.com/share/1000qYBUcTdFlVRno=/

Spring YAML Configuration

YAML is used for configuring different profiles for a simple Spring Boot application.

Spring YML file

  • Spring profiles help enable Spring Applications to define different properties for different environments.
  • The three dashes separating the two profiles indicate the start of a new document so all the profiles can be described in the same YAML file.

Binding YAML to a Config Class

To load a set of related properties from a properties file, we will create a bean class:

  • @Configuration marks the class as a source of bean definitions
  • @ConfigurationProperties binds and validates the external configurations to a configuration class
  • @EnableConfigurationProperties this annotation is used to enable @ConfigurationProperties annotated beans in the Spring application

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties

public class YAMLConfig
{
privateString name;
privateString environment;
privateList<String> servers = newArrayList<>();

// standard getters and setters

}

Accessing the YAML Properties

  • You can use get and set methods defined in the binding process.
  • Using the get method, you can display the properties
  • Using the set method, you can set values for the properties.

References

Design a site like this with WordPress.com
Get started