Learn Java Easy. Introduction

🧩 Introduction: Learn Java from scratch with history and exercises

🧩 Introduction: Learn Java from scratch with history and exercises

A carefree life in Salamanca / Introduction and data types

Throughout my entire life I have felt untouchable. I haven’t had major concerns and I have always had the support of friends and family. I wasn’t aware that, at any moment, my luck could change radically. Most people think they have everything under control, but there are things that don’t depend on oneself. It’s precisely those things that can catch you by surprise at any time. That’s exactly what happened to me.

I understand that you want to learn to program in Java. Don’t worry, I’m going to teach you and, moreover, I’ll do it in a simple way. Actually, programming isn’t difficult, at least not as difficult as it seems. But, before we start, let me introduce myself.

My real name is Pelayo, although everyone calls me Peli. I’m a first-year university student. I live in Salamanca and I’d like to dedicate myself to computer science. For now, things aren’t going as I thought. The truth is that we’ve already entered the second half of the semester and I’ve barely shown up for class. Many of the teachers don’t even know me.

To be honest, I’ve dedicated most of my time to having fun and meeting people. I know that probably, I should start studying as soon as possible, but that’s not my priority.

Learn programming

This weekend I’m going to celebrate a party at my apartment and I want it to be perfect. I don’t like to brag, but I think that, little by little, the gatherings at my house are becoming very popular. Actually, I don’t live alone; therefore, it’s not exactly my apartment. I share a house with two other university students, Rich and Chani. The truth is that they are better students than me, although they can’t be said to be very responsible either. We didn’t know each other before, but in a short time we’ve become good friends.

Learn to program

Rich is an English exchange student, although he speaks perfect Spanish. He always dresses very well and spends many hours in front of the mirror. That doesn’t mean he’s arrogant. On the contrary, he’s a very humble and charismatic person.

He’s liked by everyone and is always the center of attention. He likes that. Over the past few months we’ve spent a lot of time together and he’s become my best friend.

Actually, he was the first person I met here, or at least, the first with whom I started to become friends. In my first class I had to sit next to him. I don’t remember why we started talking, but from the first minute it seemed like I’d known him all my life.

That same day he told me that he didn’t want to live in the student residence. I still didn’t have accommodation, so I proposed that we share a house. He accepted immediately. The problem was that, between two of us, we couldn’t afford to pay the rent for an apartment. We needed a third person. We put up an ad on the university’s online bulletin board and an Asian young man contacted us within a few hours. It was Chani, who became our new friend.

Chani is also an exchange student, specifically from South Korea. He’s trying hard to learn our language, but it’s not easy for him. Sometimes I think it would be impossible for me to learn Korean.

He’s quite introverted, but that doesn’t prevent him from attending all the parties. He spends almost all day locked in his room, sleeping or playing on the computer. He only leaves his room to cook and go to the bathroom. He seems like a vampire. When night falls, he decides it’s time to activate and hang out with us.

Learn to program in Java

We’re an unconventional group of friends, but it works well for us. The coexistence is very good. We never argue and we respect each other’s space a lot. A couple of times a week we order pizza and all have dinner in our spacious living room. During the week we hardly bring guests, but we don’t feel lonely since we have each other. I couldn’t have been luckier choosing my roommates.

We love the common area of our house. It’s very large and spacious. It has huge windows and access to the terrace. We’ve gotten some very cheap sofas and even a small foosball table that entertains visitors. I had never lived in a better house than this one and the price is much cheaper than it seems.

Learn Java Easily. Introduction.

I spend almost all my day here lying down, many times in the company of Rich. He knows that I barely attend university classes and he’s worried that I won’t pass any of my exams. So he’s offered to teach me to program in Java. He knows quite a bit about the subject and explains things in a simple and clear way.

But well, I won’t ramble on anymore. Now that introductions are done, I think it’s a good time to remember Rich’s teachings. So, for the rest of the chapter, I’ll focus on reviewing and reinforcing some concepts. It will be something very basic, simply a small introduction to the world of Java and its most commonly used data types.

Introduction. Definition of OOP and presentation of data types.

The first thing that’s always mentioned when teaching Java is that it’s a type of object-oriented programming. It doesn’t matter where you get the information or who’s explaining it to you, you’ll always come across phrases like these:

“Object-oriented programming (OOP) is a programming paradigm that is based on the concept of ‘objects’. These objects are entities that combine data and related functions (called methods) into a single unit. The main idea behind object-oriented programming is to model the real world in software, which allows us to represent real-world elements and processes more accurately and efficiently in our programs.”

If you didn’t understand anything, don’t worry. If you did, congratulations, you’re one step ahead of most beginners. When you program in Java, like in many other languages, the code isn’t written linearly. That would be impractical. You have to consider that certain complex programs or applications have tens or even hundreds of thousands of lines of code.

It’s much more practical to divide that code into small groups that interact with each other. This will help us, for example, to identify and solve errors in the code much faster, to reuse already written code and avoid duplication, to divide tasks among several people easily, to carry out effective and organized code maintenance, to implement new features in the application, and ultimately, to make our lives easier.

Pay attention now, because I’m going to pose a possible exam question: tell me the four fundamental concepts on which object-oriented programming is based.

OOP is based on four fundamental concepts:

Classes: A class is like a blueprint or template that defines the common characteristics and behaviors of a particular type of object. It defines the data that an object can contain (called attributes) and the operations it can perform (called methods). For example, if we think of a “car” object, the corresponding class can define attributes such as color, model and speed, and methods such as accelerate and brake.

Objects: Objects are concrete instances of a class. Each object has its own copy of the data defined in the class, but shares the methods defined in it. For example, if we have a “Car” class, a specific object could be a red Toyota Corolla model car with a current speed of 60 km/h.

Encapsulation: Encapsulation is the concept of hiding the internal details of an object and exposing only the necessary functionality through well-defined interfaces. This is achieved by defining the class attributes as private and providing public methods (getters and setters) to access and modify these attributes in a controlled manner. Encapsulation helps keep code modular, facilitates maintenance and reduces the risk of errors.

Inheritance: Inheritance is a mechanism that allows a class (called a subclass or derived class) to inherit the attributes and methods of another class (called a superclass or base class). This allows code reuse and the creation of class hierarchies, where more specific classes can add or modify inherited behavior. For example, a “Vehicle” class can be a superclass of “Car” and “Truck” classes, which inherit their basic characteristics, but can have additional specific behaviors.

You don’t need to memorize these terms. We’ll work with them in the following topics and, little by little, they’ll become entrenched in your head. Although it’s convenient for you to become familiar with them and know of their existence. For now, we simply keep the idea that Java is an object-oriented language.

Programming is an unintuitive activity that uses many unknown terms. Little by little, everything will start to make sense, but remember that you’ll have to be consistent and not give up.

Data types and variables:

I don’t know if you like cooking, but surely you’ve tried to prepare some recipe at home. If we compare programming with cooking, we could say that data types are the ingredients, the raw material we use to create our program.

Variables, on the other hand, are the places where you store those ingredients to use them later in your recipe, like jars or bowls that contain flour, sugar, etc.

–      Data types.

In Java, data types are classified into two main groups: primitive data types and reference data types.

Primitive data types: These are the basic types built into the language. There are eight in total:

  • byte: An 8-bit integer type that can store values between -128 and 127.
  • short: A 16-bit integer that can handle values between -32,768 and 32,767.
  • int: A 32-bit integer that covers values between -2^31 and 2^31 – 1.
  • long: A 64-bit integer that can represent values from -2^63 to 2^63 – 1.
  • float: A 32-bit floating-point number, with a precision of approximately 6-7 decimal digits.
  • double: A 64-bit floating-point number, with a precision of around 15 decimal digits.
  • char: Represents a single 16-bit Unicode character.
  • boolean: Can only have two possible values: true or false.

Reference data types: Instead of containing data directly, these types store references to objects in memory. Some of the most common include:

  • String: A sequence of characters used to represent text. Unlike many languages, in Java it’s not a primitive type, but a reference type.
  • Arrays: Structures that store multiple elements of the same type contiguously in memory.

– Variables

In Java, a variable is a container that stores data that can change during program execution. I repeat: the data inside a variable can change as the program is executed. Variables have a name that is used to refer to them and a data type that specifies what type of values they can contain.

For example: int variable = 7;

In the variable above we can see that the data type is int and that its name is “variable”. In addition, we see that, at the moment, its value is 7. That value may vary during program execution, but now it’s 7.

When we declare a variable, we must do so depending on the type of data we need. Variables are constrained by the type of data they contain. A numeric variable will not be able to contain text data. Therefore, we can refer to them with the same qualification we give to data types. This causes that, on many occasions, we see both terms written indistinctly and, in the end, it becomes confusing.

It’s easier to explain with an example. Imagine that we need to create a variable called “name”. This variable will contain a text data type (String), specifically with the name Pedro. So here we have it:

String name = "Pedro";

That variable is now a “String” type variable since it contains a text data type.

There are quite a few data types and it’s good that you know them all. Although, for now and for the exercises we’re going to do, you’ll only need to know a few. As I mentioned in the previous paragraph, data types are linked to variables. Therefore, and to avoid confusion, from now on we’ll only use the term variable.

Let’s now see a slightly more extensive definition of the variables you’ll need to know:

Integer variables (int): Integer variables are used to store whole numbers. For example, we can use an integer variable to represent a person’s age or the quantity of products in inventory. In Java, we declare an integer variable using the keyword “int”, followed by the variable name and optionally, its initial value.

For example:

int age = 25;

Text variable (String): It’s used to store character sequences, that is, text. To define a String type variable, we simply use the String keyword, followed by the variable name and optionally, we assign a value. Here’s an example of how to define a String variable in Java:

String myName = “Juan”;

Floating-point variables (float and double): These variables are used to store numbers with decimals. The difference between float and double lies in the precision of the decimal number they can store. In Java, we use “float” for single-precision numbers and “double” for double-precision numbers. For example:

float height = 1.75f; double pi = 3.14159;

Boolean variables (boolean): A boolean variable can only take one of two values: true or false. These variables are useful for representing logical conditions. For example:

boolean isAdult = true;

Character variables (char): Character variables are used to store a single character. For example, we can use a character variable to represent a letter or a symbol. In Java, we declare a character variable using the keyword “char”. For example:

char initial = ‘A’;

The advantages of specifying the type of data that a variable can contain are as follows:

  1. Making our code simpler and easier to understand: if we didn’t specify the type of data that a variable can contain, the code would be almost impossible to understand for you and for other programmers. Knowing what type of data a variable expects helps to understand how it will be used in the program.
  2. Error detection: If you try to assign a value of an incorrect type to a variable, you’ll be warned about this error. This helps find errors even before the program runs, which facilitates the programming task and prevents real-time errors.
  3. Better performance: In some cases, variable typing can improve program performance, since the code can be optimized knowing the data types being used.
  4. Facilitates code maintenance: When you review or modify your code in the future, having indicated data types can help you remember how certain variables are supposed to be used. If another person reviews the code, this becomes even more useful. This facilitates maintenance and updating of the code as the project evolves.

Difference between variable assignment and declaration.

Now that we already know what data types there are, we need to know how to implement them in our code. We’ve already seen some examples in the previous paragraphs:

String myName = “Juan”; int age = 25; double pi = 3.14159; boolean isAdult = true; char initial = ‘A’;

