0% found this document useful (0 votes)
8 views15 pages

Java Operators and Incrementing Variables

The document provides examples of arithmetic operators in Java including addition, subtraction, multiplication, division, increment, decrement, modulo, and order of operations. It demonstrates how to perform calculations with integers and doubles, as well as how to cast between types. Examples are given for addition, subtraction, multiplication, division, incrementing, decrementing, modulo, and order of operations using various data types. Challenges are provided to modify the examples, such as changing types or operators.

Uploaded by

Tushar Mudgal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views15 pages

Java Operators and Incrementing Variables

The document provides examples of arithmetic operators in Java including addition, subtraction, multiplication, division, increment, decrement, modulo, and order of operations. It demonstrates how to perform calculations with integers and doubles, as well as how to cast between types. Examples are given for addition, subtraction, multiplication, division, incrementing, decrementing, modulo, and order of operations using various data types. Challenges are provided to modify the examples, such as changing types or operators.

Uploaded by

Tushar Mudgal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

The

addition operator works as you would expect with numbers.

[Link](7 + 3);

You can also add two variables together.

int a = 7;
int b = 3;
[Link](a + b);

challenge

Make a of type double(e.g. double a = 7.0; )?


Make b a negative number (e.g. int b = -3; )?
Make b an explicitly positive number (e.g. int b = +3; )
Incrementing a variable means to change the value of a variable
by a set amount. You will most often have a counting variable,
which means you will increment by 1.

int a = 0;
a = a + 1;
[Link](a);

a = a + 1

The variable a appears twice on the same line of code. But each
instance of a refers to something different.

How to Read a = a + 1

++ +=

Incrementing is a common task for programmers. Many


programming languages have developed a shorthand for a = a +
1 because of this, a++ does the same thing as a = a + 1 .
int a = 0;
int b = 0;
a = a + 1;
b++;
[Link](a);
[Link](b);

In the cases you need to increment by a different number, you


can specify it using the += operator. You can replace b++; with
b+=1; in the above code and get the same result.

challenge

Change b such that b+=2 ?


Change b such that b+=-1 ?

Change b such that b-=1 ?


String Concatenation

String Concatenation
String concatenation is the act of combining two strings together.
This is done with the + operator.

String a = "This is an ";


String b = "example string";
String c = a + b;
[Link](c);

challenge

What happens if you:


Concatenate two strings without an extra space (i.e. a =
"This is an" )?

Use the += operator instead of the + operator


(i.e. a+=b; )?
Add 3 to a string?
Add "3" to a string?
int a = 10;
int b = 3;
int c = a - b;
[Link](c);

challenge

Change b to -3 ?
Change c to c = a - -b ?

Change b to 3.0 ?

-- -=

Decrementing is the opposite of incrementing. Just like you can


increment with ++ , you can decrement using -- .

int a = 10;
a--;
[Link](a);

Like += , there is a shorthand for decrementing a variable - -= .


You might be able to concatenate strings with the + operator,
but you cannot use the - operator with them.

String a = "one two three";


String b = "one";
String c = a - b;
[Link](c);
Division in Java is done with the / operator

double a = 25;
double b = 4;
[Link](a / b);

challenge

Change b to 0 ?
Change b to 0.5 ?
Change the code to

double a = 25;
double b = 4;
a /= b;
[Link](a);

Hint
/= works similar to += and -=

Normally, you use double in Java division since the result


usually involves decimals. If you use integers, the division
operator returns an int . This “integer division” does not round
up, nor round down. It removes the decimal value from the
answer.

.guides/img/intDivision

int a = 5;
int b = 2;
[Link](a / b);
Type casting (or type conversion) is when you change the data
type of a variable.

int numerator = 40;


int denominator = 25;
[Link]( numerator / denominator);
[Link]( (double) numerator / denominator);

numerator and denominator are integers, but (double) converts


numerator into a double.

challenge

Cast only denominator to a double?


Cast both numerator and denominator to a double?
Cast the result to a double (i.e. (double)(numerator /
denominator) )?

More Info
If either or both numbers in Java division are a double , then
double division will occur. In the last example, numerator and
denominator are both int when the division takes place - then
the integer division result is converted to a double.

What do you think the code below will print?


int a = 5;
String b = "3";
[Link](a + b);

When you try to print an integer and a string added together,


