In this chapter, we are going to talk about Java, one of the pillar languages of object-oriented programming, in which the examples seen in this series of chapters will be presented.
We will talk about its history, understand how it works, why we chose it, and prepare you to write your first program.
# A Bit of History and Philosophy
Java was originally conceived by Sun Microsystems in 1995 and has since been adopted as one of the world's most popular programming languages.
In 2010, Oracle Corporation acquired Sun Microsystems, taking Java to new heights. Its motto "Write once, run anywhere" encapsulates its philosophy of portability and efficiency, allowing the same code to work on different platforms without modifications.
# Why Choose Java?
Java (along with C#) is one of the pioneering and most popular object-oriented programming languages; it continues to be of great importance and is highly used within the industry today.
Java is chosen for several reasons:
-
Portability: Thanks to the JVM (Java Virtual Machine), Java code is portable and can run on any operating system.
-
Object-Oriented: It promotes a clean and modular design, facilitating software maintenance and scalability.
-
Security and Robustness: It manages memory automatically and protects against many common vulnerabilities found in other languages.
-
Rich Ecosystem: A wide range of libraries and frameworks for almost any imaginable programming task.
# Compiled vs. Interpreted: The Role of the JVM
Java is both compiled and interpreted; the JVM (Java Virtual Machine) is a virtual machine that allows us to execute Java code. It is a program that is installed on top of the operating system and runs our program.
First, the source code is compiled into bytecode by the Java compiler, and then, at runtime, the JVM interprets and executes this bytecode.
This double stage allows for exhaustive verification and optimization, which contributes to Java's efficiency and portability, as the compiled code is independent of the operating system; it is the same for everyone because it executes on the JVM.
The JVM is responsible for interacting with the Operating System.
# Installing the JDK (Java Development Kit)
The JDK is a necessary development kit for writing and executing Java programs. It includes the JRE (Java Runtime Environment) and a set of tools for Java development.
-
Step 1: Download the JDK
Visit the official website of Oracle or an OpenJDK distribution and download the most recent version of the JDK for your operating system.
-
Step 2: Installation
Run the downloaded installer and follow the instructions. Make sure to select an installation PATH that you remember, as you will need to reference it later.
-
Step 3: Configuring the PATH
To be able to run Java commands from the command line, you need to add the location of the Java binary to the system PATH.
-
On Windows: Go to System Settings >
Environment Variables and edit the 'Path' system variable to include the path to
the Java binary (e.g.,
C:\Program Files\Java\jdk-11.0.1\bin). -
On macOS/Linux: Edit your profile file
(.bash_profile, .bashrc, .zprofile, etc.) and add
export PATH=/usr/lib/jvm/jdk-11.0.1/bin:$PATH, replacing the path with your specific installation path.
-
On Windows: Go to System Settings >
Environment Variables and edit the 'Path' system variable to include the path to
the Java binary (e.g.,
-
Step 4: Verification
Open a terminal or command line and type
java -versionandjavac -version. If the installation was successful, you should see the installed versions of the JRE and the Java compiler, respectively.
# IDE (Integrated Development Environment)
An IDE will provide you with an interface for writing, debugging, and executing your code. Some popular ones include:
-
Eclipse: The most widely used IDE by Java developers.
-
IntelliJ IDEA: Known for its ergonomics and intelligent features.
-
NetBeans: Another free and open-source IDE.
Choose one, download it, and install it from its official website.
# Java Syntax
Java is a rich and powerful programming language with many elements in its syntax. Below, I present the basic elements you will need to know to start programming in Java.
1. Classes
Everything in Java is associated with classes and interfaces. A class is a "blueprint" for creating objects (specific instances of the class).
public class MyClass {
// Attributes, methods, etc.
}
2. Methods
A method is a block of code that executes when invoked. A Java program can have many methods.
public void myMethod(){
// Code to execute
}
3. Variables
Variables are containers for storing data. In Java, each variable must be declared with a data type.
int myNumber = 5; // Integer variable
4. Data Types
Java is a strongly typed programming language. Some basic types include:
- -
int: For integers. - -
double: For decimal numbers. - -
boolean: For true/false. - -
char: For individual characters. - -
String: For text strings.
5. Operators
Java uses operators to perform operations on variables and values. Some common examples include:
- -
+: Addition - -
-: Subtraction - -
*: Multiplication - -
/: Division - -
%: Modulo - -
==: Equal to - -
!=: Not equal to
6. Flow Control
Flow control allows your program to make decisions and execute code conditionally.
If Statement:
if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if condition2 is true
} else if (condition3) {
// code to execute if condition3 is true
/// ...
} else {
// code to execute if no previous condition is true
}
Switch Statement:
switch (expression) {
case x:
// code to execute if expression is equal to x (expression == x)
break; // does not continue evaluating other cases
case y:
// code to execute if expression is equal to y (expression == y)
break; // does not continue evaluating other cases
default:
// code to execute if no previous cases are met
// also executes if it didn't exit via some break
}
7. Loops
Loops are used to execute a block of code multiple times.
For Loop:
for (int i=0; i < 10; i++) {
// code to execute in each iteration
}
While Loop:
while (condition) {
// code to execute while the condition is true
}
8. Arrays
Arrays in Java are containers that store multiple elements of the same type.
int[] myArray = {1, 2, 3, 4, 5};
9. Comments
Comments are used to explain code and can help when revisiting the code in the future. They are not executed by the program.
- - Single-line comments:
// This is a comment - - Multi-line comments:
/* This is a multi-line comment */
10. Member Access and Access Modifiers
- Member access:
public,private, andprotecteddetermine the visibility of classes, variables, and methods. - Non-access modifiers: Like
static, which indicates that a member belongs to the class rather than an instance of the class.
11. Constructors
A constructor is a special method used to initialize objects.
public class MyClass {
// attributes
// Constructor
public MyClass() {
// code to execute during object creation
}
}
12. Inheritance
Inheritance allows one class to acquire the fields and methods of another class.
public class MySubclass extends MyClass {
// Class that inherits from MyClass
}
13. Interfaces and Abstract Classes
Interfaces and abstract classes are used to achieve abstraction in Java.
Interface:
interface MyInterface {
public void myMethod();
}
Abstract Class:
abstract class MyClass {
public abstract void myMethod(); // abstract method
}
14. Exceptions
Exceptions are events that occur during program execution and alter the normal flow; they are caught using try/catch statements.
try {
// code that may generate an exception
} catch (ExceptionType1 e) {
// code to handle the exception
} catch (ExceptionType2 e) {
// code to handle the exception
// ...
} catch (ExceptionTypeN e) {
// code to handle the exception
}
15. Collections in Java
Collections are data structures used to store and organize multiple elements. Java provides a robust collections framework for working with different types of data sets.
Collections Framework
The Java collections framework
provides several interfaces and classes for storing and manipulating groups of
objects. These interfaces and classes are mainly found in the java.util
package.
Interfaces and implementations
A variable (or attribute) is declared with the interface type, and when created, it is assigned a concrete implementation type.
-
List: The simplest interface, an ordered collection (list) that can contain duplicate elements. It allows positional access to elements.
- Implementation examples:
ArrayList,LinkedList. -
Set: A Set interface. This collection does not contain duplicate elements.
- Implementation examples:
HashSet,LinkedHashSet,TreeSet. -
Map: A map-type interface (key, value). This object maps keys to values. A key cannot be duplicated, but it can have one or more values.
- Implementation examples:
HashMap,LinkedHashMap,TreeMap. -
Queue: A collection designed for FIFO (First-In-First-Out) operations.
- Implementation examples:
PriorityQueue,LinkedList.
Generics
Collections are often used
together with Generics, which allow defining collections with a specific data type.
For example, List<String> defines a list of elements that are
text strings.
List Usage Example
// names is of type List (Interface)
// when creating it, I assign a concrete type, ArrayList
List<String> names = new ArrayList<>();
names.add("Ana");
names.add("Luis");
// List allows duplicate elements
names.add("Ana");
for (String name : names) {
System.out.println(name);
}
Set Usage Example
Set<String> names = new HashSet<>();
names.add("Ana");
names.add("Luis");
names.add("Ana");
// Set does not allow duplicate elements, it will not add it
for (String name : names) {
System.out.println(name);
}
Map Usage Example
Map<String, Integer> ages = new HashMap<>();
ages.put("Ana", 25);
ages.put("Luis", 30);
ages.put("Ana", 28); // Keys are unique. This overwrites "Ana"'s value.
for (Map.Entry<String, Integer> entry : ages.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
Queue Usage Example
Queue<String> queue = new LinkedList<>();
queue.offer("First");
queue.offer("Second");
queue.offer("Third");
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}
The basic elements of Java syntax mentioned here form the backbone of any Java program.
Throughout the chapters, we will see what each one means.
# Your First Java Program: "Hello World"
Once you have configured your environment, it's time to write your first program.
-
Step 1: Create a New File
Open your IDE, create a new project, and then a new file called
HelloWorld.java. -
Step 2: Write the Code
Copy the following code into your file.
public class HelloWorld { // Class // public static void main is the entry point of every program public static void main(String[] args) { System.out.println("Hello, world!"); } } -
Step 3: Compile and Run
Use your IDE's tools to compile and run the program. You should see "Hello, world!" printed in the output.
# Understanding the Code
-
Class:
public class HelloWorlddefines a public class namedHelloWorld. In Java, all code must be inside a class. -
Main Method:
public static void main(String[] args)defines the main method, the entry point for any Java program. When you run the program, the JVM calls this method. -
Print to Console:
System.out.println("Hello, world!");prints a line of text to the console. It is a way to show data to the user.
# Troubleshooting Common Issues
Don't be discouraged if you encounter errors; they are part of learning. Always analyze the error, it's likely one of the following:
-
JDK Installed Correctly: Make sure that both
javaandjavacare available on your command line or terminal. -
Code Structure: Verify that your code structure exactly matches the example and that the filename matches the class name.
-
IDE Configuration: Make sure your IDE is configured to use the JDK you installed.
-
"Google it": "Googling" is what will prevent "reinventing the wheel." The Java community is huge and always ready to help; on sites like Stack Overflow, you will find many common problems.
# Exploring Further
Once you feel comfortable with the fundamentals, don't stop. Java is very powerful.
Experiment with more advanced concepts like threads, collections, and GUIs.
Dive into frameworks like Spring to see how Java is handled in enterprise environments.
# Conclusions
Java is not just a language; it is an adventure in the world of programming. With each line of code, you are participating in a story that has been written by millions of developers over decades.
So go ahead, configure your environment, write your code, and be part of the global community that continues to take Java to new horizons.