Java Basics: Exceptions

When I started programming, I would get nervous seeing exceptions and errors pop up in my code, but now that I better understand Java I can write these exceptions myself!

What happens in Java is that when an exception occurs, or is thrown, the program’s normal pace is terminated and it instead marks the exception as being “caught” before entering an exception-handling routine.

You’ve been caught!

There are two kinds of exceptions: checked and unchecked exceptions. Checked exceptions are caught during compile-time when JDK’s compiler first runs through your code. Unchecked exceptions go undiscovered until run-time, which is why they are unchecked.

Specifying exceptions in your code is important because:

  • It more easily specifies what went wrong than the default checked exception print statements.
  • It helps you improve your bug-tracking skills.
  • It helps during testing phase when you run it.

There are 2-3 blocks that can make up a try-catch statement: try, catch, and finally. Try is which operation the exception-handling routine surrounds, remaining content skipped once an exception is found. Catch is the chosen exception. Finally is not always used, but can be used to take ending action regardless of exceptions to ensure certain code is run at the end, such as closing an open data stream.

try {
	. . .
} catch (InputMismatchException e){
	. . . 
} catch (ArrayIndexOutOfBoundsException e){
	. . . 
} 
finally {
	objScanner.close();
}

There are different exceptions and multiple can be included by a try-block. You can even make your own! Remember though: only one is chosen. Seek out my code and you can read all about it!

Follow my original code on my GitHub profile!

Angular Interview Questions

I will be making a list of intermediate to advanced interview questions, then listing their answers here.

  1. What is Angular?
  2. Why use Angular?
  3. What is Angular used for?
  4. What are Angular components?
  5. What are Angular expressions?
  6. What are Angular templates?
  7. What are Angular directives?
  8. In Angular, what is string interpolation?
  9. In Angular, what’s different between Annotations and Decorators?
  10. What is Scope in Angular?
  11. What is data binding in Angular?
  12. Why have a filter in Angular?

Here are my answers!

  1. Angular is an open-source front-end web framework that provides a platform for easy development of web-based single page applications (SPAs) and empowers developers in curating cross-platform applications. It integrates features like declarative templates, dependency injection and various other best practices that streamlines the development path.
  2. There are numerous benefits to using Angular:
    • It supports two-way data-binding
    • It follows MVC pattern architecture
    • It supports static template and Angular template
    • You can add a custom directive
    • It also supports RESTful services
    • Validations are supported
    • Client and server communication is facilitated
    • Support for dependency injection
    • Has features like Event Handlers, Animation, etc.
  3. Angular is typically used for the development of SPA which stands for Single Page Applications. Angular provides a set of ready-to-use modules that simplify the development of single page applications. Not only this, with features like built-in data streaming, type safety, and a modular CLI, Angular is regarded as a full-fledged web framework.
  4. Components are building block in an Angular application. Components are defined using the @component decorator. A component has a selector, template, style and other properties, using which it specifies the metadata required to process the component.
  5. Angular expressions are code snippets that are usually placed in binding such as Syntax: {{ expression }} similar to JavaScript. These expressions are used to bind application data to HTML.
  6. Angular templates are written with HTML that contains Angular-specific elements and attributes. These templates are combined with information coming from the model and controller which are further rendered to provide the dynamic view to the user.
  7. Angular directives are a core feature of Angular, attributes that allow you to write new HTML syntax, specific to your application. They are essentially functions that execute when the Angular compiler finds them in the DOM.  The Angular directives are segregated into 3 parts: Component Directives, Structural Directives, and Attribute Directives.
  8. String interpolation in Angular is a special syntax that uses template expressions within double curly {{ }} braces for displaying the component data. It is also known as moustache syntax. The JavaScript expressions are included within the curly braces to be executed by Angular and the relative output is then embedded into the HTML code. These expressions are usually updated and registered like watches, as a part of the digest cycle.
  9. Annotations in angular are “only” metadata set of the class using the Reflect Metadata library. They are used to create an “annotation” array. On the other hand, decorators are the design patterns that are used for separating decoration or modification of a class without actually altering the original source code.
  10. Scope in Angular is an object that refers to the application model. It is an execution context for expressions. Scopes are arranged in a hierarchical structure which mimics the DOM structure of the application. Scopes can watch expressions and propagate events.
  11. In Angular, data binding is one of the most powerful and important features that allow you to define the communication between the component and DOM(Document Object Model). It basically simplifies the process of defining interactive applications without having to worry about pushing and pulling data between your view or template and component. In Angular, there are four forms of data binding:
    • String Interpolation
    • Property Binding
    • Event Binding
    • Two-Way Data Binding
  12. Filters in Angular are used for formatting the value of an expression in order to display it to the user. These filters can be added to the templates, directives, controllers or services. Not just this, you can create your own custom filters. Using them, you can easily organize data in such a way that the data is displayed only if it fulfills certain criteria. Filters are added to the expressions by using the pipe character |, followed by a filter.

