Java is a strongly typed, object-oriented programming language used for building everything from mobile apps to enterprise servers. Most beginners struggle with the distinction between the JDK and JRE, but remember that the JDK is the full toolkit needed to write code, while the JRE only runs it.
What are the Java Basic Data Types?
Java uses primitive types to store simple values and reference types for complex objects. You must declare the type of every variable before using it. This strictness prevents errors where a program might try to treat a word as a number.
The most common primitive types include int for whole numbers, double for decimals, and boolean for true or false values. A char stores a single character, like 'A', and must be wrapped in single quotes. For text, you use the String class, which is a reference type and requires double quotes.
Memory usage varies by type. An int typically takes 32 bits of memory, while a long takes 64 bits. If you are building a system that handles millions of small numbers, using byte (8 bits) or short (16 bits) can save space. However, for most general applications, int and double are the standard choices.
A common misconception is that float and double are interchangeable. While both handle decimals, double has twice the precision of float. If you are calculating financial data or scientific measurements, always use double or the BigDecimal class to avoid rounding errors that occur with binary floating-point math.
How do Java Control Structures Work?
Control structures decide which part of your code runs based on specific conditions. The if statement is the primary tool for decision making. You place a boolean expression inside parentheses, and if it evaluates to true, the code block inside the curly braces executes.
When you have many possible paths, a switch statement is cleaner than multiple if-else blocks. It compares a single variable against a list of constant values. Remember to include a break statement after each case; otherwise, the program will continue executing the next case regardless of whether the value matches. This is known as fall-through behavior.
Loops allow you to repeat a task multiple times. The for loop is best when you know exactly how many times to repeat a block, such as iterating through a list of 10 items. The while loop is better when you want to repeat a task until a certain condition changes, such as waiting for a user to press a specific key.
The do-while loop differs from the standard while loop because it executes the code block at least once before checking the condition. This is useful for menus where you want to show the options to the user first and then check if they want to exit.
What is the Difference Between Class and Object?
A class is a blueprint or a template. It defines what data a thing has and what it can do. An object is a specific instance of that class. For example, if you have a class called Carro (Car), it might define that all cars have a color and a brand. An object would be a specific red Toyota.
To create an object, you use the new keyword. This allocates memory for the object and calls the constructor method. The constructor is a special method that has the same name as the class and no return type. It initializes the object's state when it is first created.
Encapsulation is a core rule in Java. You should keep your class variables private and provide public getter and setter methods to access or change them. This prevents external code from putting the object into an invalid state, such as setting a car's speed to a negative number.
Inheritance allows one class to take on the properties of another using the extends keyword. A Cachorro (Dog) class can extend an Animal class. This means the dog inherits all the general traits of an animal but can add its own specific behaviors, like barking. This reduces code duplication across your project.
How do Java Collections and Arrays Differ?
Arrays are fixed-size containers. Once you create an array of 5 integers, you cannot add a 6th. This makes arrays very fast and memory-efficient, but inflexible. You access elements using an index starting at 0. If you try to access index 5 in a 5-element array, Java throws an ArrayIndexOutOfBoundsException.
Collections, specifically the ArrayList, provide a dynamic alternative. An ArrayList grows automatically as you add items. While it is slightly slower than a raw array due to this flexibility, it is the preferred choice for most lists of data.
For storing unique items where order does not matter, use a HashSet. It prevents duplicate entries automatically. If you need to store pairs of data, such as a username and an email address, use a HashMap. This allows you to find a value quickly using a unique key.
When choosing between these, consider the nature of your data. Use an array if the size is constant and performance is critical. Use an ArrayList for general lists, a HashSet for unique sets, and a HashMap for key-value lookups. Labels and method names for these collections may differ slightly depending on the version of the JDK you have installed.
How is Error Handling Managed with Try-Catch?
Java uses exceptions to handle runtime errors without crashing the entire program. An exception is an event that disrupts the normal flow of instructions. For example, dividing by zero or trying to open a file that does not exist triggers an exception.
You wrap risky code in a try block. If an error occurs, Java stops executing the try block and jumps to the catch block. Inside the catch block, you define how to handle the error, such as printing a message to the user or logging the event to a file.
The finally block is an optional section that runs regardless of whether an exception was thrown or caught. This is the correct place to close resources, such as database connections or file streams. If you open a file in the try block and an error occurs, the finally block ensures the file is closed so it does not leak memory.
You can also create your own exceptions by extending the Exception class. This allows you to define business-specific errors, such as SaldoInsuficienteException (InsufficientBalanceException) for a banking app. This makes your code more readable because the exception name explains exactly what went wrong in the context of your application.
What are the Java Syntax Basics for PT-BR Learners?
While the Java language keywords are always in English (like public, static, void), you can use Portuguese for your own identifiers. Your class names, variable names, and method names can be in Portuguese to make the logic easier to follow during the learning phase.
For example, instead of int userAge = 25;, you can write int idadeUsuario = 25;. However, professional environments usually prefer English for all identifiers to ensure the code is accessible to developers worldwide. It is a good habit to learn the English terms for common programming concepts like loop, string, and array.
When naming your classes, always use PascalCase (e.g., ContaBancaria). For variables and methods, use camelCase (e.g., calcularSaldoTotal). This naming convention is a standard across the Java community and helps other developers understand your code structure at a glance.
To print text to the console, use System.out.println("Texto aqui");. The println method adds a new line after the text. If you want to print something without moving to the next line, use System.out.print("Texto aqui");. This is useful when building a prompt that stays on the same line as the user's input.