Java Core Concepts: Data Structures, I/O, and More

Classified in Computers

Written on in English with a size of 7.83 KB

Java Programming Fundamentals

This document provides a quick reference to fundamental Java programming concepts, including object-oriented programming basics, common data structures like ArrayLists, handling user input, string manipulation, type conversion, and file input/output operations.

Object-Oriented Programming: The Persona Class

Below is a basic definition of a Persona class, illustrating fields and a constructor. In a complete implementation, you would also include getter and setter methods for each field.

public class Persona {
    private String nombre;
    private int ojos;
    private int piernas; // Added for completeness based on constructor
    private int brazos; // Added for completeness based on constructor

    public Persona() { }

    public Persona(String nombre, int ojos, int piernas, int brazos) {
        this.nombre = nombre;
        this.ojos = ojos;
        this.piernas = piernas;
        this.brazos = brazos;
    }

    // Example getters and setters (others would be here)
    public int getBrazos() { return this.brazos; }
    public void setBrazos(int brazos) { this.brazos = brazos; }
    // Additional getters and setters for nombre, ojos, piernas
}

Mastering Java ArrayLists

The ArrayList class is a resizable array implementation of the List interface. It's part of the Java Collections Framework and is widely used for dynamic collections of objects.

ArrayList Initialization and Basic Usage

Here's an example demonstrating how to initialize an ArrayList of Persona objects and perform basic operations like adding elements and accessing them.

import java.util.ArrayList;
import java.io.IOException;

public class Ejemplo_arraylist {
    public static void main(String[] args) throws IOException {
        ArrayList<Persona> personas = new ArrayList<Persona>();
        // Persona p = new Persona(); // Example of creating a single Persona object

        // Adding 10 default Persona objects to the ArrayList
        for (int i = 0; i < 10; i++) {
            personas.add(new Persona());
        }

        // Modifying and accessing an element
        personas.get(0).setBrazos(1000);
        System.out.println(personas.get(0).getBrazos());
    }
}

Core ArrayList Methods

These are some of the most frequently used methods when working with ArrayList:

  • size(): Returns the number of elements in the list.
  • add(X): Appends the specified element to the end of this list.
  • add(position, X): Inserts the specified element at the specified position in this list.
  • get(position): Returns the element at the specified position in this list.
  • remove(position): Removes the element at the specified position in this list.
  • remove(X): Removes the first occurrence of the specified element from this list, if it is present.
  • clear(): Removes all of the elements from this list (empties the array).
  • set(position, X): Replaces the element at the specified position in this list with the specified element.
  • contains(X): Returns true if this list contains the specified element, false otherwise.
  • indexOf(X): Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

Enhanced For Loop for Collections

The enhanced for loop (also known as the for-each loop) provides a simpler way to iterate over elements in collections like ArrayList.

for(Humano h1 : lista) {
    // Code to execute for each Humano object in 'lista'
}

Handling User Input with Java Scanner

The Scanner class is used for obtaining input from the user. It can parse primitive types and strings using regular expressions.

import java.util.Scanner;

Scanner entrada = new Scanner(System.in);

Essential Scanner Methods

Common methods for reading different types of input:

  • nextLine(): Reads the rest of the current line.
  • nextInt(): Reads the next token as an int.
  • (Other methods like next(), nextDouble(), etc., are also available)

String Manipulation in Java

Strings are fundamental in Java, and the String class provides numerous methods for manipulating text data.

Key String Methods

Here are some important methods for working with strings:

  • cadena.length(): Returns the length of the string.
  • cadena.substring(startPos, endPos): Returns a new string that is a substring of this string.
  • charAt(pos): Returns the char value at the specified index.
  • indexOf('pepe'): Returns the index within this string of the first occurrence of the specified substring.
  • split(';'): Splits this string around matches of the given regular expression.

Java Type Conversion: Integers

Converting between string representations and primitive integer types is a common task in Java.

Integer.parseInt(string_value); // Converts a String to an int
Integer.toString(integer_value); // Converts an int to a String

Java File Input/Output (I/O) Operations

Java provides robust capabilities for reading from and writing to files, essential for data persistence.

File I/O Imports and Setup

To perform file operations, you typically need to import classes from the java.io package.

import java.io.*;

Writing Data to Files

The EscribirFichero method demonstrates how to write a string to a file, appending to it if the file already exists. It also includes a conditional file renaming operation.

public static void EscribirFichero(String s, String n) throws IOException {
    File f1 = new File("temporal.txt");
    try {
        FileWriter fw = new FileWriter(f1, true); // true for append mode
        fw.write(s);
        if (fw != null) {
            fw.close();
        }
        // This condition 'vuelta == 4' is context-dependent and not defined here.
        // It suggests a specific application logic for renaming the file.
        // Assuming 'vuelta' is a variable accessible in this scope.
        // if (vuelta == 4) {
        //     File f2 = new File(n + ".txt");
        //     f1.renameTo(f2);
        // }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Reading Data from Files

The LeerFichero method illustrates how to read content from a file line by line. It checks if the file exists before attempting to read.

public static String LeerFichero(String n) throws IOException {
    String s = "";
    File f = new File(n + ".txt");
    if (f.exists()) {
        try {
            FileReader fr = new FileReader(f);
            BufferedReader br = new BufferedReader(fr);
            while ((s = br.readLine()) != null) {
                // The 'decodificar(s)' method is context-dependent and not defined here.
                // It implies some processing of each line read from the file.
                // decodificar(s);
            }
            if (br != null) {
                br.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return s; // Note: This will only return the last line read, or an empty string.
              // A more typical implementation would return a List<String> or process lines internally.
}

Related entries: