Casting variables in Java

Casting a varibale in java is converting the type of a variable from one datatype to another.

There are two types of casting:

  1. explicit casting;
  2. implicit casting.

Explicit casting

Explicit casting in Java is when you explicitly indicate to the compiler the target type you want to convert the value of your variable to (otherwise your code will not compile).

It is like if you tell the compiler : Trust me, my varibale can be cast to the target type !

The source data type must be compatible with the target data type at runtime (when you execute the program). If not, you will get a ClassCastException.

Examples of explicit casting:

// 256.1234f will be converted to int and the 
// digits after the period (.) will be lost
float f = 256.1234f;
int i = (int)f;

// p is converted to Student datatype
// Student must be a sub-type of Person 
Person p= new Person();
Student s = p;

Implicit casting

Implicit casting in Java is when you assign a variable of a lower (or child) type to a greater (or parent) type. A conversion is  automatically made by the compiler without the programmer’s intervention.

Examples of implicit casting:

// example 1 : a was implicitly casted from int to double
int a = 10;
double d=a;

// example 2 : student was implicitly casted from Student to Person
// we suppose that Student is a subclass of Person
Student student= new Student();
Person person = student;


Casting primitives

Java  allows primitive types to be cast implictly from lower to higher data types . For explicit cast of primitives, you have to be careful with the loss of precision and varibale truncating when you cast higher to lower datatypes (Example : from  double to int).

The following is a summary of what are the implicit and explicit casts allowed for primitive types in Java.

Primitives casting in Java

Primitives casting in Java




Java Expressions, Statements and Blocks

In java, Statements are composed of one or many expressions. They may also be grouped into blocks.


Expressions in java are made of variables, operators and method invocations. An expression always evaluates to a single value.

//Examples of valid expressions
a =0;
"Hello "+firstName + " "+ lastName
d = a + b;



A statement in java is a complete unit of execution. Assignment expressions, pre-increment operators, pre-decrement operators, post-increment operators, post-decrement operators, method invocation and object instantiation expressions can compose a statement by terminating the expression with a semicolon (;) .

// using the Examples to create valid statements
int a =0;
System.out.println("Hello "+firstName + " "+ lastName);
double d = a + b;



A block in Java is composed of zero or more statements enclosed inside curly braces { }. Blockes are allowed wherever statements are allowed. Blocks can be nested.

// Example of two blocks
{ // block 1 beginning
  int x=0;
  System.out.println("Block 1 is executed");
} // block 1 ending
{ // block 2 beginning
  System.out.println("Block 2 is executed");
} // block 2 ending



How to get the root exception of any exception

Sometimes, the root exception causing your code to fail is hidden behind an other exception or a set of nested exceptions.

Nested Exceptions

Nested Exceptions


The following code (function) searches for the root exception of any exception and returns it :

public static Throwable getRootException(Throwable exception){
 Throwable rootException=exception;
  rootException = rootException.getCause();
 return rootException;

Example of usage :

catch(MyException e){



JDBC Connection example

JDBC (Java Database Connectivity) is an API provided by Oracle offering a standard for communication between java code and a wide range of databases based on SQL or files (flat files, spreadsheets).

You need a driver for each type of database. That driver is often developed and offered by the company or the open source project maintaining the DBMS (Database Management System) . It comes usually as jar archive that you include manually in your classpath or dynamically using a dependency management system like maven.

The following is a basic example of connection and interrogation of a MySQL database, the same code (with some changes) apply to other databases like Oracle DB,  MariaDB and Postgresql. These changes may include at least the driver name and in some cases  the SQL syntax.

(The explanation of the different steps will follow the code example )

package tutoref;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCMySQLExample {
 // Database URL and Driver
 static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
 static final String DB_URL = "jdbc:mysql://localhost/TUTOREFDB";
 //  Database username and password
 static final String DB_USERNAME ="username";
 static final String DB_PASSWORD ="password";

 public static void main(String[] args) {
  try {
   // registering the driver
   // creating a connection
   Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
   // creating a normal statement
   Statement statement = connection.createStatement();
   // execute a SELECT query and create a ResultSet that holds the results
   String query="SELECT * from USERS";
   ResultSet resultSet = statement.executeQuery(query);
   // iterating through the ResultSet (Display results)
   // create a prepared INSERT query
   String preparedQuery="INSERT INTO USERS(username, password, email, first_name, last_name) VALUES(?,?,?,?,?)";
   PreparedStatement preparedStatement = connection.prepareStatement(preparedQuery);
   // fill the values
   preparedStatement.setString(1, "john.doe"); // username, the 1st index=1 and not 0
   preparedStatement.setString(2, "123demo"); // password
   preparedStatement.setString(2, ""); // email
   preparedStatement.setString(2, "John"); // first name
   preparedStatement.setString(2, "Doe"); // last name
   // execute the query
   boolean success=preparedStatement.execute();

   // free the resources
   if(resultSet != null){
   if(connection != null){
  } catch (ClassNotFoundException | SQLException e) {




Registering the driver

Most of the database specific classes are included in the provided driver. You need to register the driver in order to be able to create a connection.


Creating a connection

The connection object is the link ensuring the communication between the code and the database, you must get a connection to be able to interrogate the database.

The connection object is obtained via the static method getConnection() of the class DriverManager.

Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);

Creating a Statement

A statement object is obtained from the connection object, it is used for executing a static SQL statement and returning the results it produces.

Statement statement = connection.createStatement();


In some cases it is more suitable to use a Prepared Statement in the place of a static Statement. A common example is when you want to protect your application against the SQL Injections.

To obtain a prepared statement you must use one of the prepareStatement(…) static methods of the class DriverManager, and specify a query containing interrogation symbols in the place of values.

You have to specify the values before you execute the query and get the results.

PreparedStatement preparedStatement=connection.prepareStatement(
"INSERT INTO USERS(username, password, email, first_name, last_name) VALUES(?,?,?,?,?)")
// fill the values
preparedStatement.setString(1, "john.doe"); // username, the 1st index=1 and not 0
preparedStatement.setString(2, "123demo"); // password
preparedStatement.setString(2, ""); // email
preparedStatement.setString(2, "John"); // first name
preparedStatement.setString(2, "Doe"); // last name

Executing the query and getting the results

When your Statement or Prepared Statement is ready, you can execute the query and get the results.

If you execute a query of type SELECT, you must use the executeQuery method of the statement object, the results are returned inside an iterable object of type ResultSet.

ResultSet resultSet = statement.executeQuery(query);


The above code will print the usernames on the console.

If you execute a query of type UPDATE, DELETE or INSERT, you can use the execute() method, which returns true if the first result is a ResultSet object, and false if the first result is an update count or there is no result. You also have the possibility to use the executeUpdate() method, that returns either  the number of deleted, updated or inserted rows or 0 for SQL statements that return nothing.

Freeing the resources

When you work with databases, you have to close the resources manually, otherwise you can have problems with the DBMS limitations. Elements having to be closed include (in this order) , the ResultsSets, The statements and the connection.

What is the order of initialization in a Java class

The order of initialization of a Java class is the following:

  1. Static constants, variables and blocks are first initialized in the order in which they appear in the code;
  2. Then non-static constants, variables and blocks are first initialized in the order in which they appear in the code;

Consider the following code :

public class Sample{
 static Sample2 a = new Sample2();
 Sample2 b = new Sample2("Instance variable");
 public Sample(){
 System.out.println("Static block");
 public static void main(String[] args) {
 new Sample();

class Sample2{
 public Sample2(){
 System.out.println("Sample2 Constructor");
 public Sample2(String str){


Accoding the above points 1 and 2, the displayed result will be :

Sample2 Constructor
Static block
Instance variable



Labeled statements in Java 8

Labeled statements are transfer of control statements used to give a statement a prefixed label.

Referred statements can be loops, switch statements or blocks {statements enclosed in curly braces}. Example :

loop1: for(int i=0;i<10<i++){


Labeled statements are used in conjunction with break and continue statements.

To understand better, lets take the following example of two nested for loops and a break statement. The use of the break statement inside of the inner loop will cause the program to interrupt the innermost for loop when j become equal to 5  . It will not interrupt the outer loop.


for(int i=0;i<=10;i++){
 for(int j=0;j<=10;j++){
  System.out.println(i + " - " + j);


Now we will label the outer for loop, and add the same label to the innermost break statement. This will cause the program to interrupt the outer loop (the labeled one) .

for(int i=0;i<=10;i++){
 for(int j=0;j<=10;j++){
  System.out.println(i + " - " + j);
   break label1;


As mentioned earlier, labeled statements can be used in conjunction with a break statement inside a loop or a switch statement. or with a continue statement inside a loop.

The following example will interrupt the outer for loop when j == 5 which is the labelled for loop.

for(int i=0;i<=10;i++){
 for(int j=0;j<=10;j++){
  System.out.println(i + " - " + j);
   case 5:
    break label1;
    // do nothing


Access modifiers in java : public, protected, default, private

In Java, access modifiers are keywords that help setting the accessibility of classes, methods or members. There are four access modifiers in Java language, they are exposed in the following from the least restrictive (public) to the most restrictive (private).



Means that the class or the member variable or method can be accessed from anywhere in the code, from the same package or from a different one.


Can be used with inner variables, methods or inner classes. This access modifier means that the member can be accessed only from the same class or a subclass.

Default (or package private)

This is the default access modifier that will be applied when we don’t specify any. It can be used with a class or member variable or method.
It means that the member can be accessed only from the same package. Please note that a default member cannot be accessed from a subclass in an other package as well.


The private keyword can be used for members (variables, methods or inner classes , when used it limits access to members to only the same class only.


The native keyword in java is not considered as an access modifier.


class package Sub-class

(same package)


(other package)

public  ✔  ✔  ✔  ✔
Protected  ✔  ✔  ✔  ✔  x
default  ✔  ✔  ✔  x  x
private  ✔  x  x  x  x

What is new in Java 9

Java 9 is a major feature release. The following summarizes features and enhancements in Java  language version 9.

  • Allow @SafeVargs annotation on private instance methods
  • Allow final variables to be used as resources in the try-with-resources statement
  • Allow the use of diamond with anonymous classes if the type of the inferred type is denotable.
  • Complete the removal of underscore from the set of legal identifier names. This was started in java version 8.
  • Add support for private interface methods.

Reference :

Array Example in Java 8

Declaring and instantiating an array

// declaration and instanciation
String [] oneDimentionArray = new String[10];
String [][] multiDimentionArray = new String[10][];
String [][] multiDimentionArray2 = new String[10][20];

Note that you can also put the square brackets after the variable name :

// Brackets after the variable name
String oneDimentionArray[] = new String[10];


Affecting values to an array (Initialisation)

// One dimension array
oneDimentionArray[0]="Value 1";
oneDimentionArray[2]="Value 2";

// two dimension array
multiDimentionArray[0][1] = "An other value";

Trying to access oneDimentionArray[1] will throw the ArrayOutOfBoundsException as it was not set.

Declaring and initialization

When creating arrays of Objects (and not primitives) , you can use curly brackets to initialize you array with the values this way :

String [] array = new String [] {"A", "B", "C"};


Iterating trough arrays

To read array values you can read a specific index :

System.out.println("Cell 0 value : "+myTable[0]);

You can also iterate through the array using the old for loop:

for(int i = 0 ; i < myTable.lenght ; i++){

Or the new enhanced for loop :

// we suppose that myArray is an array of Strings
for(String value: myArray){

Please note that you can find other ways of iterating through arrays.

Java Enum example

The enum type in java is a special data type that enables a variable to be set to one of a predefined set of values.

An enum can be in its own file (example: or included in an other class.

Example of a simple enum

enum Directions {

A more elaborated example

enum Directions{
     // the ; after the fields is needed
     private final String symbol;
     Directions(String symbol){
     public String symbol(){
      return this.symbol;

 The use of an enum

Directions direction = Directions.EAST;


  case EAST:
  case SOUTH:
  case NORTH:
  case WEST:

The above code will print the following: