Java Performance Tuning Books for Students To Read

Java development requires more than just experience. Learning from the experiences of other people is an invaluable habit that will propel your programming career to another level.

Photo by Markus Spiske from Pexels

Luckily for Java lovers, some developers have offered their best insights on Java programming in books. Here are the top Java performance books that will enlighten your craft.

Java Performance: The Definitive Guide

These 400 pages will transform your mentality as a Java engineer. It focuses on approaches that form the foundation of a successful project. Some of the concepts addressed by Scotts Oaks include response time, throughput, and micro-benchmarking. Other areas covered in detail include memory optimization, multi-thread concept, and garbage collection analysis. You will admit that these are the pivotal elements of any programming exercise. Learning from this Java guru offers the best insights into one of the most promising programming languages.

Java Performance

The book is co-authored by Binu John and Charlie Hunt. It provides some of the most comprehensive views of performance tuning tools and JVM. It is unique because the author has focused on Oracle products, helping developers to understand this area in depth. Among the areas covered include performance tuning, performance benchmarking, and profiling. The book featured more text and less code. The technique helps you to use imagination and get into an intense understanding of coding.

Java Performance Tuning

Jack Shirazi demonstrates his mastery of Java performance by including his life experiences in the process of development. He has also provided excellent demonstrations of real-life projects. The tips mentioned in the book will also help developers kick-start their projects. For beginners, this is a book that will outline the expected journey, especially from seasoned programmers who have walked the road. Some of the areas given prominence include exceptions, I/O, and object creation. It is an eye-opener for any Java lover.

Systems Performance: Enterprise and the Cloud

Brendan Gregg is a certified performance architect for Java. Brendan has given a general view of performance as opposed to specific Java issues. For engineers, this is the kind of material you would want for your upcoming project because it does not restrict your thinking. It goes into incredible depth using very simple language. This makes the book easy to understand.

Books on Java programming are an eye-opener for amateurs and seasoned developers alike. They provide a chance to learn from the mistakes and successes of other people. You have an invaluable start to your programming journey.

How do I format EditText for currency input in Android?

The following Android code snippet shows you how to customize the input value format of an EditText component for accepting currency number. To format the input value we will create a text watcher class called MoneyTextWatcher, this class implements of the android.text.TextWatcher interface. To apply this text watcher class we call the the addTextChangedListener() method of the EditText object and pass an instance of MoneyTextWatcher.

package org.kodejava.android;

import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

import java.math.BigDecimal;

public class MainActivity extends AppCompatActivity {
    private EditText editText;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = findViewById(R.id.editText);
        editText.addTextChangedListener(new MoneyTextWatcher(editText));

        textView = findViewById(R.id.textView);
    }

    public void doGetValue(View view) {
        BigDecimal value = MoneyTextWatcher.parseCurrencyValue(editText.getText().toString());
        textView.setText(String.valueOf(value));
    }
}

When the EditText input is changed the afterTextChanged() method of the text watcher will be called. In this method we’ll take the input text and format the input value with currency symbol and a number, this is done by the NumberFormat.getCurrencyInstance() object. The static helper method parseCurrencyValue() will get the number part of the EditText by removing the currency symbol and return the input number.

package org.kodejava.android;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;

import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Objects;

public class MoneyTextWatcher implements TextWatcher {
    public static final NumberFormat numberFormat = NumberFormat.getCurrencyInstance(new Locale("id", "ID"));
    private final WeakReference<EditText> editTextWeakReference;

    public MoneyTextWatcher(EditText editText) {
        editTextWeakReference = new WeakReference<>(editText);
        numberFormat.setMaximumFractionDigits(0);
        numberFormat.setRoundingMode(RoundingMode.FLOOR);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        EditText editText = editTextWeakReference.get();
        if (editText == null || editText.getText().toString().equals("")) {
            return;
        }
        editText.removeTextChangedListener(this);

        BigDecimal parsed = parseCurrencyValue(editText.getText().toString());
        String formatted = numberFormat.format(parsed);

        editText.setText(formatted);
        editText.setSelection(formatted.length());
        editText.addTextChangedListener(this);
    }

    public static BigDecimal parseCurrencyValue(String value) {
        try {
            String replaceRegex = String.format("[%s,.\\s]", Objects.requireNonNull(numberFormat.getCurrency()).getDisplayName());
            String currencyValue = value.replaceAll(replaceRegex, "");
            return new BigDecimal(currencyValue);
        } catch (Exception e) {
            Log.e("MyApp", e.getMessage(), e);
        }
        return BigDecimal.ZERO;
    }
}

