Curso de Jetbrains y mi traduccion del curso de JAVA
Practicas de java: Curso de JAVA en ingles y posteriormente traducido por mi.
Learn Java while building real functional applications. You’ll get to choose a project that suits your level and will get all the necessary knowledge to complete it. Completing the full track will prepare you to deal with various tasks related to desktop application or web development in Java. While progressing through different projects of this track you can learn to:
Understand the syntax of Java and write well readable and efficient code.
Work with professional development tools and GitHub.
Apply the principles of object-oriented programming widely used in commercial development.
Simplify your application design with functional programming.
Use collections to effectively process data in your application.
Use multicore processing to optimize the speed of your app.
Use the Swing library for desktop development.
Build an efficient web application with SpringBoot.
Work with data formats like JSON and XML.
Work with databases.
(Aprende Java mientras construyes aplicaciones reales funcionales. Puedes elegir un proyecto de acuerdo a tu nivel y tendras todo el conocimiento para completarlo. Completar el camino completo te preparará para manejar tareas varias relacionadas a aplicaciones de escritorio o desarrollo web en Java. Mientras progresas a través de diferentes proyectos de este camino aprenderas: a entender la sintaxis en Java y escribir un codigo eficiente y leible; a trabajar con herraminetas profesionales de desarrollo y GitHub; a aplicar los principios de programacion orientada a objetos usada en desarrollo comercial; a simplificar el diseño de tu aplicacion con programcion funcional; a usar procesamiento multinucleo para optimizar la velocidad de tu app; a usar la libreria swing para desarrollo de escritorio; a crear una aplicacion web eficiente con springboot; a trabajar con formatos de data como JSONy XML; y a trabajar con bases de datos)
Project: Simple Tic-Tac-Toe
About:
Everybody remembers this paper-and-pencil game from childhood: Tic-Tac-Toe, also known as Noughts and crosses or Xs and Os. A single mistake usually costs you the game, but thankfully it is simple enough that most players discover the best strategy quickly. Let’s program Tic-Tac-Toe and get playing!
primer desafio:
You have a guest list of the people who registered their stay at the hotel. There are 4 rooms in the hotel: 1 single room, 2 double rooms and 1 family room for three guests. The guest list consists of 4 lines. Each line contains the name or the names of the guests registered together in one room.
Read the names of the registered guests from the list and output each name in a separate line and in reverse order starting with the last registered guest. Note that the order of the guests registered in each room is undefined.(Proyecto un simple tateti. Sobre esto: todos recordamos este juego de la niñez que se jugaba con papel y lapiz: tateti, tambien conocido como ceros y cruces y X y 0. Un simple error podia costarte el juego pero es suficiente para que la mayoria de los jugadores descubran la mejor estrategia rapidamente. Programemos tateti y juguemos.
Primer desafio: Tienes una lista de invitados de la gente que registró su estadia en el hotel. Hay 4 cuartos en el hotel: 1 cuarto simple, 2 cuartos dobles y 1 cuarto familiar para tres invitados. La lista de invitados consiste de 4 lineas. Cada linea contiene el nombre o los nombres de los invitados registrados juntos en un cuarto.Lee los nombre de los invitados registrados de la lista y muestra cada nombre en una linea separada y en orden reverso empezando por el ultimo invitado registrado. Nota que el orden de los invitados registrados en cada cuarto es indefinido.)
Sample Input 1:(muestra de datos ingresados 1)
Jane Kate
John
Mary Susan Paul
Boris Ann
Sample Output 1:(muestra de datos procesados)
// Ann
// Boris
// Paul
// Susan
// Mary
// John
// Kate
// Jane
// 3desafio
// IntelliJ IDEA can do something with context near the cursor.(Intellij IDEA puede hacer algo con el contexto cerca del cursor)
// How to ask for it?(como pedirlo?)
// Select one option from the list(selecciona una opcion de la lista)
// Using Alt+Enter keystroke
// Using the Change to action
// Going to File | Settings
// Creating a new file
// Creating a new project
// 4desafio
// Modify this program to output
// Cats are robots!
// desafio
// Remember the conventions for naming variables? Make the variable CACTUS@HEIGHT not only syntactically correct, but also compliant with those recommendations. Enter the result.(recuerdas las convenciones para nombrar variables? hace a la variable CACTUS@HEIGHT no solo sintacticamente correcta sino sigue las recomendaciones. Ingresa el resultado)
// What you’ll do in this stage 1/5: Welcome to the battlefield!
// Description
// Tic-tac-toe is known all over the world. Each country may have its own version of the name, sometimes the rules are different, but the essence of the game remains the same. Below are the main rules that may be familiar to you since childhood.(Tateti es conocido en todo el mundo. Cada pais puede tener su version del nombre, a veces las reglas son distintas, pero la esencia del juego se mantiene. Mas abajo estan las reglas principales que pueden ser familiares para vos de tu niñez.)
// Tic-tac-toe is a game played by two players on a 3x3 grid. One of the players is ‘X’, and the other player is ‘O’. X plays first, then O takes the next turn, and so on.
(tateti es un juego en el que participan 2 jugadores en un tablero de 3x3. Uno de los jugadores usa la “x” y el otro la “o”, la x juega primero y la o el siguiente turno)
// The players write ‘X’ and ‘O’ on a 3x3 field.(los jugadores escriben x y o en un campo de 3x3)
// The first player that puts 3 X’s or 3 O’s in a straight line (including diagonals) wins the game.(el primer jugador que pone 3 x o 3 o en una linea o diagonal gana el juego)
// Objectives(objetivos)
// Your first task in this project is to print the game grid in the console output. Use what you’ve learned about the print() function to print three lines, each containing three characters (X’s and O’s) to represent a game of tic-tac-toe where all fields of the grid have been filled in.(tu primera tarea en este proyecto es imprimir el tablero del juego en la salida de la consola. Usa lo que aprenderas sobre la funcion imprimir para imprimir tres lineas, para que cada una contenga 3 caracteres (x y o) para representar el juego de tateti donde todos los campos del tablero son llenados).
Example(ejemplo)
The example below shows how your output might look:(el ejemplo de abajo muestra como la salida debe verse)
X O X
O X O
X X O
What is Java?(que es Java?)
Java is a general-purpose modern programming language initially developed by Sun Microsystems, and currently owned by Oracle Corporation. The key feature of the language is platform independence: it means that the same Java program can be run on multiple platforms without any changes! This principle is also known as “write once, run anywhere” (or WORA).(Java es un lenguaje de programacion multiproposito desarrollado por microsistemas sun y actualmente es de la corporaacion Oracle. La principal herramienta de este lenguaje es la independencia de la plataforma: esto significa que puede ser ejecutado por multiples plataformas sin cambios, este principio es conocido como escribe una vez y ejecutalo donde sea)
Java has been one of the most popular programming languages for many years. It has earned the top position in the TIOBE index (a programming language popularity index). This language is used by a huge community of developers around the world! If you have a problem, you can always ask other developers or find a suitable answer online.(Java ha sido uno de los mas populares lenguajes de programacion por muchos años. Se ha ganado la alta posicion en el indice TIOBE, un indice de popularidad de lenguajes de programacion. Este lenguaje es usado por una enorme comunidad de desarrolladores por el mundo, si tienes un problema puedes preguntar a otros desarrolladores o encontrar una respuesta adecuada en linea)
Java is used in our Android smartphones, the financial services industry, telecommunications, embedded systems, and in many other areas. Medical applications use it to store patient data, computer games, such as Minecraft, are created using Java; development tools like IntelliJ IDEA and Eclipse wouldn’t exist without it. (Java es usado en nuestros celulares Android, la industria de servicios financieros, telecomunicaciones, sistemas embebidos, y en muchas otras areas. Aplicaciones medicas lo usan para almacenar data de los pacientes, juegos de computadora como minecraft son creados usando Java; herraminetas de desarrollo como Intellij IDEA y Eclipse no existirian sin él)
A short history of Java(una historia corta de Java)
The Java language project was initiated in 1991 by James Gosling and his colleagues. In the beginning, the language was called “Oak.” Later the project was renamed “Java” as a reference to Java coffee. For this reason, the language’s logo is a cup of coffee.(El proyecto de lenguaje Java fue inciado en 1991 por James Gosling y sus colegas. En el principio, el lenguaje fue llamado “oak”. Mas tarde el proyecto fue renombrado Java como una referencia al cafe Java.
Sun Microsystems released Java 1.0 in 1996. After that, new versions were released every 1 to 3 years. Since Java 9, released in 2017, new versions have been released every 6 months. You can read more about its history and find the most recent version here.(Microsistemas Sun liberaron Java 1.0 en 1996. Luego de eso, nuevas versiones eran liberadas cada 1 o 3 años. Desde Java 9, liberado en 2017, nuevas versiones son liberadas cada 6 meses)
Some important features of Java(Algunas importantes herramientas de Java)
As we’ve mentioned before, the most important feature of Java is platform independence.(Como mencionamos antes, la herramienta mas importante de Java es su independencia de plataforma)
Another important feature is a simple and clear syntax. Many elements of the language are easy to read and are widely used in other programming languages such as C/C++, C#, JavaScript, and Go.(Otra importante herramienta es su simple y clara sintaxis. Muchos elementos del lenguaje son faciles de leer y son ampliamente usados en otros lenguajes de programacion como C/C++, C#, JavaScript y Go)
If you have ever written programs in C/C++, you know that manual memory cleaning can lead to bugs in the code. Fortunately, Java has a garbage collector that automatically cleans memory from unused objects during runtime.(Si has escrito promamas en C/C++ sabras que el manual de limpieza de memoria puede llevar a bugs en el codigo. A fortunadamente, Java tiene un recolector de basura que automaticamente limpia la memoria de los objetos que no tienen uso durante la ejecucion)
It is also important to note that Java supports multiple programming paradigms; you will get to know more about them in these topics. Java is primarily an imperative language based on the object-oriented concept: almost every part of a program is an object. Therefore, a program itself can be considered as a set of interacting objects. Also, it partially supports modern programming paradigms such as generic programming, concurrent programming, functional programming, and some others.(Es importante notar que Java soporta paradigmas de programacion multiple; sabras de ello en los siguientes temas. Java es primariamente un lenguaje imperativo basado en el concepto de orientacion a objetos: Casi cada parte de un programa es un objeto. A demas, un programa en si mismo puede ser considerado como un conjunto de objetos interactuando. Tambien, soporta parcialmente paradigmas de programacion modernos como la programacion generica, programacion concurrente, programacion funcional y muchos otros).
If you are a beginner in programming, it may be difficult to comprehend all the features of Java right now. This is not a bad thing. Throughout this set of topics, you will learn about all of these concepts.
In conclusion, Java is a modern and popular programming language that can be successfully used in almost all domains.(Si sos un principiante en la programacion, deberia ser dificil comprender todas las herramientas de Java ahora mismo. Esto no es malo. A traves, de varios temas aprenderas sobre todos estos conceptos. En conclusion, Java es un lenguaje de programacion moderno y popular que puede ser usado exitosamente en casi todos los dominios)
Literals
Regardless of its complexity, a program always performs operations on numbers, strings, and other values. These values are called literals. There are many different sorts of literals in Java, but in this topic we will focus only on a few of them: the ones that surround us all the time in everyday life.(A pesar de su complejidad, un programa siempre realiza operaciones con numeros, strings y otros valores. Estos valores son llamados literales. Hay muchas clases de literales en Java, pero ahora nos enfocaremos en unos pocos: aquellos que nos roddean todo el tiempo en nuestra vida cotidiana)
Let’s consider integer numbers, strings, and characters in the format in which they are written in Java.(Consideramos numeros enteros, strings, y caracteres en el formato en el que son escritos en Java)
Integer numbers
These numbers are used to count things in the real world. Also, we will often use them in Java.(Estos numeros son usados para contar cosas en el mundo real. Tambien, los usamos a menudo en Java)
Here are several examples of valid integer number literals separated by commas: 0, 1, 2, 10, 11, 100.(Aqui hay varios ejemplos de numeros enteros validos separados por comas: 0, 1, 2, 10, 11, 100.
If an integer value contains a lot of digits, we can add underscores to divide the digit into blocks for increased readability: 1_000_000. It’s more readable than the same value written as 1000000.(Si un valor entero contiene muchos digitos podemos agregar guiones bajos para dividir los digitos en bloques para mejorar la lectura:1_000_000. Es mas leible que el mismo valor escrito como 1000000.)
Characters
A single character can represent a digit, a letter or another symbol. To write a character we use single quotes as follows: ‘A’, ‘B’, ‘C’, ‘x’, ‘y’, ‘z’, ‘0’, ‘1’, ‘2’, ‘9’. Character literals can represent symbols of an alphabet, digits from ‘0’ to ‘9’, whitespaces (‘ ‘), or other characters or symbols (‘$’).(Un simple caracter puede representar un digito, una letra u otro simbolo. Para escribir un caracter usamos comillas simples como: ‘1’,’2’,etc. Los literales de caracter pueden representar simbolos de un alfabeto, digitos del ‘0’ al ‘9’, espacios en blanco ‘ ‘, u otros caracteres o simbolos(‘$’).
Do not confuse characters that represent numbers (e.g. ‘9’), with numbers themselves (e.g. 9).(No confundas caracteres que representan numeros(ej: ‘9’) con los numeros en si(9).
A character can’t include two and more digits or letters because it represents only a single symbol. The following two examples are incorrect: ‘abc’, ‘543’. These literals contain too many characters.(Un caracter no puede incluir 2 o mas digitos o letras porque representa solo un solo simbolo. Los siguientes dos ejemplos son incorrectos: ‘abc’, ‘543’. Estos literales contienen muchos caracteres)
Strings
A string is a sequence of any individual characters. Strings represent text information such as a text of advertising, an address of a web page or a login on a site.(Un string es una secuencia de caracteres individuales. Strings representan informacion de texto como texto de advertencia, una direccion de una pagina web o el ingreso a un sitio)
To write a string we use double quotes instead of single ones. Here are some valid examples: “text”, “I want to know Java”, “123456”, “e-mail@gmail.com”. A string consisting of a single character like “A” is also a valid string, but do not confuse it with the ‘A’ character.(Para escribir un String usamos dobles comillas en vez de las simples. Aqui hay algunos ejemplos validos: “texto”, “Quiero saber Java”, “123456”, “email@gmail.com” Un string consistente de un caracter simple como “A” es tambien un string valido, pero no hay que confundirlo con el caracter ‘A’)
As you can see, strings can include letters, digits, whitespaces, and other characters.(Como puedes ver, los strings pueden contener letras, digitos, espacios y otros caracteres)
Remember(Recuerda)
Do not confuse these literals:(No confundas estos literales:)
123 is an integer number, “123” is a string;
‘A’ is a character, “A” is a string;
‘1’ is a character, 1 is an integer number.
In this topic, we will build our very first Java program. Our program will simply print “Hello, World!” on the screen (a tradition by most programmers when learning new languages). Our code may not seem too exciting at first, however, we will learn about the basic template that all Java programs need to follow.(En este tema, construiremos nuestro primer programa en Jva. Nuestro programa simplemente imprimira “Hola mundo!” en la pantalla. Una tradicion de los programadores cuando aprenden un nuevo lenguaje)
The Hello World program(El programa hola mundo)
Here is the Java code of this program:(Aqui esta el codigo Java de este programa:)
public class Main {
public static void main(String[] args) {
System.out.println(“Hello, World!”);
}
}
You can type this code in the Your Code section here and then press the execute button. In the result section, you will see:
Hello, World!
If you have already installed Java, you can run the program on your computer. If not, there is no need to install it right now. We will do that later.(Si ya instalaste Java, puedes ejecutar el programa en tu computadora. Sino no hay necesidad de instalarlo ahora mismo. Lo haremos mas tarde.)
The basic terminology(La terminologia basica)
Now that you have seen the result, let’s learn some basic terminology and then try to understand this program.(Ahora que has visto el resultado, aprenderemos terminologia basica y luego intentaremos entender este programa)
Program – a sequence of instructions (called statements), which are executed one after another in a predictable manner. Sequential flow is the most common and straightforward sequence of statements, in which statements are executed in the order that they are written – from top to bottom in a sequential manner;(Un Programa es una secuencia de instrucciones que son ejecutadas una despues de otra en una forma predecible. El flujo secuencial es la mas comun y sencilla secuencia de declaraciones, en los que las declaraciones son ejecutadas en el orden en que son escritos de arriba hacia abajo en una forma secuencial.)
Statement – a single action (like print a text) terminated by semi-colon (;);(Declaracion es una accion, como imprimir un texto terminado con un ;.)
Block – a group of zero, one or more statements enclosed by a pair of braces {…}; There are two such blocks in the program above.(Bloque es un grupo de cero, uno o mas declaraciones encerrados dentro de un par de llaves {}
Method – a sequence of statements that represents a high-level operation (also known as subprogram or procedure).(Metodo es una secuencia de declaraciones que representa una operacion de alto nivel, tambien conocida como subprograma o procedimiento)
Syntax – a set of rules that define how a program needs to be written in order to be valid; Java has its own specific syntax that we will learn;(Sintaxis es un conjunto de reglas que definen como un programa necesita ser escrito para ser valido, Java tiene su sintaxis especifica que aprenderemos)
Keyword – a word that has a special meaning in the programming language (public, class, and many others). These words cannot be used as variable names for your own program;(Palabra clave es una palabra que tiene un significado especial en el lenguaje de programacion. Estas palabras no pueden ser usadas como nombres de variables para tu propio programa)
Identifier or name – a word that refers to something in a program (such as a variable or a function name);(Identificador o nombre: una palabra que refiere a algo en un programa, como una variable o el nombre de una funcion)
Comment – a textual explanation of what the code does. Java comments start with //.(Comentario: una explicacion textual de lo que el codigo hace)
Whitespace – all characters that are not visible (space, tab, newline, etc.).(Espacio en blanco: todos los caracteres que no son visible(espacio, tabulador, nueva linea, etc)
The Hello World program under a microscope(El programa hola mundo bajo un microscopio)
The Hello World program illustrates the basic elements of Java programs. For now, we will discuss only the most important elements.(El programa hola mundo ilustra los elementos basicos de los programas Jva. Por ahora, discutiremos los elementos mas importantes)
public class Main {
// …
}
The text after // is just a comment, not a part of the program. We will learn about comments in detail in later topics.(El texto des pues de // es solo un comentario, no es parte del programa. Aprenderemos sobre comentarios en los siguientes temas)
public static void main(String[] args) {
// statements go here
}
The keywords public, static, and void will be discussed later, so just remember them for now. The name of this method (main) is predefined and should always be the same. Capitalization matters; if you name your first method like Main, MAIN or something else, the program cannot start.(Las palabras clave public, static y void seran vistas mas tarde, solo recuerdalas por ahora. El nombre de este metodo, main,esta predefinido y siempre deberia ser el mismo. Las mayusculas importan, si nombras el metodo como Main, MAIN, o algo mas el programa no puede comenzar)
The element String[] args represents a sequence of arguments passed to the program from the outside world. Don’t worry about them right now.(El elemento String[] args representa una secuencia de argumentos pasados al programa del mundo exterior)
System.out.println(“Hello, World!”); // each statement has to end with ;(Cada declaracion tiene que terminar con ;)
This is one of the most important things to understand from the Hello World program. We invoke a special method println to display a string followed by a new line on the screen. We will often use this approach to print something of interest to the screen. The text is printed without double quotes.(Esta es una de las cosas mas importantes para entender el programa hola mundo. invocamos un metodo especial println para mostrar un string seguido de una nueva linea en la pantalla, usaremos esto seguidp para imprimir algo de interes en la pantalla)
Important, that “Hello, World!” is not a keyword or an identifier; it is just a text to be printed.(Importante, el “Hola mundo!” nos es una palabra clave ni un identificador, es solo un texto a ser impreso)
Keywords(Palabras claves)
As you can see, even a simple Java program consists of many elements, including keywords that are parts of the language. In total, Java provides more than 50 keywords which you will gradually learn on this platform. The full list is here, but do not try to remember them at this moment.(Como puedes ver incluso un simple programa de Java consiste de muchos elementos, incluyendo palabras clave que son partes del lenguaje. En total, Java provee mas de 50 palabras clave que gradualmente aprenderas. La lista completa esta aqui, pero no intentes recordarla ahora mismo)
Note, main is outside the given list because it is not a keyword(Nota, main esta afuera de la lista dada porque no es una palabra clave)
Conclusion
We have discussed the simplest program you can write in Java. It has a single class with a single main method. Every Java program must have a main method as it is the first to be executed when the program runs. Don’t worry about memorizing every single term used in the topic (syntax, statement, block). These terms will reappear in further materials. Do not forget to use the provided Hello World program as a template for your own programs.(Discutimos el mas simple de los programas que puedes escribir en Java. Teien una sola clase con un solo metodo. Cada programa Java debe tener un metodo principal que sera el primero en ser ejecutado cuando el programa corra. No te preocupes en memorizar cada termino usado en el tema, sintaxis, declaracion, bloque, etc. Estos terminos reapareceran en materiales posteriores. No olvides usar el programa hola mundo provisto como un template para tus propios programas)
class Main {
public static void main(String[] args) {
System.out.println(“Hello, World!”);
}
}
Displaying text using println() and print()
Standard output is a receiver to which a program can send information (text). It is supported by all common operating systems. Java provides a special object System.out to work with the standard output. We will often use it to print something.(La salida estandar es un recibidor en el cual un programa puede recibir informacion, texto. Esta suportado por todos los sistemas operativos comunes. Java provee un objeto especial System.out para trabajar con la salida estandar. Nosotros lo usaremos seguido para imprimir algo)
The println method displays the passed string followed by a new line on the screen (print-line). As an example, the following code fragment prints four lines.(El metodo println muestra el string seguido por una nueva linea en la pantalla)
System.out.println(“I “);
System.out.println(“know “);
System.out.println(“Java “);
System.out.println(“well.”);
The output:
I
know
Java
well.
All strings were printed as is, without double quotes.(Todos los strings se imprimieron como estaban sin dobles comillas)
The method allows you to print an empty line when no string is given:(El metodo te permite imprimr una linea vacia cuando no hay un string dado
System.out.println(“Java is a popular programming language.”);
System.out.println(); // prints empty line
System.out.println(“It is used all over the world!”);
The output:
Java is a popular programming language.
It is used all over the world!
The print method displays the passed value and places the cursor (the position where we display a value) after it. As an example, the code below outputs all strings in a single line.(El metodo imprimir muestra el valor pasado y coloca el cursor (la posicion donde muestra el valor) despues de el. Como ejemplo, el codigo debajo devuelve todos los strings en una sola linea)
System.out.print(“I “);
System.out.print(“know “);
System.out.print(“Java “);
System.out.print(“well.”);
The output:
I know Java well.
Pay attention to the spaces between words. We pass them to methods for printing.(Presta atencion a los espacios entre palabras. Los pasamos a metodos para imprimir).
Printing numbers and characters(Imprimiendo numeros y caracteres)
Both methods println and print allow a program to print not only strings and characters, but also numbers.(Ambos metodos println y print permiten al promgrama no solo imprimir strings y caracteres sino tambien numeros.)
Let’s print two secret codes.(Imprimamos dos codigos secretos)
System.out.print(108); // printing a number(Imprimiendo un numero)
System.out.print(‘c’); // printing a character that represents a letter(Imprimiendo un caracter que representa una letra)
System.out.print(“Q”); // printing a string(Imprimiendo un string)
System.out.println(‘3’); // printing a character that represents a digit(Imprimiendo un caracter que representa un digito)
System.out.print(22);
System.out.print(‘E’);
System.out.print(8);
System.out.println(‘1’);
It outputs:
108cQ3
22E81
As is the case with strings, none of the characters contain quotes.(Como ocurre en el caso con los strings ninguno de los caracteres contiene comillas)
Declaring and initializing
A variable is a placeholder for storing a value of a particular type: a string, a number, or something else. Every variable has a name (also known as an identifier) to distinguish it from others. Before you start using a variable, you must declare it.(Una variable en un lugar para almacenar un valor de un tipo particular: un string, un numero o algo mas. Cada variable tiene un nombre, tambien conocido como un identificador, para distinguirlo de otros. Antes de usar una variable debes declararla)
The general form of declaration is the following:(La forma general de declaracion es la siguiente:)
DataType variableName = initialization;(TipoDeDato NombreDeLaVariable = inicializacion;)
The left part of this statement describes the variable, and the right part describes something that is assigned to it.(La parte de la izquierda de la sentencia describe la
variable y la derecha describe algo que es asignado a ella.)
The type (or data type) of a variable determines what possible operations can be performed on the variable and which values can be stored in it. Here we use a non-existing data
type (DataType) to demonstrate the general form of declaration.(El tipo, o tipo de dato, de una variable determina que operaciones posibles pueden ser realizadas con una
variable y que valores pueden ser almacenadas en el. Usamos aqui un tipo de dato no existente para demostrar la forma general de declaracion)
The name (or identifier) distinguishes the variable from others. The name of a variable cannot start with a digit; it usually starts with a letter. Always try to choose
meaningful and readable names for variables to make your code easy to understand.(El nombre o identificador distingue la variable de otras. El nombre de una variable no puede
comenzar con un digito; usualmente comienza con una letra. Siempre trata de elegir nombre leibles y que hagan tu codigo mas facil de entender)
The assignment operator denoted as = is used to assign a single value or a result of an expression to a variable.(El operador de asignacion es = es usado para asignar un simple
valor o un resultado de una expresion a una variable)
The initialization is a value or a result of an expression that is assigned to the variable.(La inicializacion es una valor o un resultado de una expresion que esta asignado a
una variable)
According to this declaration, we can declare a variable of the type String and assign the word “java” to it:(De acuerdo a esta declaracion podemos declarar una variable del tipo
string y asignar la palabra “Java” a ella)
String language = “java”;
We can also declare a variable of the type int to store an integer number:(Tambien podemos declarar una variable del tipo int para almacenar un numero entero:)
int numberOfApples = 5;
The case in the name of a variable makes a difference: language is not the same as Language.(Si esta en minuscula o mayuscula en el nombre de una variable hace una diferencia:
languaje no es lo mismo que Lenguaje)
Variables can store not only strings and numbers, but also characters and other data types which we will learn about later in the next topics.(Variables pueden almacenar no solo strings y numeros, sino tambien caracteres y otro tipo de datos que aprenderemos en los siguientes temas)
Accessing the value of a variable(Accediendo al valor de una variable)
Once a variable has been declared, its value can be accessed and modified using the name. In the example below, we declare a variable and then print it:(Una vez que una variable
ha sido declarada su valor puede ser accesado y modificado usando su nombre. E n el ejemplo mas debajo declaramos una varible y luego la imprimimos)
String dayOfWeek = “Monday”;
System.out.println(dayOfWeek); // Monday
It is also possible to assign a value of one variable to another one:(Tambien es posible asignar un valor de una variable a otra)
int one = 1;
int num = one;
System.out.println(num); // 1
One important feature of variables is that they can be changed. You don’t need to declare a variable again to change its value; just assign a new value to it using the =
operator.(Una herramienta importante de las variables es que pueden ser cambiadas. No necesitas declarar una variable otra vez para cambiar su valor; Solo asigna un nuevo valor
a ella usando el operador =)
Let’s declare a variable named dayOfWeek and print its value before and after changing:(Declaremos una variable llamada DiaDeLaSemana e imprimamos su valor antes
y despues de cambiar)
String dayOfWeek = “Monday”;
System.out.println(dayOfWeek); // Monday
dayOfWeek = “Tuesday”;
System.out.println(dayOfWeek); // Tuesday
There is one restriction for variables: you can only assign a value of the same type as the type of the initial variable. So, the following code is not correct:(Solo hay
una restriccion para las variables: solo puedes asignar un valor del mismo tipo que el tipo inicial de la variable. Por lo que el siguiente codigo no es correcto:)
int number = 10;
number = 11; // ok
number = “twelve”; // it does not work!
Alternative forms of declaration(Formas alternativas de declaracion)
There are several alternative forms of declaration which are less commonly used in practice. Here are several of them in particular examples.(Hay varias formas
alternativas de declaracion que son menos usadas en la practica. Aqui hay algunas de ellas en ejemplos particulares.)
Declaring several variables of the same type as a single statement:(Declarando varias variables del mismo tipo como una sola declaracion:)
String language = “java”, version = “8 or newer”;
Separating declaration and initialization into statements:(Separando declaracion e inicializacion en sentencias:)
int age; // declaration
age = 35; // initialization
However, as we have already noted, these forms are rarely used.(Aunque estas formas son usadas raramente)
Type inference(Inferencia de tipos)
Since Java 10, you can write var instead of a specific type to force automatic type inference based on the type of assigned value:(Desde Java 10, puedes escribir var en vez de el tipo especifico para forzar automaticamente la inferencia de tipos basada en el el tipo de valor asignado:)
var variableName = initialization;
Here are two examples below:(Aqui hay dos ejemplos debajo:)
var language = “Java”; // String
var version = 10; // int
This feature can be a bit controversial: on the one hand, it allows your code to be more concise. On the other hand, since it doesn’t indicate the type explicitly, it may affect
the code readability in a bad way. For now, it’s enough to understand the basic idea. We will not use type inference in our theory so that our educational platform is suitable
for people who use earlier versions of Java. But if you would like to practice it, you may use type inference in our exercises as they fully support Java 10.(Esta
herramienta puede ser algo controversial: por un lado, permite que tu codigo sea mas conciso. Por el otro como no indica el tipo explicitamente puede afectar a tu
lectura de codigo en una mala manera. Por ahora es suficiente que entiendas la idea basica. No usaremos la inferencia de tipos en la teoria por lo que esto ayuda a la
gente con versiones anteriores de Java. Pero si quieres practicarlo, puedes usar inferencia de tipos en nuestro ejercicios ya que soportan completamente Java 10)
int i = 0, j = 0, k = 0;
String s = “s”, str = “str”;
Enter the number of declared variables in the code fragment.(Ingresa el numero de variables declaradas en el siguiente fragmento de codigo)
For example, if you think that eight variables are here, enter the number:(Por ejemplo si piensas que son ocho variables ingresa el numero)
en este caso son 5 ya que reasignar una variable cuenta como asignarla
Description
Our program should be able to display the grid at all stages of the game. Now we’re going to write a program that allows the user to enter a string representing the game state and correctly prints the 3x3 game grid based on this input. We’ll also add some boundaries around the game grid.
Objectives
In this stage, you will write a program that:
Reads a string of 9 symbols from the input and displays them to the user in a 3x3 grid. The grid can contain only X, O and _ symbols.
Outputs a line of dashes ————- above and below the grid, adds a pipe | symbol to the beginning and end of each line of the grid, and adds a space between all characters in the grid.
Examples
Examples below show how your output should look.
Notice that after Enter cells: comes the user input.
Example 1:
| O _ O |
| X X O |
Example 2:
| O X O |
| X |
Example 3:
| X O |
| _ X |
<!——— Theory: Increment and decrement————-!>
In this topic, we will discuss one of the most famous operations in programming: increment. It is used in many programming languages including Java to increase a variable by one. Fun fact: this operation is used in the name of C++, and signifies the evolutionary nature of the changes from C.
Using ++ and — in Java
Java has two opposite operations called increment (++) and decrement (—) to increase/decrease the value of a variable by one.
int n = 10;
n++; // 11
n—; // 10
The code above is actually the same as below.
int n = 10;
n += 1; // 11
n -= 1; // 10
Prefix and postfix forms
Both increment and decrement operators have two forms which are very important when using the result in the current statement:
prefix (++n or —n) increases/decreases the value of a variable before it is used;
postfix (n++ or n—) increases/decreases the value of a variable after it is used.
The following examples demonstrate both forms of increment.
Prefix increment:
int a = 4;
int b = ++a;
System.out.println(a); // 5
System.out.println(b); // 5
In this case, the value of a has been incremented and then assigned to b. So, b is 5.
Postfix increment:
int a = 4;
int b = a++;
System.out.println(a); // 5
System.out.println(b); // 4
In Java, the postfix operator has higher precedence than the assignment operator. However, it returns the original value of a, not the incremented one. That’s why when we assign a++ to b, we actually assign 4, while a itself has already been incremented. So, b is 4 and a is 5.
If that’s still not clear enough for you, take a look at the code:
int a = 4;
System.out.println(a++ + a); // this is 9
We hope that now you fully understand increment and decrement and their prefix and postfix forms.
el preincremento agrega primero y luego asigna la variable. El postincremento asigna el valor y luego aumenta el valor
int a = 4;
int b = a++;
System.out.println(a); // 5
System.out.println(b); // 4
RESPUESTA A:
int a = -1;
System.out.println(1 - a++); 2
int a = 2;
int b = 3;
int c = ++a + b—; 6
int n = 10;
n—;
System.out.println(n++); 9
<!———- Theory: Characters ————-!>
The char type is used to represent letters (both uppercase and lowercase), digits, and other symbols. Each character is just a symbol enclosed in single quotes.
char lowerCaseLetter = ‘a’;
char upperCaseLetter = ‘Q’;
char number = ‘1’;
char space = ‘ ‘;
char dollar = ‘$’;
This type can represent all characters in all languages as well as some special and computer symbols. It corresponds to the Unicode (UTF-16) format. Unicode is a computer encoding methodology that assigns a unique number for every character. It doesn’t matter what language, or computer platform it’s on. This is important in a global, networked world, and for computer systems that must accommodate multiple languages and special characters. Unicode truly unifies all of these into a single standard.
Initializing characters with codes
A character can be also created using its hexadecimal code in the Unicode table. The code starts with \u.
char ch = ‘\u0040’; // it represents ‘@’
System.out.println(ch); // @
Although we use a sequence of characters to represent such code, the code represents exactly one character.
As an example, Latin capital letters have hexadecimal codes from ‘\u0041’ to ‘\u005A’, and Latin small letters have codes from ‘\u0061’ to ‘\u007A’.
The char type has a minimum value encoded as ‘\u0000’ and the maximum value encoded as ‘\uffff’.
It is also possible to initialize a char with a positive integer number.
char ch = 64;
System.out.println(ch); // @
The number 64 just corresponds to the Unicode hexadecimal code ‘\u0040’.
Any char variable may be considered as an unsigned integer value in the range from 0 to 65535.
Retrieving subsequent characters
There are two operators for adding (+) and subtracting (-) integer numbers in order to get the next and previous character according to the Unicode order.
char ch = ‘b’;
ch += 1; // ‘c’
ch -= 2; // ‘a’
It is also possible adding and subtracting one character to / from another one.
char ch = ‘b’;
ch += ‘a’;
ch -= ‘b’;
System.out.println(ch); // prints ‘a’ without quotes
Actually, these operations manipulate with codes of characters, ‘b’ has the next code after ‘a’.
It is possible to use increment (++) and decrement (—) operators in prefix and postfix forms.
char ch = ‘A’;
ch += 10;
System.out.println(ch); // ‘K’
System.out.println(++ch); // ‘L’
System.out.println(++ch); // ‘M’
System.out.println(—ch); // ‘L’
Escape sequences
There are some special characters starting with backslash \ which are known as the escape or control sequences. They do not have corresponding symbols and cannot be found on a keyboard. To represent such characters we use a pair of regular symbols. In a program, this pair will be considered as exactly one character with the appropriate code.
‘\n’ is the newline character;
‘\t’ is the tab character;
‘\r’ is the carriage return character;
‘\‘ is the backslash character itself;
‘\’’ is the single quote mark;
‘\”‘ is the double quote mark.
Here are several examples:
System.out.print(‘\t’); // makes a tab
System.out.print(‘a’); // prints ‘a’
System.out.print(‘\n’); // goes to the new line
System.out.print(‘c’); // prints ‘c’
This code prints:
a
c
There is also a character to represent a single space ‘ ‘. It is just a regular character, not an escape sequence.
char c = ‘1’ + ‘3’;
System.out.println(c); 4
int z = ‘z’;
char mystery = z - 10;
System.out.println(mystery); COMPILE ERROR
char ch = ‘\u0031’ + ‘\u0035’;
System.out.println(ch); F
<!——- Theory: Calling a method ———!>
You may remember that a method is a sequence of statements that can be invoked or referred to by its name. Nothing special, huh? But what if we tell you that you can use it in a program anytime you need and anywhere you want just by simply invoking it with one line of code? Hope that we caught your attention now!
To get started, we will call some method:
getVolume(a, b, h);
Here, getVolume is the name of the method that, for example, calculates a volume of some geometric shape, and the variables a, b and h are its parameters. Technically, the parameter of a method is some value that is used inside the method. The combination of the name and method’s parameters in parentheses is the way we call or invoke the method. Let’s focus on it in more detail.
Name of the method
Each method has a name that is used to call it. Generally, it reflects what the method does – prints, finds, calculates, provides you with some information.
The Java compiler requires a method name to be a legal identifier. The rules for legal identifiers are the following:
identifiers are case-sensitive;
an identifier can include Unicode letters, digits, underscore _ or currency characters, such as $;
an identifier can’t start with a digit;
identifiers must not be a keyword.
In addition, there is a naming convention that restricts possible method names. It’s optional but desired for developers. By convention, a one-word name should be a verb in lowercase: sum, multiply, or round.
If a method has a multi-word name, the first letter of the second and the following words should be capitalized: getValue, calculateNumberOfOranges, or findLetter.
OK, now we know how methods are named. Let’s talk about how we actually call them!
Calling a method
If you want to call (or invoke) a method in your program, you should write its name and pass the values of its parameters in parentheses. Here’s how it can be done:
printNumber(7); // this method prints 7
convertDoubleToInt(1.25) // this method converts double value to int
findUserByName(“Kate”); // this method finds a user whose name is Kate
Let’s take a look at the findUserByName example.
Here we pass a String value with a name to make the findUserByName do its job. To call a method from outside the class it belongs to you need to indicate a class as a prefix. Check these methods:
Math.round(79.378); // method with Math class name
Character.isLetter(‘a’); // method with Character class name
Let’s try to perform a small task by invoking a method:
double weight = 63.85;
weight = Math.round(weight); // now weight equals 64.0
Here, we have methods that take parameters, but what if we tell you that some methods don’t accept parameters at all? In that case, just leave the parentheses empty.
Some methods are called in a slightly different way. Take a look:
// this is how you call an instance method
String name = new String(“Anya”); // created an instance (1)
name = name.toLowerCase() // anya (2)
Methods like this require an object of a certain class to be invoked. Before we called the toLowerCase() method, we created an object of the String class called name, since the method in question deals with strings. Now we can call the method for this particular instance (2), which results in decapitalizing all the letters from our string.
As you see, this method requires an instance to be created before it can be called, that’s why it is known as an instance method. We will talk about this type of method later.
Built-in methods
Why do you need to rewrite algorithms that have already been written? Of course, we’re not talking about some special cases like educational tasks. Still, it is more efficient to use pre-defined methods that are always available to the user. That is why there are two types of methods in Java: built-in and user-defined methods.
Built-in methods belong to the Standard Java library. Now there are a lot of built-in methods that convert or compare values, round doubles, find the maximum or the minimum value, and do a lot of useful operations. We’ve already dealt with the round(), isLetter(), compareTo(), hasNext() methods, but the number of built-in methods is huge and constantly growing. You can find the method you need in the Oracle documentation. For example, check out the link to the Math library.
In contrast to built-in methods, user-defined methods are created by the programmer. It is a common practice to create a customized subprogram for a specific purpose. You may create your own method and even put it in your own class. Later on, we will learn why it is a good practice to use user-defined methods and how to actually create them.
Conclusion
Generally, a method is a necessary tool for a programmer who is aiming for a neat and reusable code style. With the help of methods, you can perform any specific task you need. They make the program look more readable, and you don’t need to repeat routine code lines over and over. Some tasks are wrapped in special built-in methods that are parts of the standard Java library. Also, there are user-defined methods that are created by the programmer. We will discuss these methods in other topics.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// call the method here
Scanner sc = new Scanner(System.in);
countAreaOfParallelogram(sc.nextInt(), sc.nextInt());
}
// Do not change code below
public static void countAreaOfParallelogram(int b, int h) {
System.out.println(b * h);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int aa = scanner.nextInt();
int bb = scanner.nextInt();
countAreaOfParallelogram(aa, bb);
}
// Do not change code below
public static void countAreaOfParallelogram(int b, int h) {
System.out.println(b * h);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// call the method here
callMeAwesome();
}
// Do not change code below
public static void callMeAwesome() {
Scanner scanner = new Scanner(System.in);
String name = scanner.next();
System.out.println(name + ", you're awesome!");
}
}
<!————— Theory: Primitive and reference types ———————-!>
In Java, all data types are separated into two groups: primitive types and reference types.
Java provides only eight primitive types. They are built-in in the language syntax as keywords. The names of all primitive types are lowercase. The most commonly used type is int which represents an integer number.
int num = 100;
The number of reference types is huge and constantly growing. A programmer can even create their own type and use it like standard types. The most frequently used reference types are String, Scanner and arrays. Remember that Java, like most programming languages, is case sensitive.
In this topic, we will focus on String, which is a common example of the reference type.
The new keyword
In most cases, an object of a reference type can be created using the new keyword. When we use the new keyword, the memory is allocated for the object we create. That is called instantiation of the object because we create an instance of it. Then we initialize the variable by assigning some value to it. Often, as in our example, it is done with one line.
String language = new String(“java”);
//instantiation of String and initialization with “java”
You can also use a literal for strings:
String language = “java”;
The first approach with the keyword new is common for reference types, while the second is only string-specific. Both approaches give us the same result for strings but they have some technical differences which we will not consider here.
The main difference
The basic difference between primitive and reference types is that a variable of a primitive type stores the actual values, whereas a variable of a reference type stores an address in memory (reference) where the data is located. The data can be presented as a complex structure that includes other data types as their parts.
The following picture simply demonstrates this difference. There are two main memory spaces: stack and heap. All values of primitive types are stored in stack memory, but variables of reference types store addresses of objects located in heap memory.
We will not consider stack and heap in detail here. Just remember this difference between primitive and reference types.
Assignment
The way to store data also affects the mechanism to assign the value of a variable to another variable:
primitive types: the value is just copied;
reference types: the address to the value is copied (the data is shared between several variables).
Here is a snippet of code and a picture that demonstrates this.
int a = 100;
int b = a; // 100 is copied to b
String language = new String(“java”);
String java = language;
The variable b has a copy of the value stored in the variable a. But the variables language and java reference the same value, rather than copying it. The picture below clearly demonstrates the difference.
Just remember, when assigning one value of a reference variable to another, we just make a copy of a reference rather than the value itself.
Comparisons
Comparing reference types using == and != is not the same as comparing primitive types. Actually, when you are comparing two variables of the String type, it compares references (addresses) rather than actual values.
The following code demonstrates it:
String s1 = new String(“java”);
String s2 = new String(“java”);
String s3 = s2;
System.out.println(s1 == s2); // false
System.out.println(s2 == s3); // true
The picture below demonstrates this effect:
So, you should not use comparison operators when you want to compare the values. The correct way to compare content is to invoke the special method equals.
String s1 = new String(“java”);
String s2 = new String(“java”);
String s3 = s2;
System.out.println(s1.equals(s2)); // true
System.out.println(s2.equals(s3)); // true
The null type
Unlike primitive types, a variable of a reference type can refer to a special null value that represents the fact that it is not initialized yet or doesn’t have a value.
String str = null;
System.out.println(str); // null
str = “hello”;
System.out.println(str); // hello
The following statement with a primitive type won’t compile.
int n = null; // it won’t compile
Unfortunately, the frequent use of the null value can easily lead to errors in the program and complicate the code. Try to avoid null whenever it is possible, only use it if you really need it.
<!———-Theory: Array ————!>
Introduction to arrays
When you need to process multiple objects of the same type, you can save them in an array and then process them together as a single unit. It is a very convenient approach if you do not know how many objects the program will process during runtime.
You may consider an array as a collection of elements of the same type. All elements are stored in the memory sequentially.
The collection provides one name for its elements. The possible number of elements to be stored is established when the array is created and cannot be changed. But a stored element can be modified at any time.
The picture below illustrates an array of five floating-point numbers. Each element has an integer index (0-4) to be accessed.
An array of five floating-point elements
The first element has the index 0, the last element has the index equal to array size – 1.
In Java, an array has the following important features:
an array is a reference type;
all array elements are stored in the memory sequentially;
each element of the array is accessed by its numerical index, the first element has the index 0;
the last element is accessed by the index equal to array size – 1;
it is possible to create an array to store elements of any type.
Declaration, instantiation, initialization
To create an array filled with elements we should:
declare a variable of an array type (declaration);
create an instance of the array object (instantiation);
initialize the array by some values (initialization).
When we declare a variable, we define its type and name. Instantiation happens when memory is allocated for this object. Initializing the array object means that we put certain values of the array object into the memory of our program.
To declare an array we must use two special characters [ ] after the name of the type of elements in the array:
int[] array; // declaration form 1
or after the name of an array variable:
int array[]; // declaration form 2: less used in practice
Next, we will use the first form of declaration because it is mostly used in practice.
Creating an array with specified elements
Java provides several ways to create an array with specified elements.
The simplest way to instantiate and initialize an array is to enumerate all its elements:
int[] numbers = { 1, 2, 3, 4 }; // instantiating and initializing an array of 1, 2, 3, 4
Another way is to initialize an array using variables:
int a = 1, b = 2, c = 3, d = 4;
int[] numbers = { a, b, c, d }; // instantiating and initializing an array of 1, 2, 3, 4
In this case, we should have all the elements at the moment of the array creation.
Creating an array using the keyword “new”
The most general way to create an array is to use the special keyword new and specify the necessary number of elements:
int n = …; // n is a length of an array
int[] numbers = new int[n];
This form is useful when the number of elements is known before starting the program. When we create an instance of the array object with indicated length like [n] or [5] and don’t enumerate its elements explicitly, the array is initialized with default values of its type.
Now, the array has n elements. Each element is equal to zero (the default value of the type int). Next, we should make an explicit initialization of elements.
The size of an array cannot be greater than Integer.MAX_VALUE. Actually, it is even slightly smaller than this value.
It’s possible to separate declaration and instantiation in two lines:
int[] numbers; // declaration
numbers = new int[n]; // instantiation and initialization with default values
Also, we can write the keyword new and enumerate all elements of an array:
float[] floatNumbers; // declaration
floatNumbers = new float[] { 1.02f, 0.03f, 4f }; // instantiation and initialization
The length of an array
To obtain the length of an existing array, access the special property arrayName.length. Here is an example:
int[] array = { 1, 2, 3, 4 }; // an array of numbers
int length = array.length; // number of elements of the array
System.out.println(length); // 4
Accessing elements
The values of elements of an array can be changed. You can use the index to set a value of the array or to get a value from it.
Set the value by the index:
array[index] = val;
Get the value by the index:
val = array[index];
Indexes of an array have numbers from 0 to length – 1 inclusive.
Let’s see an example.
int[] numbers = new int[3]; // numbers: [0, 0, 0]
numbers[0] = 1; // numbers: [1, 0, 0]
numbers[1] = 2; // numbers: [1, 2, 0]
numbers[2] = numbers[0] + numbers[1]; // numbers: [1, 2, 3]
This code works as follows:
In the first line, the array of integers named numbers with three elements in it is created. It is initialized with default values, which is 0 for the int type.
In the second line, the value “1” is assigned to the very first element of the array by its index (do not forget, the first element has the index 0).
In the third line, the value “2” is assigned to the second element of the array by its index (numbers[1] is the second element).
In the last line, the sum of the first two elements is assigned to the third element by its index.
If we try to access a non-existing element by an index then a runtime exception occurs.
For instance, let’s try to get the fourth element (with index 3) of the considered array numbers.
int elem = numbers[3];
The program throws ArrayIndexOutOfBoundsException.
Be careful while indexing elements of an array.
The utility class Arrays
If you need to process arrays, you can import and use standard methods grouped in the utility class Arrays.
convert an array to string using Arrays.toString(array) and then print it:
byte[] famousNumbers = { 0, 1, 2, 4, 8, 16, 32, 64 };
String arrayAsString = Arrays.toString(famousNumbers); // [0, 1, 2, 4, 8, 16, 32, 64]
System.out.println(arrayAsString);
sorting a whole array or a part of it using Arrays.sort(array):
long[] bigNumbers = { 200000000L, 400000000L, 100000000L, 300000000L }; // it’s unsorted
Arrays.sort(bigNumbers); // sorting whole array
System.out.println(Arrays.toString(bigNumbers)); // [100000000, 200000000, 300000000, 400000000]
comparing arrays: two arrays are equal if they contain the same elements in the same order:
int[] numbers1 = { 1, 2, 5, 8 };
int[] numbers2 = { 1, 2, 5 };
int[] numbers3 = { 1, 2, 5, 8 };
System.out.println(Arrays.equals(numbers1, numbers2)); // it prints “false”
System.out.println(Arrays.equals(numbers1, numbers3)); // it prints “true”
filling a whole array or a part of it by some values:
int size = 10;
char[] characters = new char[size];
// It takes an array, start index, end index (exclusive) and the value for filling the array
Arrays.fill(characters, 0, size / 2, ‘A’);
Arrays.fill(characters, size / 2, size, ‘B’);
System.out.println(Arrays.toString(characters)); // it prints [A, A, A, A, A, B, B, B, B, B]
Of course, the Arrays class contains a lot of other useful methods, including array copying, searching in arrays, and so on. For details see here.
int numbers[] = { 1, 2, 3, 4, 5 };
Arrays.fill(numbers, 1, 5, 10);
System.out.println(Arrays.toString(numbers)) [1, 10, 10, 10, 10]
<!———— Theory: String ————-!>
The String type
String is a reference type consisting of characters. It is one of the most widely used types in Java. Here is an example of a string: “Hello, Java”. This string is a sequence of 11 characters, including one space.
This type has some features:
immutable type: it’s impossible to change a character in a string;
it has methods for getting individual characters and extracting substrings;
individual characters can be accessed by indexes, the first character has the index 0, the last one – the length of the string – 1;
non-primitive type.
Creating strings
A string literal is surrounded by a pair of double quotes, for instance:
String simpleString = “It is a simple string”; // a simple string
System.out.println(simpleString); // it prints “It is a simple string”
String anotherString = “This is\na multiple\nstring”; // a string with escape sequences
System.out.println(anotherString); // it prints the result in several lines
A string can represent a long character sequence (text). A string can have one or zero characters.
String strangeText = “aaaaaaaaaaaassssssssssss gggggggggggggggggggg ddddddddddd qqqqqq ffff”;
String emptyString = “”;
String s = “s”; // a string consisting of one character
A string can be null. It means no value assigned.
String nullString = null; // it is null
Another way to create a variable of String is by using the keyword new.
String str = new String(“my-string”); // it creates an object and assigns it to the variable
Get the length and characters of a string
Any string has two useful methods:
length() returns the number of characters in the string;
charAt(int index) returns a character by its index;
Here is an example:
String s = “Hi, all”;
int len = s.length(); // the len is 7
char theFirstChar = s.charAt(0); // ‘H’ has the index 0
char theFifthChar = s.charAt(4); // ‘a’ has the index 4
char theLastChar = s.charAt(s.length() - 1); // ‘l’ has the index 6
You can easily get a character of a string by the index, but you can’t change characters because strings are immutable in Java.
Useful methods of strings
The standard library of Java provides a lot of useful methods for processing strings:
isEmpty() returns true if the string is empty, otherwise – false;
toUpperCase() returns a new string in uppercase;
toLowerCase() returns a new string in lowercase;
startsWith(prefix) returns true if the string starts with the given string prefix, otherwise, false;
endsWith(suffix) returns true if the string ends with the given string suffix, otherwise, false.
contains(…) returns true if the string contains the given string or character;
substring(beginIndex, endIndex) returns a substring of the string in the range: beginIndex, endIndex - 1;
replace(old, new) returns a new string obtained by replacing all occurrences of old with new that can be chars or strings.
trim() returns a copy of the string obtained by omitting the leading and trailing whitespace. Note that whitespace includes not only space character, but mostly everything that looks empty: tab, carriage return, newline character, etc.
See the following example to better understand these methods:
String text = “The simple text string”;
boolean empty = text.isEmpty(); // false
String textInUpperCase = text.toUpperCase(); // “THE SIMPLE TEXT STRING”
boolean startsWith = textInUpperCase.startsWith(“THE”); // true
/ replace all space characters with empty strings /
String noSpaces = textInUpperCase.replace(“ “, “”); // “THESIMPLETEXTSTRING”
String textWithWhitespaces = “\t text with whitespaces !\n \t”;
String trimmedText = textWithWhitespaces.trim(); // “text with whitespaces !”
To learn more about different methods and arguments you can check out the documentation.
Exceptions when processing strings
When working with strings, there can be several exceptions.
String s = null;
int length = s.length(); // it throws NullPointerException
String s = “ab”;
char c = s.charAt(2); // it throws StringIndexOutOfBoundsException because indexing starts with 0
We will consider how to handle different types of exceptions later.
Concatenating strings
Two strings can be concatenated using the “+” operator or the concat method. Both approaches lead to the same results.
String firstName = “John”;
String lastName = “Smith”;
// concatenation using the “+” operator
String fullName1 = firstName + “ “ + lastName; // “John Smith”
// concatenation using the concat method
String fullName2 = firstName.concat(“ “).concat(lastName); // “John Smith”
When we concatenate two strings a new string is created (because strings are immutable).
Important: in the general case str1 + str2 is not the same as str2 + str1 because the concatenation is not a commutative operation.
Appending values to a string
It’s possible to add values of different types to a string. The value will be automatically converted to a string. See an example below.
String str = “str” + 10 + false; // the result is “str10false”
In the example above, the order of execution is:
“str” + 10 => “str10”
“str10” + false = “str10false”
Let’s see a more complex example:
String shortString = “str”;
int number = 100;
String result1 = shortString + number + 50; // the result is “str10050”
String result2 = number + 50 + shortString; // what is the result2?
The result2 is 150str, because, first, we calculate a sum of number and 50 and then concat it with str. The order of operations is important.
How to compare strings correctly?
Since String is a reference type you shouldn’t compare strings using == or != operators. In this case, only addresses will be compared, but not actual values.
String has two convenient methods for comparing the equivalence of the actual content of one string with the content of another string: equals(other) and equalsIgnoreCase(other). See an example below.
String first = “first”;
String second = “second”;
String anotherFirst = “first”;
String secondInUpperCase = “SECOND”;
System.out.println(first.equals(second)); // false, the strings have different values
System.out.println(first.equals(anotherFirst)); // true, the strings have the same value
System.out.println(second.equals(secondInUpperCase)); // false, the strings have different cases
System.out.println(second.equalsIgnoreCase(secondInUpperCase)); // true, it ignores cases
Do not forget the rules when comparing strings.
Description
Our program should be able to display the grid at all stages of the game. Now we’re going to write a program that allows the user to enter a string representing the game state and correctly prints the 3x3 game grid based on this input. We’ll also add some boundaries around the game grid.
Objectives
In this stage, you will write a program that:
Reads a string of 9 symbols from the input and displays them to the user in a 3x3 grid. The grid can contain only X, O and _ symbols.
Outputs a line of dashes ————- above and below the grid, adds a pipe | symbol to the beginning and end of each line of the grid, and adds a space between all characters in the grid.
Examples
Examples below show how your output should look.
Notice that after Enter cells: comes the user input.
Example 1:
| O _ O |
| X X O |
Example 2:
| O X O |
| X |
Example 3:
| X O |
| _ X |
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(sc.next().replace(‘a’, ‘b’));
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
final Scanner sc = new Scanner(System.in);
String a = sc.nextLine().trim();
System.out.println(getChangedString(a.toCharArray()));
sc.close();
}
static String getChangedString(char[] arr) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 'a') {
arr[i] = 'b';
}
}
return new String(arr);
}
}
greater than
!= not equal to
== equal to
<= less than or equal to
= greater than or equal to
Any of the following comparison operators may be used to form the condition:
< less than
greater than
!= not equal to
== equal to
<= less than or equal to
= greater than or equal to
Any of the following comparison operators may be used to form the condition:
< less than
greater than
!= not equal to
== equal to
<= less than or equal to
= greater than or equal to
An if statement can be followed by an optional else statement, which executes when the condition evaluates to false.
You can use one if-else statement inside another if or else statement.
Instead of using nested if-else statements, you can use the else if statement to check multiple conditions.
Logical operators are used to combine multiple conditions.
Let’s say you wanted your program to output “Welcome!” only when the variable age is greater than 18 and the variable money is greater than 500.
One way to accomplish this is to use nested if statements
The OR operator (||) checks if any one of the conditions is true.
The condition becomes true, if any one of the operands evaluates to true.
The NOT !) logical operator is used to reverse the logical state of its operand. If a condition is true, the NOT logical operator will make it false.
A switch statement tests a variable for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.
Syntax:
switch (expression) {
case value1 :
//Statements
break; //optional
case value2 :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
The example below tests day against a set of values and prints a corresponding message.
A switch statement can have an optional default case.
The default case can be used for performing a task when none of the cases is matched.
The switch expression allows multiple comma-separated values per case and returns a value for the whole switch-case block.
The switch expression makes the switch-case block much shorter and doesn’t use a break statement.
A loop statement allows to repeatedly execute a statement or group of statements.
while loops:
A while loop statement repeatedly executes a target statement as long as a given condition is true.
The while loops check for the condition x > 0. If it evaluates to true, it executes the statements within its body. Then it checks for the statement again and repeats.
int x = 3;
while(x>=) {
System.out.println(x);
x—;
}The while loops check for the condition x > 0. If it evaluates to true, it executes the statements within its body. Then it checks for the statement again and repeats.
When the expression is tested and the result is false, the loop body is skipped and the first statement after the while loop is executed.
Another loop structure is the for loop. A for loop allows you to efficiently write a loop that needs to execute a specific number of times.
Syntax: for(initialization; condition; increment/ decrement){
statement(S)
}Initialization: Expression executes only once during the beginning of loop
Condition: Is evaluated each time the loop iterates. The loop executes the statement repeatedly, until this condition returns false.
Increment/Decrement: Executes after each iteration of the loop.
A do…while loop is similar to a while loop, except that a do…while loop is guaranteed to execute at least one time.
int x = 1;
do{
System.out.println(x);
x++;
}while(x<5);Notice that the condition appears at the end of the loop, so the statements in the loop execute once before it is tested.
Even with a false condition, the code will run once.
Loop control statements:
The break and continue statements change the loop’s execution flow.
The break statement terminates the loop and transfers execution to the statement immediately following the loop.
The continue statement causes the loop to skip the remainder of its body and then immediately retest its condition prior to reiterating. In other words, it makes the loop skip to its next iteration.
a || b is true if either a or b is true
(a||b) && c is true if c is true and either a or b is true.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner(System.in);
String s1 = scanner.nextLine();
String s2 = scanner.nextLine().replace(“ “, “”);
String st1 = s1.replaceAll(“ “, “”).trim();
String st2 = s2.replaceAll(“ “, “”).trim();
System.out.println(st1.equals(st2));
}
}
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner(System.in);
String input1 = scanner.nextLine();
String input2 = scanner.nextLine();
String a = input1.replace(" ", "");
String b = input2.replace(" ", "");
System.out.println(a.equalsIgnoreCase(b));
}
}
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s1 = scanner.nextLine();
String s2 = scanner.nextLine();
String s3 = s1.replaceAll(“ “, “”).trim();
String s4 = s2.replaceAll(“ “, “”).trim();
System.out.println(s3.equals(s4));
}
}
SOLUCION STAGE 2
package tictactoe;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter cells: ");
String cells = reader.next();
printCells(cells);
}
public static void printCells(String cells){
char[] ch = new char[cells.length()]; // create Chars Array
for (int i = 0; i < cells.length(); i++) {
ch[i] = cells.charAt(i); // Put String into Array of chars
}
System.out.println("---------");
int p = 0;
for (int i = 0; i < 3; i++){
System.out.print("| ");
for (int j = 0; j < 3; j++){
System.out.print(ch[p]+ " ");
p++;
}
System.out.print("|");
System.out.println();
}
System.out.println("---------");
}
}
OPCION 2
package tictactoe;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
Scanner scanner= new Scanner(System.in);
System.out.print(“Enter cells: “);
String symbols = scanner.nextLine();
System.out.println(“————-“);
System.out.println(“| “ + symbols.charAt(0) + “ “ + symbols.charAt(1) + “ “ + symbols.charAt(2) + “ |”);
System.out.println(“| “ + symbols.charAt(3) + “ “ + symbols.charAt(4) + “ “ + symbols.charAt(5) + “ |”);
System.out.println(“| “ + symbols.charAt(6) + “ “ + symbols.charAt(7) + “ “ + symbols.charAt(8) + “ |”);
System.out.println(“————-“);
}
}
OPCION 3
package tictactoe;
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
Game game = new Game();
System.out.print(“Enter cells: “);
String moves = scanner.next();
game.load(moves);
game.displayPositions();
}
}
class Game {
private final char[][] positions;
public Game(){
positions = new char[3][3];
}
public void displayPositions(){
System.out.println("---------");
for (char[] row : positions) {
System.out.print("| ");
for (char position : row) {
System.out.print(position + " ");
}
System.out.print("|\n");
}
System.out.println("---------");
}
public void load(String moves) {
int k = 0;
for (int i = 0; i < positions.length; i++) {
for (int j = 0; j < positions[i].length; j++) {
positions[i][j] = moves.charAt(k++);
}
}
}
}
<!—————— STAGE 3 ————————!>
Description
In this stage, we’re going to analyze the game state to determine if either of the players has already won the game or it is still ongoing, if the game is a draw, or if the user has entered an impossible game state (two winners, or with one player having made too many moves).
Objectives
In this stage, your program should:
Take a string entered by the user and print the game grid as in the previous stage.
Analyze the game state and print the result. Possible states:
Game not finished when neither side has three in a row but the grid still has empty cells.
Draw when no side has a three in a row and the grid has no empty cells.
X wins when the grid has three X’s in a row.
O wins when the grid has three O’s in a row.
Impossible when the grid has three X’s in a row as well as three O’s in a row, or there are a lot more X’s than O’s or vice versa (the difference should be 1 or 0; if the difference is 2 or more, then the game state is impossible).
In this stage, we will assume that either X or O can start the game.
You can choose whether to use a space or underscore _ to print empty cells.
Examples
The examples below show outputs and analysis results for different game states. Your program should work in the same way.
Notice that after Enter cells: comes the user input.
Example 1:
| X X X |
| O O _ |
X wins
Example 2:
| X O X |
| O X O |
X wins
Example 3:
| X O O |
| O X O |
O wins
Example 4:
| X O X |
| O O X |
Draw
Example 5:
| X O |
| O O X |
Game not finished
Example 6:
| X O |
| X O |
Impossible
Example 7:
| O |
| X |
Impossible
Example 8:
| O O |
| O O |
Impossible
<!—————Theory: Boolean and logical operations——————-!>
Boolean type
The boolean is a data type that has only two possible values: false and true. This is also known as the logical type.
This type is a common way in programming languages to represent something that has only two opposite states like on or off, yes or no, etc.
If you are writing an application that keeps track of door’s openings you’ll find it natural to use boolean to store current door state.
boolean open = true;
boolean closed = false;
System.out.println(open); // true
System.out.println(closed); // false
Important, you cannot assign an integer value to a boolean variable. In Java, 0 is not the same as false.
Logical operators
Variables of the boolean type are often used to build logical expressions using logical operators. Java has four logical operators NOT, AND, OR and XOR:
NOT is a unary operator that reverses the boolean value. It is denoted as !.
boolean f = false; // f is false
boolean t = !f; // t is true
AND is a binary operator that returns true if both operands are true, otherwise, it is false. It is denoted as &&.
boolean b1 = false && false; // false
boolean b2 = false && true; // false
boolean b3 = true && false; // false
boolean b4 = true && true; // true
OR is a binary operator that returns true if at least one operand is true, otherwise, it returns false. It is denoted as ||.
boolean b1 = false || false; // false
boolean b2 = false || true; // true
boolean b3 = true || false; // true
boolean b4 = true || true; // true
XOR (exclusive OR) is a binary operator that returns true if boolean operands have different values, otherwise, it is false.
boolean b1 = false ^ false; // false
boolean b2 = false ^ true; // true
boolean b3 = true ^ false; // true
boolean b4 = true ^ true; // false
The XOR operator is used less often than others. Just remember that Java has it. If you really need it, you can use it.
The precedence of logical operators
Below are the logical operations sorted in order of decreasing their priorities in expressions: ! (NOT), ^ (XOR), && (AND), || (OR).
So, the following variable is true:
boolean b = true && !false; // true, because !false is evaluated first
To change the order of execution you can use round brackets (…).
An example: trekking
As an example, let’s write a complex boolean expression that determines the possibility of trekking in summer and in other seasons.
boolean cold = false;
boolean dry = true;
boolean summer = false; // suppose now is autumn
boolean trekking = dry && (!cold || summer); // true, let’s go to trek!
Do not get confused in the expression above, otherwise, you will go trek in bad weather :) A programmer should understand not only arithmetic but also logical operations.
Short-circuiting evaluation
An interesting thing is that the && and || operators don’t evaluate the second argument if it isn’t necessary. When the first argument of the && operator evaluates to false, the overall value must be false; and when the first argument of the || operator evaluates to true, the overall value must be true. So:
false && … -> false, since it is not necessary to know what the right-hand side is;
true || … -> true, since it is not necessary to know what the right-hand side is.
This behavior is known as short-circuit evaluation (do not confuse it with an electrical short circuit). It reduces the computation time, but can also be used to avoid some errors in programs. We will discuss this in the following topics.
<!———Theory: Relational operators———-!>
List of relational operators
Java provides six relational operators to compare numbers:
== (equal to)
!= (not equal to)
(greater than)
= (greater than or equal to)
< (less than)
<= (less than or equal to)
The result of applying a relational operator to its operands takes the boolean type (true or false) regardless of the types of operands.
Comparing integer numbers
Relational operators allow you to easily compare, among other things, two integer numbers. Here are some examples below:
int one = 1;
int two = 2;
int three = 3;
int four = 4;
boolean oneIsOne = one == one; // true
boolean res1 = two <= three; // true
boolean res2 = two != four; // true
boolean res3 = two > four; // false
boolean res4 = one == three; // false
Relational operators can be used in mixed expressions together with arithmetic operators. In such expressions, relational operators have lesser priorities than arithmetic operators.
In the following example, first of all, two sums are calculated, and then they are compared using the operator >.
int number = 1000;
boolean result = number + 10 > number + 9; // 1010 > 1009 is true
The result is true.
Joining relational operations using logical operators
In Java, you cannot write an expression like a <= b <= c. Instead, you should join two boolean expressions using logical operators like || and &&.
Here is an example:
number > 100 && number < 200; // it means 100 < number < 200
Also, we can write parts of the expression in parentheses to improve readability:
(number > 100) && (number < 200);
But parentheses are not necessary here because relational operators have a higher priority than logical operators.
Here is a more general example of variables.
int number = … // it has a value
int low = 100, high = 200; // borders
boolean inRange = number > low && number < high; // joining two expressions using AND.
The code checks if the value of number belongs to a range.
So, logical operators allow you to join a sequence of relational operations into one expression.
An example of a program
Suppose there are three children in the sports class. You want to check if their heights are arranged in descending order. The following program reads three integer numbers h1, h2, and h3 and then checks if h1 >= h2 and h2 >= h3. Note that h means the height of a child.
import java.util.Scanner;
public class CheckAscOrder {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int h1 = scanner.nextInt();
int h2 = scanner.nextInt();
int h3 = scanner.nextInt();
boolean descOrdered = (h1 >= h2) && (h2 >= h3);
System.out.println(descOrdered);
}
}
Here are several input-output pairs:
Input 1
185 178 172
Output 1
true
Input 2
181 184 177
Output 2
false
It is possible not to use an additional variable to store the boolean result before output:
System.out.println((h1 >= h2) && (h2 >= h3));
But when your condition is quite long, it is hard to understand what the code does without some explanations. A variable with a good name provides such an explanati
<!—————Theory: Conditional statement —————-!>
The conditional statement is a construction that allows a program to perform different computations depending on the value of a Boolean expression. If it is true, the program performs one computation; otherwise, if it is false, the program performs another computation. Here are some examples of Boolean expressions: a > b, i - j == 1, and so on.
The conditional statement has different forms. We will use all of them.
The single if-case
The simplest form of the conditional statement consists of the keyword if, a Boolean expression, and a body enclosed in curly braces.
if (expression) {
// body: do something
}
If the expression is true, the statements inside the code block are executed; otherwise, the program skips them.
See the following example.
int age = …; // it has a value
if (age > 100) {
System.out.println(“Very experienced person”);
}
In this example, if the age is greater than 100 the code prints “Very experienced person”, otherwise, it does nothing.
Sometimes you will see a situation when the expression in a condition is a single boolean type variable. Instead of writing b == true or b == false, use this variable (or its negation with !) as the Boolean expression:
boolean b = …; // it is true or false
if (b) { // or !b
// do something
}
A conditional statement can be used in any place in a program where the statement is expected. It can be even nested inside another conditional statement to perform multistage checks.
The if-else-cases
The if-case above can be extended with the keyword else and another body to do alternative actions when the expression is false.
if (expression) {
// do something
} else {
// do something else
}
In this case, if the expression is true, then the first code block is executed; otherwise, the second code block is executed, but not both together.
In the example below, the program outputs different text depending on the value of num (even or odd).
Note, a number is even if it can be divided exactly by 2; otherwise it’s odd.
int num = …; // the num is initialized by some value
if (num % 2 == 0) {
System.out.println(“It’s an even number”);
} else {
System.out.println(“It’s an odd number”);
}
Since a number can only be even or odd, only one message will be displayed. If num is 10, the program outputs “It’s an even number”. If the value is 11, it outputs “It’s an odd number”.
The if-else-if-cases
The most general form of the conditional statement consists of several conditions and else-branches.
if (expression0) {
// do something
} else if (expression1) {
// do something else 1
// …
} else if (expressionN) {
// do something else N
}
The following code outputs recommendations about what computer you need to buy depending on your budget.
long dollars = …; // your budget
if (dollars < 1000) {
System.out.println(“Buy a laptop”);
} else if (dollars < 2000) {
System.out.println(“Buy a personal computer”);
} else if (dollars < 100_000) {
System.out.println(“Buy a server”);
} else {
System.out.println(“Buy a data center or a quantum computer”);
}
This conditional statement has four branches: dollars < 1000, dollars < 2000, dollars < 100_000 and dollars >= 100_000. If the value of dollars is 10_000 it prints “Buy a server”.
A conditional statement with multiple branches creates a decision tree, whose nodes consist of boolean expressions, and each branch is marked with true or false. The true-branch leads to a block of statements to be executed and a false-branch leads to the next condition to be checked. The last false-branch means “in all other cases”.
When talking about conditions programmers often use the term “control flow statements”. Control flow is the order in which various parts of a program are executed. You will probably meet this term in our topics and on other external resources.
The picture below demonstrates such a tree for the example with computers.
Decision tree for buying a laptop
This example completes our examination of conditional statements
<!———- Theory: Ternary operator—————!>
the ternary operator is an operator which evaluates a condition and chooses one of two cases to execute. It is also called the conditional operator. The operator can be considered as a form of the if-then-else statement. The ternary operator should not be confused with the conditional statement, despite their similarity. This operator can be used in places where an expression is expected.
Sometimes the ternary operator is more readable and concise than the corresponding if statement.
Let’s start learning this operator with an example. Suppose we have to find the maximum of two int variables, a and b. It is easy to write using a conditional statement:
int a = …;
int b = …;
int max = …;
if (a > b) {
max = a;
} else {
max = b;
}
The equal ternary operator looks like:
int max = a > b ? a : b;
This code is more concise than the code above, isn’t it?
The general syntax of the ternary operator is the following:
result = condition ? trueCase : elseCase;
It includes two special symbols ? and :.
Here, the condition is a Boolean expression that evaluates to either true or false. If this expression is true, the ternary operator evaluates trueCase, otherwise elseCase is evaluated. It is important that trueCase and elseCase are expressions which can be reduced to a common type. This type determines the type of the result.
Let’s consider another example that prints whether a number is even or odd.
int num = …; // it’s initialized by a value
System.out.println(num % 2 == 0 ? “even” : “odd”);
This ternary operator consists of three operands: the value of the expression num % 2 == 0, and two string literals “even” and “odd”. The result type of it is String.
Note, Java allows us to nest one ternary operator into another one, but it can be less readable than the corresponding conditional statement. If you do this, be careful.
Imagine you need to compare 2 integer numbers and print equal in case they are equal, more if the first one has a bigger value than the second and less otherwise. The task can be solved using a combination of 2 ternary operators:
int a = …; // it’s initialized by a value
int b = …; // it’s initialized by a value
String result = a == b ? “equal” :
a > b ? “more” : “less”;
At first, the outer ternary operator checks equality of a and b numbers. If it is true, equal is printed, otherwise, the nested ternary operator a > b ? “more” : “less” is calculated. To improve readability, the whole expression is divided into 2 lines.
<!————Theory: The for-loop————!>
Sometimes we need to repeat a block of code a certain number of times. To do this, Java provides the for-loop. This loop is often used to iterate over a range of values or through an array. If the number of iterations or the range borders are known, it is recommended to use the for-loop. If they are unknown, the while-loop may be the preferable solution.
The basic for-loop syntax
The for-loop has the following basic syntax:
for (initialization; condition; modification) {
// do something
}
Parts of the loop:
the initialization statement is executed once before the loop begins; usually, loop variables are initialized here;
the condition is a Boolean expression that determines the need for the next iteration; if it’s false, the loop terminates;
the modification is a statement that changes the value of the loop variables; it is invoked after each iteration of the loop; usually, it uses increment or decrement to modify the loop’s variable.
Inside the loop’s body, the program can perform any correct Java statements. It can even contain other loops.
The order of execution for any for-loop is always the same:
the initialization statement;
if the condition is false then terminate the loop;
if the condition is true, then the loop’s body is executed;
the modification is performed;
go to stage 2 (condition).
Let’s write a loop for printing integer numbers from 0 to 9 on the same line.
int n = 9;
for (int i = 0; i <= n; i++) {
System.out.print(i + “ “); // here, a space is used to separate numbers
}
The code displays:
0 1 2 3 4 5 6 7 8 9
The variables declared in the initialization statement are visible only inside the scope that includes all parts of the loop: the condition, the body, and the modification. The integer loop variables are often named as i, j, k, or index.
Here’s another example. Let’s calculate the sum of the integer numbers from 1 to 10 (inclusive) using the for-loop.
int startIncl = 1, endExcl = 11;
int sum = 0;
for (int i = startIncl; i < endExcl; i++) {
sum += i;
}
System.out.println(sum); // it prints “55”
Skipping parts
The initialization statement, the condition, and the modification parts are optional, the for loop might not have all of them.
It is possible to declare a variable outside the loop:
int i = 10;
for (; i > 0; i—) {
System.out.print(i + “ “);
}
Moreover, it is also possible to write an infinite loop without these parts at all:
for (;;) {
// do something
}
Nested loops
It’s possible to nest one for-loop in another for-loop. This approach is used to process multidimensional structures like tables (matrices), data cubes, and so on.
As an example, the following code prints the multiplication table of numbers from 1 to 9 (inclusive).
for (int i = 1; i < 10; i++) {
for (int j = 1; j < 10; j++) {
System.out.print(i * j + “\t”);
}
System.out.println();
}
It outputs:
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81
Write a program that prints the product of all integer numbers from a to b (a < b).
Include a and exclude b from the product
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
int b = scan.nextInt();
long result = a;
for (long i = a; i < b - 1; i++) {
result += i * result;
}
System.out.println(result);
}
}
//opcion 2
import java.io.BufferedInputStream;
import java.math.BigInteger;
import java.util.Scanner;
import java.util.stream.IntStream;
class Main {
public static void main(String[] args) {
// put your code here
try (Scanner scanner = new Scanner(new BufferedInputStream(System.in))) {
final int start = scanner.nextInt();
final int end = scanner.nextInt();
final BigInteger res = IntStream.range(start, end)
.mapToObj(BigInteger::valueOf)
.reduce(BigInteger.ONE, BigInteger::multiply);
System.out.println(res);
}
}
}
//opcion 3
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner(System.in);
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
long product = num1;
for (int i = num1 + 1; i < num2; i++) {
product *= i;
}
System.out.println(product);
}
}
Choose all correct ways to write the for-loop.
a)
for (int i = 0; i < 10; i++) { / body / }
b)
int i = 0; for (; i < 10; ++i) { / body / }
c)
for (int k = 10; k > 1; ) { k—; / some statements / }
d)
for (;;) { / body / }
Given a sequence of natural numbers, not exceeding 30000. Find the maximum element divisible by 4. There is always an element divisible by 4 in the sequence and the number of elements does not exceed 1000.
As input, the program receives the number of elements in the sequence n (first line) and then the elements themselves (next n lines). The program should print a single number: the maximum element of the sequence divisible by 4.
Try to solve this problem by using a for-loop.
Report a typo
HINT by
avatar
Joe T
/**Given a sequence of natural numbers, not exceeding 30000.
The program should print a single number: the maximum element of the sequence divisible by 4
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner sc = new Scanner(System.in);
int elements = sc.nextInt();
int num;
int max = 0;
for (int i = 0; i < elements; i++) {
num = sc.nextInt();
if (num % 4 == 0 && num > max) {
max = num;
}
}
System.out.print(max);
}
}
//opcion 2
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numOfNums = scanner.nextInt();
int max = 0;
for (int i = 0; i < numOfNums; i++) {
int input = scanner.nextInt();
if (input > max && input % 4 == 0) {
max = input;
}
}
System.out.println(max);
}
}
Find the sum of numbers divisible by 6 in the given sequence of natural numbers.
The first line of the input is the number of elements in the sequence; the next lines are the elements themselves.
It is guaranteed, that there is always a number divisible by 6 in the sequence
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int r = 0;
for (int i = 0; i < n; i++) {
int c = sc.nextInt();
if (c % 6 == 0) {
r = r + c;
}
}
System.out.println(r);
}
}
//opcion 2
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int end = userInput.nextInt();
int sum = 0;
for (int i = 0; i < end; i++) {
int temp = userInput.nextInt();
if (temp % 6 == 0) {
sum += temp;
}
}
System.out.println(sum);
}
}
//opcion 3
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner(System.in);
int numElements = scanner.nextInt();
int sum = 0;
for (int i = 1; i <= numElements; i++) {
int val = scanner.nextInt();
if (val % 6 == 0) {
sum += val;
}
}
System.out.println(sum);
}
}