CodeGym /Java Course /Module 1. Java Syntax /Life hacks: how to write code better and faster

Life hacks: how to write code better and faster

Module 1. Java Syntax
Level 4 , Lesson 4
Available

1. Expressions vs statements

In Java, it is helpful to distinguish between two categories: statements and expressions. A statement is usually said to be executed, while an expression is said to be evaluated. But that's not the most important thing.

The main difference between a statement and an expression is that evaluating an expression has a result. And this result has a type, and it can be assigned to a variable or used in some other expression.

Examples:

Code Notes
int x; Statement
(a < 10) Expression whose type is boolean
i++; Expression whose type is the same as the type of the i variable
x = 5; Expression whose type is the same as the type of the x variable

And what does this give us?

First, we can take advantage of the fact that many statements are actually expressions (meaning they evaluate to a value). For example, code like this will work:

Code Notes
int x, y, z;
x = y = z = 1;
int x, y, z;
x = (y = (z = 1))

Second, if we want, we can ignore the result of evaluating an expression.

Code Code where we ignore the result:
int x = scanner.nextInt();
boolean m = (5 < 10);
scanner.nextInt();
(5 < 10);

We ignore the result of evaluating an expression, for example, if the expression involves doing something useful, and this action is what is important to us, not the result itself.


2. Ternary operator

This life hack is already more interesting than the previous one. Java has a special ternary operator. Its syntax is somewhat similar to the syntax for the if-else statement:

Condition ? Expression 1 : Expression 2;

If condition is true, then Expression 1 is evaluated, otherwise Expression 2 is evaluated. The condition is followed by a question mark, and the two expressions are separated by colon.

The main difference between the ternary operator and an if-else statement is that the ternary operator is an expression, which means we can assign its result to something.

For example, suppose we want to calculate the minimum of two numbers. Using the ternary operator, this code would look like this:

int a = 2;
int b = 3;
int min = a < b ?  a : b;

Or, let's say you need to assign different values to a variable depending on some condition. How do you do that?

One option is to use an if-else statement:

int age = 25;
int money;
if (age > 30)
   money = 100;
else
   money = 50;

The second option is to use the ternary operator, that is, shorthand for the if-else statement:

int age = 25;
int money = age > 30 ? 100 : 50;

So which is better to use — an if-else statement or the ternary operator? In terms of execution speed, there isn't much difference. This is more a matter of code readability. And this is a very important point: the code must not only work correctly, but also be easy for other programmers to read.

The simplest rule is this: if the code fits on one line, then use the ternary operator; but if it does not fit on one line, then it is better to use an if-else statement.


4
Task
New Java Syntax, level 4, lesson 4
Locked
10 numbers
Display the numbers from 1 to 10 using a while loop. Each value should be on a new line.
4
Task
New Java Syntax, level 4, lesson 4
Locked
From 10 to 1
Display the numbers from 10 to 1 using a while loop. Each value should be on a new line.

3. Comparing real numbers

As mentioned earlier, you can't just grab real numbers and compare them. There is always the possibility that some significant digits may be discarded, causing unexpected side effects.

That's why there is a time-tested approach. If two real numbers differ by a very small value, then they can be considered to be equal. Example:

double a = 1.000001;
double b = 1.000002;
if ( (b - a) < 0.0001 )
   System.out.println("The numbers are equal");
else
   System.out.println("The numbers are not equal");

But that's not all we have to worry about, since the difference between the numbers may well turn out to be negative. So for this approach to work, you need to compare not just the difference between the numbers, but the absolute value of the difference between the numbers: |a-b|

Java has a method for calculating the absolute value of a number: Math.abs():

int m = Math.abs(value);

As a result, the corrected version of our example above will look like this:

double a = 1.000001;
double b = 1.000002;

if ( Math.abs(b - a) < 0.0001 )
   System.out.println("The numbers are equal");
else
   System.out.println("The numbers are not equal");

4
Task
New Java Syntax, level 4, lesson 4
Locked
You can't have too much of a good thing
Use the keyboard to enter a string and a number N greater than 0. Use a while loop to display the string N times. Each value should be on a new line. Example input: abc 2 Example output: abc abc
4
Task
New Java Syntax, level 4, lesson 4
Locked
Seeing dollars in your future
Use a while loop to display a 10x10 square of dollar signs. Don't separate the symbols in each line. Example output: $$$$$$$$$$$ $$$$$$$$$$ $$$$$$$$$$ $$$$$$$$$$ $$$$$$$$$$ $$$$$$$$$$ $$$$$$$$$$ $$$$$$$$$$ $$$$$$$$$$ $$$$$$$$$$
Comments (16)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Anonymous #11416402 Level 24, China
4 November 2023
Actually, is it a good example? I don't know how it can prove that "we can take advantage of the fact that many statements are actually expressions (meaning they evaluate to a value)". I mean if (z = 1) is an expression.

int x, y, z;
x = y = z = 1;
Parsa Level 62, Bangalore, India Expert
13 October 2023
How are i++ and x=5 expressions? Shouldn't they be statements? What does (5<10) alone do? How is that useful?
Michele Sinisi Level 23, Bitonto , Italy
7 March 2024
5<10 always has true value! so assigning it to a variable it's like saying m = true, like a placeholder. i++ is like saying i = i + 1 , which is indeed an expression, same applies for x = 5 (just simpler expression)
Alexander Yaitskiy Level 4, Dubai, United Arab Emirates
22 August 2023
scanner.nextDouble(); Goog task
Aishwarya Level 4, deagu , South Korea
2 May 2023
what is advantage of using method math.abs(value) in java?
Harshit Garg Level 23, Chandigarh, India Expert
2 August 2023
it makes any negative value positive
Nitin Saini Level 4, India
23 March 2023
@john
Nitin Saini Level 4, India
23 March 2023
i dont know
23 March 2023
why are all the tasks premium on pc?
15 March 2023
We've been using .nextLine() to assign value to a variable. We can ignore the result of this expression if we just want to make the cursor move one line in preparation for the next (?). [It would be nice to have more examples of these instances.]
Anonymous #11416402 Level 24, China
4 November 2023
yes, I think it works. In my opinion, .nextLine() could absorb a whole line of characters in the input stream buffer, so we can use it to skip the rest of the current line. :)
GioGTelian Level 10
13 October 2022
I love this it simplify a lot :D
sumit singh Level 5, India
7 August 2022
i got stuck there but after a min of struggling i got the answer ...very happy.
atb2199 Level 19, United Kingdom, United Kingdom
18 August 2022
Never give up :D