Java will automatically convert the integer into a string. This
occurs because the system attempts to perform string
concatenation. This is why the code above resulted in 53 . To
perform integer addition, you can convert b to an integer.

int a = 5;
String b = "3";
[Link](a + [Link](b));

Data read from the keyboard or a file is always stored as a string.


If you want to use this data, you will need to know how to
convert it to the proper data type.

challenge

Parse a String to a double using [Link]()

Parse a String to a boolean using [Link]()

Convert a different type to a string with [Link]()


Modulo is the mathematical operation that performs division but
returns the remainder. The modulo operator is % .

Modulo

int modulo = 5 % 2;
[Link](modulo);

challenge

Change modulo to 5 % -2 ?
Change modulo to 5 % 0 ?
Change modulo to 5 % 2.0 ?
Java uses the * operator for multiplication.

int a = 5;
int b = 10;
[Link](a * b);

challenge

Change b to 0.1 ?
Change b to -3 ?

Hint
*= works similar to += and -=
Java uses the PEMDAS method for determining order of
operations.

PEMDAS

The code below should output 10.0 .

int a = 2;
int b = 3;
int c = 4;
double result = 3 * a - 2 / (b + 5) + c;
[Link](result);

Explanation
The first step is to compute b + 5 (which is 8 ) because it is
surrounded by parentheses.
Next, do the multiplication and division going from left to
right. 3 * a is 6 .
2 divided by 8 is 0 (remember, the / operator returns an
int when you use two int s so 0.25 becomes 0 ).

Next, addition and subtraction from left to right - 6 - 0 to get


6 .

Finally, add 6 and 4 together to get 10.0 .


challenge

5 + 7 - 10 * 3 /0.5
Solution
-48.0
(5 * 8) - 7 % 2 - (-1 * 18)
Solution
57.0
9 / 3 + (100 % 0.5) - 3
Solution
0.0

Common questions

Powered by AI

When adding a string to a numerical data type in Java, the numerical value is implicitly converted to a string, resulting in string concatenation rather than arithmetic addition. This can lead to unexpected results if numerical addition is intended, necessitating explicit parsing or type conversion to preserve numeric operations .

Type casting is crucial in scenarios requiring alteration of a variable's data type to leverage specific features or avoid data loss (e.g., converting integers to doubles for precise division results). It's essential when handling operations that require consistent data types or when integrating disparate systems that may operate on different data representations .

Increment and decrement operations provide a shorthand method for increasing or decreasing a variable's value. Incrementing (a++) is equivalent to a = a + 1, and decrementing (a--) is equivalent to a = a - 1. This streamlines the code and reduces complexity in scenarios where counting or traversal across index-based structures is required .

The addition operator is used to perform arithmetic addition when applied to numbers, where it combines numerical values. When used with strings, it serves as a string concatenation operator, combining two strings into one without actual numeric addition .

Compound assignment operators, such as += and /=, provide a concise way to update a variable's value by a specified amount or ratio in a single operation. This not only enhances readability by removing redundancy (e.g., a += b simplifies a = a + b) but also reduces potential errors from variable shadowing, making the code more maintainable .

Understanding the order of operations is crucial as it dictates the evaluation sequence of operators in expressions, significantly affecting computation outcomes. Misinterpreting this sequence, particularly in expressions involving nested operations or mixed data types, can result in unintentional results, logic errors, and increased debugging complexity .

In Java, integer division truncates the decimal part, returning only the integer quotient, which can lead to a loss of precision. To address this issue, type casting can be used to convert integers to doubles before the division, ensuring that the division operator performs floating-point division and retains the decimal values .

Parentheses override default operator precedence, forcing operations within them to be evaluated first, and can be strategically used to clarify intention or prevent logical errors in complex expressions. They are particularly useful in ensuring specific calculation sequences, thereby making the code easier to read and maintain .

Implicit type conversion, or casting, occurs when operands of different types are used in expressions. Java automatically promotes smaller data types to larger ones, such as converting ints to doubles during mixed-type arithmetic, potentially affecting precision and accuracy if not carefully managed .

The modulo operation returns the remainder after division. When handling negative numbers, the sign of the result is determined by the dividend, impacting situations like cyclic rotations where offsets can significantly alter behavior. For instance, 5 % -2 yields 1 because the angle follows the sign of the divisor .

You might also like