Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Operações Matemáticas em Java | Tipos Básicos e Operações
Fundamentos de Java

book
Operações Matemáticas em Java

Operadores

Observamos que utilizamos operadores matemáticos básicos como +, -, / e *. Esses operadores são familiares para nós de calculadoras ou da matemática; você também pode usá-los em um editor de código.

Vamos revisar o básico:

  • + – adição;

  • - – subtração;

  • / – divisão;

  • * – multiplicação.

Você pode utilizar esses quatro operadores fundamentais com tipos de dados numéricos (byte, short, long, float, double).

Vamos explorar o uso desses operadores com um exemplo de código:

java

Main

copy
package com.example;

public class Main {
public static void main(String[] args) {
// Creating an int variable with value 10
int a = 10;
// Creating an int variable with value 17
int b = 17;
// Creating an int variable to store the sum of `a` and `b`
int res = a + b;
// Printing the result to the console
System.out.println(res);
}
}
1234567891011121314
package com.example; public class Main { public static void main(String[] args) { // Creating an int variable with value 10 int a = 10; // Creating an int variable with value 17 int b = 17; // Creating an int variable to store the sum of `a` and `b` int res = a + b; // Printing the result to the console System.out.println(res); } }

Como podemos ver, a variável res armazena o valor 27, que é a soma de 10 e 17.

Vamos analisar mais alguns exemplos:

java

Main

copy
package com.example;

public class Main {
public static void main(String[] args) {
// Creating an int variable with the sum of 16 and 4
int plus = 16 + 4;
/* Creating an int variable with the value of the subtraction
of the `plus` variable and 10 */
int minus = plus - 10;
/* Variable that holds the result of multiplying
the `minus` variable by 4 */
int multiplying = minus * 4;
/* Using subtraction and division operations
on the `multiplying` variable */
int complexDivision = (multiplying - 4) / 9;
// Printing the result to the console
System.out.println(complexDivision);
}
}
12345678910111213141516171819
package com.example; public class Main { public static void main(String[] args) { // Creating an int variable with the sum of 16 and 4 int plus = 16 + 4; /* Creating an int variable with the value of the subtraction of the `plus` variable and 10 */ int minus = plus - 10; /* Variable that holds the result of multiplying the `minus` variable by 4 */ int multiplying = minus * 4; /* Using subtraction and division operations on the `multiplying` variable */ int complexDivision = (multiplying - 4) / 9; // Printing the result to the console System.out.println(complexDivision); } }

Podemos usar tanto números quanto variáveis em nossas operações. No entanto, vale lembrar que criar múltiplas variáveis aumenta o uso da stack memory. Portanto, recomenda-se utilizar números regulares sempre que possível. Além disso, podemos observar que a precedência dos operadores é respeitada. Operações dentro de parênteses são realizadas primeiro, seguidas por multiplicação ou divisão, e então adição ou subtração.

Dessa forma, podemos realizar operações simples com diferentes dados numéricos.

Ordem das operações

Java segue os princípios básicos da matemática, e as operações também possuem uma ordem de execução. Vamos analisar um exemplo:

java

main

copy
package com.example;

public class Main {
public static void main(String[] args) {
int result = (10 + 5) * 2 - 8 / 4 + 1;
System.out.println(result);
}
}
12345678
package com.example; public class Main { public static void main(String[] args) { int result = (10 + 5) * 2 - 8 / 4 + 1; System.out.println(result); } }

Aqui chegamos ao resultado realizando operações sequencialmente. Vamos analisar a ordem:

Assim, é possível priorizar a execução das operações utilizando parênteses comuns, assim como na aritmética.

Tarefa

Swipe to start coding

  1. Some os valores das variáveis firstNumber e secondNumber.
  2. Divida a soma pelo valor da variável thirdNumber.
  3. Armazene o resultado final na variável result.

Solução

java

solution

package com.example;

public class Main {
public static void main(String[] args) {
int firstNumber = 9;
int secondNumber = 4;
double thirdNumber = 2.0;
// Use variables instead of direct values
double result = (firstNumber + secondNumber) / thirdNumber;
System.out.println(result);
}
}
Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 4
package com.example;

public class Main {
public static void main(String[] args) {
int firstNumber = 9;
int secondNumber = 4;
double thirdNumber = 2.0;
// Use variables instead of hardcoded values
double result = ___
System.out.println(result);
}
}

Pergunte à IA

expand
ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

We use cookies to make your experience better!
some-alt