Java, The Carlos Way - Lesson 2

7 minute read

featured image alt

Welcome back to Java, the Carlos Way! I hope my first lesson got your feet wet and your curiosity piqued enough to want to come back and learn some more. This time around, we’ll be going through some other basics, how to set up a development environment, and finally get your feet wet!

Previous Lesson

Your First Java Program

The time has finally come to program your first Java project. In the spirit of programming culture, the first program that we will write together will do a very simple thing: output the words Hello World!. This is many programmers’ first code, and it will be yours in a very short amount of time.

Try to follow along, not by copying and pasting, but by typing everything out. That way, you know exactly what you’re doing and you get a better feel for your programming environment.

Let’s dive right in:

Main.java

// First, we declare the class Main.
public class Main{
  // Next, we declare the function, main, inside Main.
  // "void" means that we will not be returning any values
  // At the conclusion of our function.
  public static void main(String[] args){
    // Next, we print out the words "Hello World!".
    System.out.println("Hello World!");
  }
} // Always check your brackets and semicolons!

More Java 101

We’ll need to learn a little bit more about what we’re doing in order to understand the code that we just typed. Bear with me, there will be more code coming soon!

Java Data Types

In Java, information is stored in a variety of types. a type is like a container of storage, and a limited amount of information fits in each of the storage containers. You want to be as storage-efficient as possible, so you’ll choose a smaller container if possible, if you know that your information won’t take up that much space, which makes your code faster and more efficient.

There are a lot of data types in Java, but I’ll just go through the most popular ones:

  • String
  • Integer
  • Double
  • Boolean

Quick Tip: Integers can be written as int interchangeably, which is why you’ll often see me substitute int for Integer!

String

A string is a datatype that represents an array of characters. These characters can be anything, from numbers, to letters, to emoji. Strings in Java are very powerful, and have many embedded functions that allow you to perform many operations. I often find myself casting (converting) other data types to Strings in order to perform specific operations on them, like getting the number of digits in a certain number, or getting the last n digits of a number/decimal. A drawback of this data type is that it takes up lots of memory space, and inability to perform arithmetic.

Integer

An integer is a much more lean data type, sitting at only 4 bytes. This means, of course, that it can store values from -2,147,483,648 to 2,147,483,647 - which, for most cases, should be enough for any numerical value. This data type contains all of the operations you think you’ll need, such as addition, subtraction, multiplication, and division.

Double

A double is very similar to an Integer, but it holds twice as many bytes (8). While this is more storage, and will take up more RAM, doubles have a unique capability - to store decimal values. Because it is impossible to store 1.5 into an Integer, the most used data type for this kind of value is a double.

Boolean

Perhaps the most useful data type is the Java boolean. This grants the ability to store binary values, namely True or False. You’ll be using these a lot of the time without even declaring them, as many functions in Java return a True when an operation is successfully completed.

Other Types

There are many other types that you might find yourself using when you become a more successful programmer and want to worry about memory allocation, such as:

  • short
  • long
  • float

Additionally, the classes you write yourself act just like data types, which you will learn more about later on. When we make functions, we will also be employing data types, as we can return them at the conclusion of our functions.

Declaring variables

Now that we know all about data types and what they store, let’s look into how to create them and use them in our code.

The general structure for declaring variables is as follows:

datatype variableName = value
  • datatype is the name of the datatype we are declaring.
  • variableName is the name of the variable that we will be using in the rest of our code.
  • value is the actual value being stored inside of the variable.

Now, let’s go through an actual example that we can use to rewrite our “Hello World” program:

public class Main{
  public static void main(String[] args){
    // We declare a new String called message that stores
    // the value "Hello World!"
    String message = "Hello World!";
    // We print out the message instead of the text.
    System.out.println(message);
  }
}
// Output: Hello World!

As you can see, the output is the exact same, but this time, we created a variable and printed it out instead of placing the content of the message inside of System.out.println();

Casting Between Data Types

Oftentimes you’ll find yourself wanting to convert between data types, such as from integers to Strings, as mentioned above, or between more abstract data types to Strings in order to visualize them easily. The process of converting a variable from one data type to another is called Casting.

The general format of casting from one type to another is as follows:

There are two kinds of casting:

Lossless Casting

Lossless casting is casting in which no information is lost. When an Integer is converted into a Double, no information is lost, because all of the integer’s values can be placed within the double. Here’s an example of that process:

/**
We first declare the variable, "num" as an integer,
and assign the value of 420.
**/
int num = 420;

// We print out the value that we just created.
System.out.println(num);
// Output at this point: 420

/**
We create a new double, "dec", and cast "num" to "dec".
**/
double dec = (double)num;

// We print out "dec".
System.out.println(dec);
// Output: 420.00

As you can see, no information is lost, because doubles can hold any and all values of integers.

Lossy Casting

Lossy casting involves converting an object of greater data capacity into one with less data capacity. For example, the reverse of the previous example would be considered a lossy cast, because a double is 8 bytes and an integer is 4 bytes, and information could be lost. Let’s show an example:

double dec = 420.69;

System.out.println(dec);
// Output: 420.69

// Information is lost because integers do not have decimals.
int num = (int)dec;

System.out.println(num);
// Output: 420

In the above example, you can see that the new integer we created did not have the decimal value that was after 420. It is important to remember that this occurs so that you will not make any mistakes in math or your code in general!

Quick Tip: By default and when casting, Java does NOT round up or down. It truncates, which means it just chops off whatever information it needs to from the numerical value.

Automatic Casting

Since lossless casting does not result in the loss of information, Java will do it automatically, if prompted for a datatype that is higher in storage than the one that is given. This actually happens all the time, most importantly for beginners when we use System.out.println();.

For instance:

System.out.println(11);
// 11 is being casted to a String and then printed out.
// Output: 11

Since System.out.println(); takes in a String as its parameter (the variable between the parentheses), Java automatically casts the integer to a String and then uses it as-is. This will also work with doubles, and the other data types I mentioned.

toString

Another form of automatic casting is what is called the toString() function. toString() is a function that is embedded by default in all classes, and is actually what is being called in the function above, and whenever we convert any of the default data type into a String. When we write a Class, which you will be doing a lot of later, you will also have the opportunity to write your own toString() function, and with that, you’ll be able to easily write text outputs for your functions.

Let’s try an example of a type that already exists though:

// Num is declared as an integer.
int num = 420;
// It is converted into a string with toString.
String numString = num.toString();
// A string is printed out.
System.out.println(numString);
// Output: 420

Summary

In this lesson, you learned:

  • The standard "Hello World!" Java program
  • Basic Java data types
  • How to print things to the Java console
  • Casting (Converting between data types)
    • Lossy Casting (Data is lost)
    • Lossless Casting (No data is lost)
  • Automatic casting
  • The toString function

Next time, we’ll go into creating Java projects in my favorite editor, VSCode, logical statements, and basic inheritance. Stay tuned!

LinkedIn

Subscribe to Newsletter

* indicates required

Comments