The following animation is the result of our code snippet above.

Currency Format EditText Demo

Currency Format EditText Demo

How do I get Android Device ID or IMEI?

The following code snippets shows you how to get a Device ID of an Android phone. To be able to read the Device ID you need to update the AndroidManifest.xml file and add the READ_PHONE_STATE permission.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="org.kodejava.android">

    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    ...
    ...
</manifest>
package org.kodejava.android;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class MainActivity extends AppCompatActivity {

    private static final int PERMISSIONS_READ_PHONE_STATE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, PERMISSIONS_READ_PHONE_STATE);
        }

        String deviceId = null;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            deviceId = Settings.Secure.getString(getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
        } else {
            TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            if (telephonyManager.getImei() != null) {
                deviceId = telephonyManager.getImei();
            } else if (telephonyManager.getMeid() != null) {
                deviceId = telephonyManager.getMeid();
            }
        }

        Log.d("MyApp", "Device ID: " + deviceId);
    }
}

How do I print to a Bluetooth thermal printer in Android?

In this example we are going to create a simple Android application to print texts to a Bluetooth thermal printer. We’ll be using the Android library for ESC/POS Thermal Printer to develop this example.

We begin by creating an Android project with an Empty Activity. After the project is created we need to edit the app/build.gradle to add the required dependencies and the repository from which it will be downloaded.

...
...

dependencies {
    ...
    ...
    implementation 'com.github.dantsu:escpos-thermalprinter-android:2.0.11'
}

allprojects {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}

Next, add the permission to access Bluetooth in the AndriodManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="org.kodejava.android">

    <uses-permission android:name="android.permission.BLUETOOTH" />

    ...
    ...
</manifest>

Let’s now jump to the code snippet that will actually print our store receipt to the printer. The steps are quite simple.

After added the uses-permission in the AndroidManigest.xml we also need to check permission in the application, you’ll do it like this.

if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH}, MainActivity.PERMISSION_BLUETOOTH);
}

Open the connection to Bluetooth printer by calling the selectFirstPaired() method of the BluetoothPrintersConnections class. This will give us an instance of BluetoothConnection. If the connection is good we create an instance of EscPosPrinter by passing some parameters like the connection, printer dpi, width in millimeter and the printer’s number of character per line.

BluetoothConnection connection = BluetoothPrintersConnections.selectFirstPaired();
EscPosPrinter printer = new EscPosPrinter(connection, 203, 48f, 32);

The next step is to prepare the text to be printed and called the printFormattedText() of the printer object and pass the text to be printed.

String text = "[C]Hello World!\n";
printer.printFormattedText(text);

Here is the full code snippet for our application.

package org.kodejava.android;

import android.Manifest;
import android.content.pm.PackageManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.dantsu.escposprinter.EscPosPrinter;
import com.dantsu.escposprinter.connection.bluetooth.BluetoothConnection;
import com.dantsu.escposprinter.connection.bluetooth.BluetoothPrintersConnections;
import com.dantsu.escposprinter.textparser.PrinterTextParserImg;

import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    public static final int PERMISSION_BLUETOOTH = 1;

    private final Locale locale = new Locale("id", "ID");
    private final DateFormat df = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss a", locale);
    private final NumberFormat nf = NumberFormat.getCurrencyInstance(locale);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void doPrint(View view) {
        try {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH}, MainActivity.PERMISSION_BLUETOOTH);
            } else {
                BluetoothConnection connection = BluetoothPrintersConnections.selectFirstPaired();
                if (connection != null) {
                    EscPosPrinter printer = new EscPosPrinter(connection, 203, 48f, 32);
                    final String text = "[C]<img>" + PrinterTextParserImg.bitmapToHexadecimalString(printer,
                            this.getApplicationContext().getResources().getDrawableForDensity(R.drawable.logo,
                                    DisplayMetrics.DENSITY_LOW, getTheme())) + "</img>\n" +
                            "[L]\n" +
                            "[L]" + df.format(new Date()) + "\n" +
                            "[C]================================\n" +
                            "[L]<b>Effective Java</b>\n" +
                            "[L]    1 pcs[R]" + nf.format(25000) + "\n" +
                            "[L]<b>Headfirst Android Development</b>\n" +
                            "[L]    1 pcs[R]" + nf.format(45000) + "\n" +
                            "[L]<b>The Martian</b>\n" +
                            "[L]    1 pcs[R]" + nf.format(20000) + "\n" +
                            "[C]--------------------------------\n" +
                            "[L]TOTAL[R]" + nf.format(90000) + "\n" +
                            "[L]DISCOUNT 15%[R]" + nf.format(13500) + "\n" +
                            "[L]TAX 10%[R]" + nf.format(7650) + "\n" +
                            "[L]<b>GRAND TOTAL[R]" + nf.format(84150) + "</b>\n" +
                            "[C]--------------------------------\n" +
                            "[C]<barcode type='ean13' height='10'>202105160005</barcode>\n" +
                            "[C]--------------------------------\n" +
                            "[C]Thanks For Shopping\n" +
                            "[C]https://kodejava.org\n" +
                            "[L]\n" +
                            "[L]<qrcode>https://kodejava.org</qrcode>\n";

                    printer.printFormattedText(text);
                } else {
                    Toast.makeText(this, "No printer was connected!", Toast.LENGTH_SHORT).show();
                }
            }
        } catch (Exception e) {
            Log.e("APP", "Can't print", e);
        }
    }
}

The following image is the result of our code snippet printed on 48mm thermal printer.

Android Bluetooth Thermal Printer

Android Bluetooth Thermal Printer

You can find the complete source code in the following repository Android Bluetooth Thermal Printer Example. For more information on formatted text syntax guideline you can visit the project documentation website.

How do I read MySQL data from Android using JDBC?

This example show you how to connect and read data from MySQL database directly from Android. The following steps and code snippet will show you how to do it.

Add the MySQL JDBC driver into your project dependencies. Open the app/build.gradle file and add the dependency.

...
...

dependencies {
    ...
    ...
    implementation 'mysql:mysql-connector-java:5.1.49'
}

If you want to connect to MariaDB you can change the JDBC driver dependency using 'org.mariadb.jdbc:mariadb-java-client:1.8.0', also update the JDBC url in the code snippet by replacing mysql with mariadb.

Next, add internet permission to our application in AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="org.kodejava.android">

    <uses-permission android:name="android.permission.INTERNET" />

    ...
    ...

</manifest>

Let’s connect, read data from the database and display the information on the screen. In the code snippet we create an AsyncTask to read the information from the database. In the doInBackground() method we open a connection to the database, create a PreparedStatement, execute a query, get a ResultSet and read the information from it. We pack the data into a Map and return it.

After the doInBackground() method finish its execution the onPostExecute() method will be called. In this method we take the result, the Map returned by the doInBackground() method, and set the values into the TextView compoments for display.

package org.kodejava.android;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    private static final String URL = "jdbc:mysql://192.168.0.107:3306/kodejava";
    private static final String USER = "kodejava";
    private static final String PASSWORD = "kodejava";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new InfoAsyncTask().execute();
    }

    @SuppressLint("StaticFieldLeak")
    public class InfoAsyncTask extends AsyncTask<Void, Void, Map<String, String>> {
        @Override
        protected Map<String, String> doInBackground(Void... voids) {
            Map<String, String> info = new HashMap<>();

            try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
                String sql = "SELECT name, address, phone_number FROM school_info LIMIT 1";
                PreparedStatement statement = connection.prepareStatement(sql);
                ResultSet resultSet = statement.executeQuery();
                if (resultSet.next()) {
                    info.put("name", resultSet.getString("name"));
                    info.put("address", resultSet.getString("address"));
                    info.put("phone_number", resultSet.getString("phone_number"));
                }                
            } catch (Exception e) {
                Log.e("InfoAsyncTask", "Error reading school information", e);
            }

            return info;
        }

        @Override
        protected void onPostExecute(Map<String, String> result) {
            if (!result.isEmpty()) {
                TextView textViewName = findViewById(R.id.textViewName);
                TextView textViewAddress = findViewById(R.id.textViewAddress);
                TextView textViewPhoneNumber = findViewById(R.id.textViewPhone);

                textViewName.setText(result.get("name"));
                textViewAddress.setText(result.get("address"));
                textViewPhoneNumber.setText(result.get("phone_number"));
            }
        }
    }
}
  • Finally here is the screenshot of our Android application.
Android - MySQL JDBC

Android – MySQL JDBC

The complete source code can be accesses in our GitHub repository here: android-mysql-example.

Basic Operators in Java

This article covers basic operators of Java syntax, and how they function. By thorough discussion and coding examples, you’ll be able to use basic operators in your programs like a pro.

What are basic operators?

Java provides different sets of operators to perform simple computations like addition/ subtraction and other advanced operators for decision making or individual bitwise calculations.

Here are some major categories of operators

  • Arithmetic Operators (+, -, *, /)
  • Relational Operators (==, !=)
  • Logical Operators (&&, ||)
  • Assignment Operators (=, +=, -=)
  • Unary Operators (pre/post-fix)
  • Shift Operators (>>, << )
  • Bitwise Operators (&, |, ^)
  • Ternary/Conditional Operator (?:)
  • Misc Operators

The scope of this article encompass arithmetic, relational and logical operators only.

Arithmetic Operators

You can use basic arithmetic operators to perform a mathematical calculation and impact the value of any variable. Let’s see how it works in Java.

package com.basicoperators.core;

public class ArithmeticOperators {
    public static void main(String[] args) {
        // Addition 
        int apples = 5;
        int oranges = 7;
        int totalFruits = apples + oranges;

        System.out.println("\n-------------Addition---------------- " );
        System.out.println("Apples: " + apples);
        System.out.println("Oranges: " + oranges);
        System.out.println("Total Fruits: " + totalFruits);

        // Subtraction      
        int totalBananas = 24;
        int bananasSold = 12;
        int bananasLeft = totalBananas - bananasSold;

        System.out.println("\n----------------Subtraction--------------- " );
        System.out.println("Total Bananas: " + totalBananas);
        System.out.println("Bananas Sold: " + bananasSold);
        System.out.println("Bananas Left: " + bananasLeft);

        // Multiplication   
        int weeks = 3;
        int daysInAWeek = 7;
        int totalNumberOfDays = weeks * daysInAWeek;

        System.out.println("\n--------------Multiplication-------------- " );
        System.out.println("Days In A Week: " + daysInAWeek);
        System.out.println("Days In A Week: " + daysInAWeek);
        System.out.println("Total Number Of Days: " + totalNumberOfDays);

        // Division
        int totalMinutesConsumed = 420;
        int minutesInOneHour = 60;
        int numOfHours = totalMinutesConsumed / minutesInOneHour;

        System.out.println("\n----------------Division---------------- " );

        System.out.println("Total Minutes: " + totalMinutesConsumed);
        System.out.println("Minutes In One Hour: " + minutesInOneHour);
        System.out.println("Num Of Hours: " + numOfHours);    
    }
}

Output

----------------------Addition---------------------- 
Apples: 5
Oranges: 7
Total Fruits: 12

---------------------Subtraction--------------------- 
Total Bananas: 24
Bananas Sold: 12
Bananas Left: 12

--------------------Multiplication------------------- 
Days In A Week: 7
Days In A Week: 7
Total Number Of Days: 21

----------------------Division---------------------- 
Total Minutes Consumed: 420
Minutes In One Hour: 60
Num Of Hours: 7

Relational Operators

As the name implies, relational operators define the relationship of one instance with another. This means you can compare two numbers and see what relationship do they share. If they are equal to each other, one is greater than or smaller than the other number. Like 2 is less than 3. According to Java syntax, both instances should be of the same data type. For example, you can not compare if an integer is less than a string. Here is a small snippet explaining how you can use basic relational operators in Java.

package com.basicoperators.core;

public class RelationalOperators {
    public static void main(String[] args) {
        int even = 2;
        int odd = 3;

        System.out.println("Even = " + even);
        System.out.println("Odd = " + odd);

        // prints if even is equal to odd
        boolean check = even == odd;
        System.out.println("Is Even equal to Odd? " + check);

        // prints if even is not equal to odd
        check = even != odd;
        System.out.println("Is Even not equal to Odd? " + check);

        // prints if even is greater than odd
        check = even > odd;
        System.out.println("Is Even greater than Odd? " + check);

        // prints if even is less than odd
        check = even < odd;
        System.out.println("Is Even less than Odd? " + check);

        // prints if even is greater than equal to odd
        check = even >= odd;
        System.out.println("Is Even greater than equal to Odd? " + check);

        // prints if even is less than equal to odd
        check = even <= odd;
        System.out.println("Is Even less than equal to Odd? " + check);
    }
}

Output

Even = 2
Odd = 3
Is Even equal to Odd? false
Is Even not equal to Odd? true
Is Even greater than Odd? false
Is Even less than Odd? true
Is Even greater than equal to Odd? false
Is Even less than equal to Odd? true

Logical Operators

Logical Operators in Java are used for decision making. They allow the programmer to test if the combination of given expressions are true or false. Based on the result of your expression, you can make a decision.

  • AND – returns “true” only if both expressions are true
  • OR – returns “true” if any of the given expressions is true
  • NOT – returns the “inverse” of any given boolean expression

For your better understanding, let’s look at the following snippet.

package com.basicoperators.core;

public class LogicalOperators {
    public static void main(String[] args) {
        String myPet1 = "doggo";
        String myPet2 = "kitty";

        System.out.println("Pet1: " + myPet1);
        System.out.println("Pet2: " + myPet2);

        // implements AND
        boolean check = myPet1.equals("doggo") && myPet2.equals("kitty");
        // returns true only when both conditions are true
        System.out.println("Does my first pet name \"doggo\", and second one \"kitty\"? " + check);

        check = myPet1.equals("dog") && myPet2.equals("kitty");
        // returns "false" even if single condition is false 
        // remember these conditions are case sensitive
        System.out.println("Does my first pet name \"dog\", and second one \"kitty\"? " + check);

        // implements OR
        check = myPet1.equals("doggo") || myPet2.equals("lion");
        // returns "true" even when single condition is true
        System.out.println("Does any of my pet name \"doggo\"? " + check);

        check = myPet1.equals("cat") || myPet2.equals("tiger");
        // returns "false" because both conditions are false
        System.out.println("Does any of my pet name \"tiger\"? " + check);

        // implements NOT
        check = !(myPet1.equals("bingo") && myPet2.equals("kate"));
        // returns "true" when both conditions are true (inverse of statement)
        System.out.println("Does my first pet name \"bingo\", and second one \"kate\"? " + check);

        check = !(myPet1.equals("doggo") && myPet2.equals("kitty"));
        // returns "false" because both conditions are true
        System.out.println("Does my first pet name \"doggo\", and second one \"kitty\"? " + check);
    }
}

Output

Pet1: doggo
Pet2: kitty
Does my first pet name "doggo", and second one "kitty"? true
Does my first pet name "dog", and second one "kitty"? false
Does any of my pet name "doggo"? true
Does any of my pet name "tiger"? false
Does my first pet name "bingo", and second one "kate"? true
Does my first pet name "doggo", and second one "kitty"? false

Conclusion

The basic operators in Java are pretty simple to learn and easy to use. You might get overwhelmed by studying the different operators all at once. However, we recommend you practicing one set at a time. This way, you’ll master all of them soon. As always, you’re welcome to plug-in in case of any confusion. Happy learning!

How do I install Calibri font in Ubuntu?

I need to create a Microsoft Word Mail Merge document in my Java Spring MVC application. But running it in Ubuntu server resulting in a document that missing the default font use in the document, which is the Calibri font. So I need to install the font in Ubuntu to make the document looks as expected.

Here what I need to do to install the font in my Ubuntu box. Starts by updating the repository package list to get latest packages information for upgrades or new package installation.

sudo apt-get update

Then install FontForge in our system. FontForge is a free and open source font editor, but in this case it will help doing the font conversion in the installation script on the upcoming step.

sudo apt-get install fontforge

Install the Microsoft Cabinet file unpacker. This is required for the next script to successfully install the fonts.

sudo apt-get install cabextract

The following script will install Microsoft Vista TrueType Fonts (TTF) in Ubuntu. It includes the following fonts, Calibri, Cambria, Candara, Consolas, Constantia, and Corbel.

wget https://gist.github.com/maxwelleite/10774746/raw/ttf-vista-fonts-installer.sh -q -O - | sudo bash

Run the next command to see if the font successfully installed. You will see the Calibri fonts in the result if the fonts successfully installed.

fc-list | grep Calibri

Here are the list of installed Calibri fonts.

/usr/share/fonts/truetype/vista/calibriz.ttf: Calibri:style=Bold Italic
/usr/share/fonts/truetype/vista/calibrii.ttf: Calibri:style=Italic
/usr/share/fonts/truetype/vista/calibrib.ttf: Calibri:style=Bold
/usr/share/fonts/truetype/vista/calibri.ttf: Calibri:style=Regular

How do I create a generic class in Java?

In this example you will learn how to create a generic class in Java. In some of the previous post in this blog you might have read how to use generic for working with Java collection API such as List, Set and Map. Now it is time to learn to create a simple generic class.

As an example in this post will create a class called GenericMachine and we can plug different type of engine into this machine that will be use by the machine to operate. For this demo we will create two engine type, a DieselEngine and a JetEngine. So let’s see how the classes are implemented in generic.

package org.kodejava.examples.generic;

public class GenericMachine<T> {
    private T engine;

    public GenericMachine(T engine) {
        this.engine = engine;
    }

    private void start() {
        System.out.println("This machine running on: " + engine);
    }

    public static void main(String[] args) {
        //
        // Creates a generic machine with diesel engine.
        //
        GenericMachine<DieselEngine> machine = new GenericMachine<>(new DieselEngine());
        machine.start();

        //
        // Creates another generic machine with jet engine.
        //
        GenericMachine<JetEngine> anotherMachine = new GenericMachine<>(new JetEngine());
        anotherMachine.start();
    }
}

Now, for the two engine class we will only create an empty class so that the GenericMachine class can be compile successfully. And here are the engine classes:

package org.kodejava.examples.generic;

public class DieselEngine {
}
package org.kodejava.examples.generic;

public class JetEngine {
}

The <T> in the class declaration tell that we want the GenericMachine class to have type parameter. We also use the T type parameter at the class constructor to pass the engine.

7 Of The Best Java Podcasts Today

Java has already taken the coding world by storm with its promises to create better technologies for the future. Though, if you’re looking to learn about the Java programming language from a podcast, it can be hard to find a sufficient developer (or in this case, Java) podcast to learn from, with literally hundreds of podcasts to listen to these days.

So, where should you start? Don’t panic! We’re here to help!

We’ve taken the liberty of searching for the best Java podcasts for you, despite the hundreds of great ones that are out there. Plus, we want to show you the most up-to-date podcasts that you can learn the coding language from.

So, without further ado, here are 7 of the best Java podcasts that you should definitely take a listen to today!

1. Simple Programmer Podcast

Okay, so this one’s not exclusively a Java podcast. However, there’s no denying that the Simple Programmer Podcast has got lots of great Java-exclusive episodes featuring many brilliant tips, especially for beginners. The Simple Programmer Podcast even helps to direct you towards all sorts of other equally useful Java resources, like books and courses.

2. Coders Campus

Want to learn how to program using the Java programming language? Then this podcast is for you!

Coders Campus will teach you step-by-step lessons on how to use Java to create your own web applications or mobile apps. “From clear tutorials to in-depth explanations of the Java programming language, all ideas and lessons are presented in plain English for better understanding. And, all important concepts are addressed, so that listeners can excel in the field of software,” says Tyler Gregory, a Java expert at UKWritings and Boomessays.

3. Inside Java

Inside Java has anything and everything Java, since it’s brought to you directly from the people that make Java at Oracle. As these people discuss the coding language, they’ll also cover the JVM, OpenJDK, platform security, innovation projects (i.e. Loom and Panama), and other exciting developments and stories about Java.

4. Java Pub House

Want to learn how to program in Java? Then tune in to Java Pub House, where they talk about the odds and ends of Java, like “Hello world,” O/R setups, threading, learning how to troubleshoot coding issues, etc. Once you subscribe to the podcast, you’ll have access to all episodes of the podcast, whether you’re at home or on the go. And whether you’re a novice to Java, or an expert developer looking to brush up on your skills, this is the podcast for you!

5. Coding 101

A Catholic priest talking coding? No kidding!

Father Robert Ballecer joins Lou Maresca on an amazing podcast called Coding 101. In this weekly instructional, project-oriented programming show, Fr. Ballecer and Maresca teaches Java to beginners and intermediate programmers within several interchangeable modules. With a wide range of topics to talk about – special interests, “applied” programming tips and tricks, other Java programs (i.e. C++, Visual Basic, PHP, Perl, etc.), etc., Coding 101 has stood the test of time, despite no longer being in production. You can catch all the episodes, along with guest programmer interviews on their website in the TWiT Archives.

6. Bus318 – Business Programming In Java

Leaning more towards expert Java developers, Bus318 acts as a hardcore Java education, with prerequisites in Computer Science 221 with a (C) or better, at least concurrent enrollment in Business 314. From advanced topics in object-oriented data modeling, to graphical user interfaces, to text and binary I/O, to calling on integration with relational and object-oriented databases, this podcast is your go-to learning spot for Java!