Spring Boot Interview Questions

I will be making a list of intermediate to advanced interview questions, then listing their answers here.

  1. What is the difference between Spring and Spring Boot?
  2. How would you connect a database to Spring Boot?
  3. How do we persist/retrieve data with Spring Boot?

Here are my answers!

  1. Spring Framework is a great place to build all sorts of applications, but to build them rapidly as production-ready applications requires Spring Boot. Spring requires numerous configurations and other choices to be made during the app development process, but Spring Boot makes it much quicker with its autoconfiguration setting default choices for these config options. Along with other fundamental principles such as inversion of control, the user is able to speedily create needed apps with little effort!
  2. Create a database with a username and password, insert tables and values into your database, then create your application.yml file. In this file, specify your database’s URL, username, and password.
  3. We add JPA 2 and Hibernate to our project. Add required annotated entity we want persisted and add an id. Create a repository, then finally create a service class to use the repository.
Spring Boot is an enhanced version of Spring itself for rapid creation.

MySQL 202 Interview Questions

I will be making a list of intermediate to advanced interview questions, then listing their answers here.

  1. Explain the difference between Mongo vs MySQL.
  2. What’s the difference between noSql vs SQL?
  3. What is a stored procedure?
  4. In the context of SQL, what’s Function?
  5. Function vs Stored Procedure?
  6. How do you configure a database using JDBC?
  7. What are transactions in SQL?
  8. What is the difference between “PreparedStatement” and Statement in JDBC?
  9. How do you create a prepared statement in MySQL?
  10. What is normalization?

Here are my answers!

  1. MySQL is a relational database language that stores data within a defined table structure. Mongo is a NoSQL type language that is non-relational and stores data in JSON-esque documents that can vary in structure. It’s simple to add new attributes to an entity in Mongo, but can be costly and difficult to redefine in MySQL.
  2. NoSQL is a non-relational database while SQL is a relational database. NoSQL are document based, key-value pairs graph databases, or wide-column stores. SQL are databases that are table based.
  3. A stored procedure like a function that can save and run multiple SQL statements for later use. It can also take in multiple parameters.
  4. A function can run multiple SQL statements like a procedure and can take in parameters, but it returns a value directly unlike a procedure.
  5. A stored procedure can run multiple statements in a block. It is a type of function that can take in parameters, but unlike functions, does not return a value. The only way to get a return value, is to use the out or inout parameters.
  6. Add the SQL connection JAR to your program’s class path. Load and register the JDBC driver and connect to the database using the DriverManager class. Pass in the URL, USERNAME, and PASSWORD to access your database. Run through the process of executing a query in a java program.
    1. Establish a connection to the database and get the Connection.
    2. Create a Statement using the Connection.
    3. Execute the Statement with an SQL string.
    4. Get the ResultSet back from the executed Statement and use them to display the results.
  7. A transaction is a sequence of operations performed using at least one SQL statement. Transactions can be committed to a database or rolled back (undone) from the database.
  8. A Statement already has the entirety of the query written out and can be executed right away, while a PreparedStatement only has some of the query written out. A PreparedStatement is parameterized and you can pass parameters at runtime.
  9. First initialize the PreparedStatement like below where conn is the Connection to your database.
    1. PreparedStatement pstmt = conn.prepareStatement(“select * from ACTOR where actor_id = ?”);
    2. After, you can set the parameters for the statement, since actor_id is of type int and it is the first, so its place is at 1.
    3. pstmt.setInt(1, 12);
    4. Above we set the first parameter (actor_id) as 12. If The parameter was some sort of string, there is a setString() function and others for more types. After, all you need to do is to execute the query.
    5. pstmt.executeQuery();
  10. Normalization is a way of structuring your data/tables so you avoid repetitive data, insert anomalies, delete anomalies, and update anomalies.

Java 202 Interview Questions

I will be making a list of intermediate to advanced interview questions, then listing their answers here.

  1. What are Java streams and how would you use them?
  2. What are lambda functions and when would you use them?
  3. What’s an example of how to use lambda functions with a stream method?
  4. What are the different types of exceptions?
  5. How would you handle an exception?

Here are my answers!

  1. Java provides a new additional package in Java 8 called java.util.stream which consists of classes, interfaces and enum to allows functional-style operations on the elements. You can use stream by importing java.util.stream package. The best feature about streams is how they focus on declarative programming, not focusing on the coding process as much as the objective. Watch the video at the bottom of this post for an in-depth explanation of how Java 8 streams work.
  2. Also introduced in Java 8, lambda expressions express instances of functional interfaces (An interface with a single abstract method is called functional interface. An example is java.lang.Runnable). Lambda expressions implement the only abstract function and therefore implement functional interfaces. Lambda expressions are added in Java 8 and provide the following functionalities: able to treat functionality as a method argument, or code as data, functions that can be created without belonging to any class, and a lambda expression can be passed around as if it was an object and executed on demand. Read the code segment at the bottom of this post for an explanation of how Java 8 lambda expressions work.
  3. [will continue]
  4. Checked exceptions are checked at compile-time in Java. It means if a method is throwing a checked exception then it should handle the exception using try-catch block or it should declare the exception using throws keyword, otherwise the program will give a compilation error. It is named as checked exception because these exceptions are checked at compile-time. All Unchecked exceptions are direct subclasses of RuntimeException class. Unchecked exceptions are not checked at compile-time. Most of the times these exception occurs due to the bad data provided by user during the user-program interaction. It is up to the programmer to judge the conditions in advance, that can cause such exceptions and handle them appropriately.
  5. An exception caused by a method can be propagated to the method caller by the “throws” keyword, or can be handled within the method with a try/catch block.
Amigoscode does a great job teaching about Java Streams in this video.

Java Intermediate: ArrayList

Today we’ll be examining ArrayLists. I had once covered arrays, but ArrayLists are different. ArrayLists unlike Arrays are resize-able after creation, making them dynamic and able to adapt to unknown and unexpected size ranges.

What exactly are ArrayLists though and what do they look like? ArrayLists are part of the Java Collection framework. The java.util package contains all the classes and interfaces for the Collection framework, making collection types outside of the standard built-in array easy to find or keep track of for import.

I will be creating code to demonstrate usage of an ArrayList and what you can do with one with the example of a list of test grades.

ArrayList<Integer> grades = new ArrayList<Integer>(); // create ArrayList named grades that stores integers

First we create our ArrayList. A new ArrayList Object, we name it grades for its imminent purpose.

grades.add(100); // add element to ArrayList
grades.set(0, 0);
grades.remove(0);
grades.clear();
grades.size

We may use all sorts of different ArrayList Methods.

  • add – add element to ArrayList
  • set – adjust element of ArrayList; first 0 is index, second is integer value, String, or whichever immutable form you choose for your ArrayList
  • remove – remove index-specified element from ArrayList
  • clear – remove all elements from ArrayList
  • size – display current size of ArrayList

Let’s make this program more substantial, adding additional methods from import to use and really flesh out our program.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

