# Exercises with variables in Java

After the previous post about variables in java, in this one, I leave some exercises to practice what I explained then. This will be the way of acting for the rest of the Java topics, firstly I explain the topic and then, in the following post, I will propose a series of exercises and their solutions.

There are several possible solutions to solve the same problem, some more efficient than others. Here you can see a possible solution for each proposed exercise, which is not the only one possible.

## Exercise 1

For now, we continue using the online compiler

In this exercise, we have to correct the errors of the following program so that it runs properly

``````public class AplicacionJava {
public static void main(String[] args) {
int a,b;c;
a = 10; b=10;
c =a+b;
int cont;
for (int i=a;i<c;i++){
cont++;
System.out.pritln ("counter: "cont);
System.out.println(b+cont);
}
}
}``````

### Solution

A possible solution is:

``````public class AplicacionJava {
public static void main(String args[]) {
int a,b,c;
a = 10; b=10;
c =a+b;
int cont=0;
for (int i=a;i<c;i++){
cont++;
System.out.println("counter: " + cont);
System.out.println(b+cont);
}
}
}``````

## Exercise 2

Develop a program with the following characteristics:

The program must have two variables of type double. The value of these variables is hardcoded, the first is 5 and the second is 7. And the program must display the following lines on the screen.

``````First value = <value stored in first variable>

Secondo value = <value stored in second variable>

Multiplication = <result of multiplying both values>

Division= <result of dividing both values>``````

### Solution

A possible solution is:

``````public class MiPrograma {
public static void main(String args[]) {
double x=5;
double y=7;
System.out.println("First value = " + x);
System.out.println("Second value = " + y);
System.out.println("Multiplication = " + x*y);
System.out.println("Division = " + x/y);
}
}``````

If we execute this program, we would get:

``````First value = 5.0
Second value = 7.0
Multiplication = 35.0
Division = 0.7142857142857143``````

NOTE:

This post is part of the “Java” collection that reproduces the notes of the class that I teach on the subject at ESIC University. You can see the index of this collection here.