As you can see, we always start by writing the data type we need. For example, String, int, double, boolean, char. Then, the name we’ve chosen for the variable. All of this followed by an equal sign. Subsequently, the assigned value and always ending with a semicolon.

Notice that, for the String data type, the assigned text must always be between double quotes: “Juan”. In the case of a char, the character we want in our variable must be between single quotes: ‘A’.

Now, it’s not always necessary to assign a value to our variable. We can simply declare it and use it later. For example, we start an exercise that asks us to create a String variable called name and another int variable called registration. As you can see, it’s not necessary to assign them any value.

String name; int registration;

You might think at the moment that this doesn’t make sense. Why not assign a value when creating a variable? It’s basically for reasons of order and structure. Once you start to have some fluency with the exercises, you’ll see that everything has a reason.

You might be wondering how to assign a value to a variable that has already been declared. Let’s continue with the two examples we saw two paragraphs above (name and registration). We’ll simply do it as follows:

name = “Juan”; registration = 55;

The only thing we have to do is keep in mind the type of data we want to use (String and int in the example). Then, we simply follow the normal structure we had already seen: variable name, equal sign and the value we want to add.

Variable naming convention in Java

In Java, variables follow certain naming conventions. Here I explain the main ones:

Start with lowercase letter: The name of a variable must begin with a lowercase letter. For example: age, height, width, etc.

Use camelCase: This means that if the variable name consists of more than one word, the first letter of each word after the first is written in uppercase, without spaces or hyphens. For example: currentAge, fullHeight, totalWidth, etc.

Meaningful and descriptive: Try to use names that indicate what is being represented. For example, instead of x or y, you could use age or accountBalance.

Avoid special characters: Only letters, numbers and the underscore _ are allowed. Other characters such as spaces, hyphens (-), periods (.), among others, should not be used in the name of a variable.

Don’t use Java keywords: Avoid using words reserved by Java (such as int, float, while, etc.) as variable names, if you do, there may be errors in your code later.

Don’t use accents or special characters: Java doesn’t allow the use of accents or special characters in variable names.

By following these rules, your programs will be easier to read and understand for you and for other people who read your code.

Summary of what we’ve learned

In this first chapter, you’ve begun your foray into the world of Java programming.

Congratulations! Not everyone dares to take on this challenge. Now it can be said that you have a general idea of how Java is structured and what the term “object-oriented programming” (OOP) means.

In addition, you already know what the four fundamental pillars of OOP are: classes, objects, encapsulation and inheritance. If any of these concepts isn’t clear to you yet, don’t worry, it’s normal. I don’t think many people understand everything the first time. Being realistic, we haven’t delved much into the topic and there are still many questions to be resolved. Although from this point, learning new concepts will be much easier for you.

By this point, you probably feel more comfortable talking about data types and variables. These are more concrete concepts and easy to grasp. When we start with the practical part, they’re going to be indispensable in all our exercises. We know that there are primitive and reference data types. In addition, we’ve emphasized the importance that data type specification has in Java. This achieves improved clarity, error detection and facilitates code maintenance.

We’ve also had time to learn what the difference is between variable assignment and declaration.

Although for now it’s not a priority in your learning, you’ve been able to take a look at the naming conventions in Java for naming variables. Soon you’re going to start working with variables and you’ll have to create your own code, in which you’ll have total freedom to choose variable names. My advice is that you try to follow this convention so that you get used to following good practices.

As a summary, we’ll say that you’ve already taken your first step in the world of programming. There’s still a long way to go; I understand that theory is sometimes a bit boring, but it’s totally necessary. This introduction will serve you to establish a solid foundation with which to understand the more advanced concepts that will be addressed in the following chapters.

I’m sure you’re eager to get to work and start writing your own programs. If I’m honest with you, it’s my favorite part. So don’t worry, because we’ll soon start solving exercises and using the theoretical knowledge we’re acquiring.

Did you like it? Don’t keep it to yourself — share it like juicy gossip! 😏