7. Java Off-Heap

“The Java Off-Heap Podcast is sure to bring listeners the latest tech news when it comes to Java,” says Spencer Talbot, a tech writer at Custom Writing and Reviewal. “From Java professionals from Chicago, to going over the latest news and issues, this podcast will go in depth on all the topics, bringing in the most useful knowledge that all Java developer novices and experts can take into consideration.”

Conclusion

So, are you ready to learn Java? Then check out these 7 select podcasts that will give you great insight on coding, and mastering Java!

Happy listening, and happy coding!

What Makes Java 14 Special?

Java 14 has finally been released in March 2020 and brings a whole host of new features that will help ease coding frustrations.

In this article, we will break down the top 6 features that make Java 14 an outstanding update compared to the previous versions. Here we go:

1. Switch Expressions

Although Switch Expressions was just a preview feature over the previous two versions, it has now been given permanent status in version 14.

The lambda syntax was introduced for switch expressions in Java 12 and this means that multiple case labels for pattern matching could be produced. This also stopped any fall-through that led to verbose code and enforced exhaustive cases that would issue a compilation error if all input cases weren’t entered.

In the previous versions yield statements were introduced to replace a break for returning values from an expression. Within Java 14, all these features are included as standard now. We should also point out that yield is not a new keyword for Java and is just used within switch expressions.

2. Previewing Text Blocks

Another former preview item, Text Blocks were first added into Java 13 with the intention to make multiline string literals much easier to create. In particular, HTML, JSON and SWL query strings became much easier as a result.

“Text blocks do remain a preview within Java 14, but they have some interesting new additions,” says Robert Class, a journalist at NextCoursework and Australia2Write. “In particular, you can now use a backslash to display smart multiline string blocks.”

The code \s can build trailing spaces that are ignored by the compiler as a default. This then preserves all of the spaces that are included before it.

3. Pattern Matching for instanceof

Most codebase creations by Java developers will include a strong use of instanceof conditions filtered in throughout the code. Generally speaking, the instanceof conditional check normally comes before an explicit typecast.

Within the Java 14, developers will be happy to know that this has been removed to make conditional extraction a lot clearer. The scope of this variable is currently limited to just the conditional block.

4. Useful NullPointerExceptions

Most developers will tell you that the null pointer exceptions have been a complete nightmare in previous versions of Java. The infamous NPEs can be exceedingly difficult to debug.

This invariably led to developers falling back on other debugging tools or trying to manually figure the variable/method that was null because the stack trace shows only the line number.

“In Java 14, we also see the introduction of a brand new JVM feature, which has enhanced insights with a descriptive stack,” suggests Anita Lockfield, a tech writer at Britstudent and Write My X. “This is not a language feature, but a development of the runtime environment.”

5. Previewing Records

Within Java, you can build classes to hold data and utilize encapsulation to control the way that the data is accessed and modified. It is an object-oriented language.

Because it uses objects, this makes manipulating complicated data types easy and straightforward. This is one of the things that makes Java popular as a platform. The problem has been that the creation of data types has been verbose in old versions and it needs a lot of code for even the simplest case.

Within Java 14, they have introduced records as a brand-new preview feature. This new concept helps developers to include a new language feature without having to make it part of the Java standard. This means that developers can test features and provide feedback that leads to changes before those features become standard.

If you want to use the preview feature, you need to specify the command line flag, --enable-preview for the compilation and runtime. For compilation, you must also specify the sourceflag. The record becomes a much simpler way of showing a data class.

6. New APIs

There are three new APIs within Java 14 that we love. The first is java.io which contains a new annotation type called Serial. This was designed to be used with compiler checks on Serializations. This means that annotations of this type can be applied to serialization related methods and with the fields in any classes declared to be Serializable.

The second API that we enjoyed is java.lang. This class has two distinct methods for the new Record feature, including isRecord() and getRecordComponents(). These have a range of RecordComponent objects and gives up to eleven ways to retrieve things, like the details of annotations and the generic type.

Finally, the new java.util.concurrent.locks API has one new method called setCurrentBlocker. This provides an ability to unpark and park a thread. This helps avoid the same problems that previous versions have had with the Thread.suspend and Thread.resume methods. You can also set the Object that will be returned by getBlocker with this new API, which can help when recalling the no-argument park method from a non-public object.