Saltar al contenido principal
ProductosHerramientas de escritorioTASTECADRevisión de planosTASTEFILESGestión de archivosTASTEFTPTransferencia de archivosTASTESSHEspacio de trabajo remotoTASTEZIPCompresión y extracciónTASTEWINMGestión de archivosHerramientas para desarrolladoresTASTECODEEntorno de desarrollo integrado para RustTASTESTUDIOEntorno integrado de desarrollo y pruebasTASTEETLIntegración de datos (ETL)ServidoresTASTEREMOTEServidor de escritorio remotoTASTEGEOServidor geoespacialTASTEMAILEspacio de trabajo de correoInversiónTASTESTOCKAplicación de escritorio de trading automático de accionesEmpezarDescargasDocumentaciónComprarTodos los productos
Marketplace
Noticias
TecnologíaNoticiasNoticias de desarrollo de hoyDocumentaciónLenguajes de programaciónRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps y escritorioTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos esencialesAlgoritmos avanzadosAlgoritmos prácticos
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparateGuía de la comunidad
ColaboraTransferencia técnicaDesarrollo de sitio webDesarrollo de app de escritorioCanal de lanzamiento y pagosSocio de ventasContacto
ServiciosEscritorio remotoPaquetes de instalación a medida
TASTEDEV
Productos

Herramientas de escritorio

TASTECADAbre planos complejos con ligerezaTASTEFILESSolo los archivos que necesitas, lo más rápido posibleTASTEFTPEl camino más limpio para tus archivosTASTESSHEntre tu servidor y tú, una conexión más sólidaTASTEZIPComprime más rápido, descomprime más seguroTASTEWINMUn gestor de archivos de dos paneles pensado para el teclado

Herramientas para desarrolladores

TASTECODEEdita, compila, depura y prueba apps de Rust en una sola ventanaTASTESTUDIODe la edición a las pruebas remotas y las correcciones con IA aprobadasTASTEETLMueve datos viendo sus valores

Servidores

TASTEREMOTEUn escritorio remoto que funciona en tu propio servidorTASTEGEOUn servidor geoespacial compatible con GeoServer, reconstruido en RustTASTEMAILRecupera el control de tu correo

Inversión

TASTESTOCKTrading automático de acciones según las reglas que tú defines: cuándo y qué

Empezar

DescargasÚltimas versiones de cada productoDocsCómo usar cada productoComprarSuscripciones y licencias perpetuasTodos los productosTodos los productos de un vistazo
Todos los productos
MarketplaceNoticias
Tecnología

Noticias

Noticias de desarrollo de hoyAnuncios oficiales de lenguajes, frameworks, GitHub e IADocumentaciónGuías de lenguajes, frameworks y algoritmos

Lenguajes de programación

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps y escritorioTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálisis de complejidad · Ordenamiento · Búsqueda · Estructuras de datos básicas · Árboles y montículosAlgoritmos esencialesRecorrido de grafos · Camino mínimo y árbol generador mínimo · Programación dinámica · Algoritmos voraces · Divide y vencerás · Backtracking (vuelta atrás)Algoritmos avanzadosAlgoritmos de cadenas · Matemáticas y teoría de números · Manipulación de bits · Árboles de segmentos · Union-FindAlgoritmos prácticosEstrategia para entrevistas de código · Caché LRU · Limitación de tasa · Hashing consistente
Toda la documentación de desarrollo
Comunidad
ProyectosDescubre creadores y su trabajoRegistros de desarrolloDecisiones y aprendizajesPromptsInstrucciones reutilizablesProblemas con herramientas de IAProblemas y alternativas de Claude, Codex, GeminiEscaparateResultados terminadosGuía de la comunidadCómo construimos en abierto
Colabora
Transferencia técnicaApps nativas con Rust y eguiDesarrollo de sitio web10 idiomas, cuentas, documentación y descargasDesarrollo de app de escritorioRust y egui, sin WebViewCanal de lanzamiento y pagosFirma, MSI, deb, rpm, AppImage, hashesSocio de ventasRecomiéndanos y gana el 30 %ContactoDesarrollo, alianzas e inversión
Servicios
Escritorio remotoAccede a tu ordenador desde el navegadorPaquetes de instalación a medidaSolo lo necesario, ajustes precargados
Comprar
ES
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Iniciar sesión
Iniciar sesión
TASTEDEV

De pequeñas herramientas a un mejor desarrollo.

support@tastedev.netApoyar a TASTEDEV
ProductosLínea de productosComprarDocsDescargasMarketplaceSoporte
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparate
PolíticasQuiénes somosPolítica de privacidadTérminos de servicioCondiciones de suscripciónReembolsosNormas de la comunidad
CuentaIniciar sesiónRegistrarse
Visitantes
Hoy
Ayer
Vistas totales
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro mercantil
853-44-00368
Dirección
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Teléfono
+82-10-4404-1523
Correo electrónico
whitecalvin@tastedev.net
Responsable de privacidad
CHOI YOUNG GU

© 2026 TASTEDEVLa información de los productos se basa en fuentes de desarrollo verificadas.Publicado · en mejora

Documentación de Java
Java
Getting StartedSyntax BasicsTypes and DataModules and PackagesErrors and TestingKey Concepts
Debates

Guía de Java · 2/6

Syntax Basics

Por ahora, este capítulo solo está disponible en inglés.

Java is statically typed, and all code lives inside classes. Statements end with semicolons and blocks are wrapped in braces. This chapter covers classes and the main method, variables and var, methods, branching and loops, switch expressions, and working with strings.

Classes and main

A class bundles state (fields) with behavior (methods). A runnable program needs one class with a main method. The static keyword means the method belongs to the class itself, so it can be called without creating an object first.

package com.example.basics;

public class Greeter {
    private final String greeting; // field

    public Greeter(String greeting) { // constructor
        this.greeting = greeting;
    }

    public String greet(String name) { // instance method
        return greeting + ", " + name;
    }

    public static void main(String[] args) {
        Greeter greeter = new Greeter("Hello");
        System.out.println(greeter.greet("Java"));
    }
}

There are four access levels: public (visible everywhere), protected (same package plus subclasses), package-private (no modifier at all), and private (only inside the class). The usual habit is to keep fields private and expose only the methods callers actually need.

Variables and var

You declare a variable with a type and a name. For local variables you can write var and let the compiler infer the type from the initializer. This is not dynamic typing: the inferred type is fixed for the life of the variable. Mark a variable final to prevent reassignment.

int count = 10;
double ratio = 0.75;
boolean done = false;
String title = "Java";

var names = new java.util.ArrayList<String>(); // inferred as ArrayList<String>
names.add("Duke");

final int max = 100;
// max = 200; // compile error: cannot assign a value to final variable

var only works for local variables, not for fields or method parameters. It shines when the type is long and already obvious from the right-hand side.

Methods

A method declaration lists a return type, a name, and parameters; use void when nothing is returned. Overloading lets you define several methods with the same name as long as their parameter lists differ. Java always passes arguments by value; for objects, the value being copied is the reference.

public class MathUtil {
    static int add(int a, int b) {
        return a + b;
    }

    static double add(double a, double b) { // overload
        return a + b;
    }

    static int sum(int... values) { // varargs
        int total = 0;
        for (int v : values) total += v;
        return total;
    }
}

Branching and loops

The usual suspects are all here: /, the classic , the enhanced for-each loop, , and . Use to leave a loop early and to skip to the next iteration.

¿Tienes preguntas sobre este capítulo?
Capítulo anteriorGetting StartedCapítulo siguienteTypes and Data
if
else
for
while
do-while
break
continue
int score = 82;
if (score >= 90) {
    System.out.println("A");
} else if (score >= 80) {
    System.out.println("B");
} else {
    System.out.println("C");
}

for (int i = 0; i < 3; i++) {
    System.out.println("i = " + i);
}

for (String lang : java.util.List.of("Java", "Kotlin", "Scala")) {
    if (lang.equals("Kotlin")) continue;
    System.out.println(lang);
}

int n = 3;
while (n > 0) {
    n--;
}

Switch expressions

The old switch statement falls through to the next case whenever you forget a break. The arrow form (->) never falls through and produces a value, so you can assign or return it directly. When a case needs several statements, use a block and hand back the result with yield.

enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }

static String kind(Day day) {
    return switch (day) {
        case SAT, SUN -> "weekend";
        case MON, TUE, WED, THU, FRI -> "weekday";
    };
}

static int length(Object value) {
    return switch (value) {
        case String s -> s.length();
        case java.util.List<?> list -> list.size();
        case null -> 0;
        default -> {
            String text = value.toString();
            yield text.length();
        }
    };
}

When every enum constant is covered, no default branch is needed. The second example uses type patterns: each case checks the runtime type and binds the value to a new variable in one step.

Strings

String objects are immutable; every method that seems to modify a string actually returns a new one. Compare contents with equals, never ==, because == only checks whether two references point at the same object.

String s = "  Hello, Java  ";
String trimmed = s.strip(); // "Hello, Java"
boolean same = trimmed.equals("Hello, Java"); // true
String upper = trimmed.toUpperCase();
String[] parts = trimmed.split(", "); // ["Hello", "Java"]
String message = "%s has %d chars".formatted(trimmed, trimmed.length());

String json = """
    {
      "name": "Duke",
      "lang": "Java"
    }
    """; // text block

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) sb.append(i).append(',');
System.out.println(sb); // 0,1,2,

When you build up a string piece by piece inside a loop, a StringBuilder avoids creating a pile of throwaway objects. For multi-line content, text blocks delimited by triple quotes keep the text readable without escape sequences.

Summary

  • All code lives in classes, and execution begins at main.
  • Local variables can use var for inference, but their types remain static.
  • Arrow-style switch expressions return a value, never fall through, and support type patterns.
  • Strings are immutable: compare them with equals and build large ones with StringBuilder.

0 comentarios

Comentarios destacadosMás recientes primero

Iniciar sesión · Inicia sesión para dejar un comentario.