# Casting

Casting allows us to change a variable's type to better suit our needs.

## How Casting Works

Lets say we want to turn a double into an integer, or an integer into a double.

To change a variable's type we just add the type in between parentheses to cast it.

Consider the following:

```java
int doubleToInt = (int)10.95;
// This will become '10'
```

### Casting an Integer to a Double

To cast an integer value to a double we add `(double)` in front of the variable.

```java
int intVal = 10;

// Our 'doubleVal' variable is now '10.0'
double doubleVal = (double)intVal;
```

### Casting a Double to an Integer

To cast a double to an integer we add `(int)` in front of the variable. It is important to remember our new integer value will truncate the decimal.

```java
double doubleVal = 7.4;

// Our 'intVal' variable is now '7'
int intVal = (int)doubleVal;
```

## Division with Casting

If we divide two integers, even if we are setting them to a double, we will always be returned an integer.

```java
int currResidents = 50;
int floorTotal = 56;

double average = floorTotal / currResidents;
// 'average' will return the value '1'
```

We can get the correct answer by casting one of the variables to a double.

```java
int currResidents = 50;
int floorTotal = 56;

double average = (double)floorTotal / currResidents;
// We now have the value of '1.12'
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://codehs.gitbook.io/apjava/basic-java/casting.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