public class Array_List {
    public static void main(String[] args) {
...
Random randNo = new Random(); // declare/establish java.util.Random object
grades.add(randNo.nextInt(40) + 60);

We import ArrayList as needed, Random class for randomization, and Collections to call sort() method to sort our numerical data.

int group_size = 1;
do {
      grades.add(randNo.nextInt(40) + 60);
      group_size++;
} while (group_size < 19);

Rather than entering in the ArrayList’s add() method 19 more times, let’s make a do-while loop that iterates until it populates additional grades for 20 total grades. Big class! Notice the 40 and 60. This tells my Random class Object randNo to generate a number between 1 and 40, add 60 to it, then give the sum as an object to the ArrayList. Finally, we sort it, then print it.

Collections.sort(grades);
for (int iterator : grades)
{
      System.out.print(iterator + " ");
}

We create a for-each loop to iterate throughout size of our ArrayList. Rather than use a standard for loop to declare and initialize loop iterator variable, we instead declare a variable of same type as base type of array/ArrayList, followed by a colon, which is then followed by our ArrayList name. Is more commonly used with Collections class ArrayList than array, minimizing chance of OutOfBounds exceptions.

Demonstration of ArrayLists

I hope that you found this content informative, both blog and video! Please check out the full code as depicted on YouTube on my Github account.

Tip: How to Package/Run Spring Boot Maven App as a JAR

Working with the Spring Tool Suite IDE (Integrated Development Environment) over time has taught me much, particularly about using Maven projects. While Gradle is an alternative, I have yet to use it and have been mainly using Maven because of the convenience of its POM.xml file to inject dependencies into my project and mass import dozens of needed .jar (Java Archive) files using only a few lines.

I will be using Windows OS for this guide. After writing up a Maven project in STS (Spring Tool Suite) and successfully running it in Spring Boot, it’s time to build it as a executable JAR! Bundle it up and wrap a pretty bow on it for others’ use.

  1. Ensure Maven is manually installed, not only for use within STS.
  2. Establish the JAVA_HOME Environment Variable if you hadn’t yet done so, pointing to your JDK. Powershell requires a compiler to build your JAR.
  3. Edit Path Environment Variable to add apache-maven-[version]\bin to ensure Powershell can access it.
  4. Open up Powershell. Navigate to whichever workspace folder your targeted STS project folder is stored in, then enter the following commands one by one and it will build your project!
  • cd C:\Java_Workspace\course-api-data
  • mvn -version
  • mvn clean install

I hope that this guide has proven helpful. It took me too long to be able to do this, but you can now do it easily! Thanks for reading.

Java Basics: Polymorphism

I had previously covered one of the four fundamentals of Java programming: Abstraction. Today I am going to cover Polymorphism, based on Greek words “poly” and “morph” compounded into “many forms” from translation.

No not Polymerization, Polymorphism!

One of my favorite hobbies personally is cooking so I’ll be using that as an example, along with code snippets of course! Don’t forget to rinse your vegetables before dicing them.

class PanFry {
    public void panFry() {
        System.out.println("1: Begin heating a clean frying pan to medium heat.");
        System.out.println("2: Lubricate pan.");
        System.out.println("3: Season with salt, pepper, and fry until brown, occasionally moving about using spatula or wooden spoon.");
        System.out.println("4: Turn off pan heat, take pan off heat, wait until pan stops emitting hot steam, finally serve and enjoy!");
    }
}

First we create our main class, PanFry. Its method panFry() will instruct on how to pan fry successfully. Notice how step 2 seems a bit vague? Let’s try to pan-fry both broccoli and a diced onion.

class Broccoli extends PanFry {
    public void panFry() {
        System.out.println("1: Begin heating a clean frying pan to medium heat.");
        System.out.println("2: Lubricate pan with olive oil.  Add broccoli, drizzling a bit extra on top five minutes in.");
        System.out.println("3: Season with salt, pepper, and fry until brown, occasionally moving about using spatula or wooden spoon.");
        System.out.println("4: Turn off pan heat, take pan off heat, wait until pan stops emitting hot steam, finally serve and enjoy!");
    }
}

class Onion extends PanFry {
    public void panFry() {
        System.out.println("1: Begin heating a clean frying pan to medium heat.");
        System.out.println("2: Lubricate pan with butter, melting fully in pan before adding diced onion.");
        System.out.println("3: Season with salt, pepper, and fry until brown, occasionally moving about using spatula or wooden spoon.");
        System.out.println("4: Turn off pan heat, take pan off heat, wait until pan stops emitting hot steam, finally serve and enjoy!");
    }
}

Oh! But what’s this? The method originally drawn from the extended PanFry class diverges in both subclasses? This is what we call overriding, translating the same method to multiple different forms. Using olive oil to pan-fry diced onion is gross, so we prefer to use butter for this vegetable. Step 2 is different in both subclasses, an example of overriding i.e. overwriting the original method’s behavior. Behaving differently is polymorphism.

Another example of polymorphism could be overloading if our method had parameters. Overloading changes the method’s structure changes its parameters. If the panFry() method had an Integer parameter, using it in an extended subclass with an additional String parameter is overloading.

class Kitchen {
    public static void main (String[] args) {
        PanFry sideDish = new Broccoli();
        PanFry steakTopping = new Onion();

        sideDish.panFry();
        steakTopping.panFry();
    }
}

Using our kitchen, we create new objects from our extended subclasses to be used in our main method. Next, all we must do is call these object’s specific methods we polymorphed by the extended class’ method name. Before you know it, we have enough for a steak dinner! Who’s cooking the steak?

I suppose lamb is good too!

Hopefully you may now understand Java polymorphism, or at least understand it before your next meal. Bon-appeti!

My video on this subject

Follow my original code on my GitHub profile!

Java Intermediate: Annotations

Once I was driving, but got pulled over by a state trooper. He saw the sticker on my windshield, stating that my car is due for its annual inspection soon. I told him I had an appointment scheduled for this weekend. He understood, letting me go on my way. This officer didn’t know the context of my situation and couldn’t know until told. This wasn’t wrong, he was just doing his job. Today we’re going to be talking about annotations which just help Java Virtual Machine (JVM) compilers do their jobs.

Java annotations are attached to classes, methods, or fields, represented with @ and represent metadata (data about data) for the compiler. Apply by placing the annotation at line above whatever you’re applying it to, like so:

class Parent {
	void speak() { System.out.println("I can talk!") }
}

class Toddler extends Parent {
	@Override
	void speak() { System.out.println("I can tawk!") }
}

In my earlier statement about my vehicle’s upcoming annual inspection, this is an example of giving context to the compiler that it otherwise wouldn’t have, displaying errors during compile time. Let’s look at a few:

  • @Override – the most common, assures that subclass method is overriding parent class method. In Java, this overrides existing behavior of a method, as seen above. Same method, different behavior in subclass.
  • @SuppressWarnings – is self-explanatory. Normally warnings are welcome unless they become annoying or inappropriate during compile time, such as an excessive number of warnings.
  • @Deprecated – marks method as deprecated so that compiler will print a warning about it. Good practice to use compiler for warning others what NOT to do for future versions.

These three annotations are applied to Java code use. Java annotations substitute the needs for XML or a marker (empty) interface. There are other annotations as well; users may even create their own Java annotations if necessary! To interact with the compiler and give it and others context in your next Java program, try using annotations.

Follow my original code on my GitHub profile!

Java Basics: Objects

Hello again readers! Today we’re going to be taking a step back from all of these new features and go back to core Java design: objects!

Objects are the cornerstone of all Java development as Java is an (Object-Oriented Programming) OOP language. Each one is made with a state and behavior. Think of a blueprint. Classes act as blueprints for objects. Constructors use these blueprints/classes to instantiate objects as such:

public class myClass {
   public myClass(int num) {
      System.out.println("This is object number " + num);
   }

   public static void main(String[] args) {
      myClass obj = new myClass(1);
   }
}

All of this happens within class myClass. First, we create a constructor with one parameter: number. Second, we create our main method and create our object obj from our constructor. Our constructor contains our output which prints object number when run.

Its state is its number integer and its behavior is to print its object number. I demonstrate more use of objects in this video!

Follow my original code on my GitHub profile!

Design a site like this with WordPress.com
Get started