This week's book giveaway is in the Artificial Intelligence and Machine Learning forum.We're giving away four copies of TensorFlow 2.0 in Action and have Thushan Ganegedara on-line!See this thread for details.
Win a copy of TensorFlow 2.0 in Action this week in the Artificial Intelligence and Machine Learning forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Liutauras Vilda
• Paul Clapham
• Bear Bibeault
• Jeanne Boyarsky
Sheriffs:
• Ron McLeod
• Tim Cooke
• Devaka Cooray
Saloon Keepers:
• Tim Moores
• Tim Holloway
• Jj Roberts
• Stephan van Hulst
• Carey Brown
Bartenders:
• salvin francis
• Scott Selikoff
• fred rosenberger

# Having trouble with "min = max = nums[0];"

Ranch Hand
Posts: 109
1
I am working through a beginners guide on Core Java.
I have started on Arrays and I don't know if I missed
something in earlier lessons but I need to understand
how the values are obtained in the following code:

Here:

min = max = nums[0];
for(int i = 1; i < 10; i++) {
if(nums[i] < min) min = nums[i];
if(nums[i] > max) max = nums[i];

How does the program determine "if(nums[i] < min"  or "if(nums[i] > max" ?

min and max are never initialized with a value. It's just "min = max = nums[0];

To me, this looks like min 0 = max 0 = nums[0]; and therefore -9 would be < 0 or min and 18 would be > 0 or max.

Not feeling especially sharp at the moment.

Marshal
Posts: 70724
288
• 4

Ray Gilbert wrote:. . . a beginners guide on Core Java.  . . .

Which book? I hope I haven't bought a book telling me to use two assignment operators = in the same line. It might compile, but it is hardly good style
I recommend you use an array initialiser to initialise arrays if possible:-Quicker to write, and more reliable, because the size of the array exactly matches the number of elements, which might not happen if you populate it in multiple lines. If (as is the case here) the declaration and initialisation are on the same line, you are allowed to omit new int[].
I also hope that book doesn't show the [] after the array name, which is also poor style. Is it an old book? You can do the same with a for‑each loop (officially called enhanced for), and you don't need the array index.

What you are doing is guessing what the largest and smallest values in the array will be. [additional]Your double = takes the value of nums[0] and applies it to max and then applies the value of max, which hasn't changed, to min. Note that = associates to the right, so work out the expression right to left. [/additional] If your guess is the same as one of the array elements, unless you have the bad luck to be given a 0‑element array, you can be absolutely sure that there is at least one element not smaller than max and one not larger than min. That means, if all the following tests fail and your first element is the largest/smallest, you will still have a correct answer. Then you iterate the array, starting with the second element (array[1]). If that element is smallestsmaller than min, then you set min equal to the element and similarly for max. When you get to the end of the array, you have the answers
Let's try with a for‑each loop:-

Ray Gilbert
Ranch Hand
Posts: 109
1
The book is: Java A Beginners Guide Eigth Edition by Herbert Schilt 2019

In the next lesson He introduces initializing arrays when they are created.

He also introduces the "Enhanced for" or "for each" for loop later int the chapter.

Later, the author also talks about: "Alternative Array Declaration Syntax"
where he says: "There is a second form that can be used to declare an array:

type[] var-name;

Here, the square brackets follow the type specifier, not the name of the array variable.
For example, the following two declarations are equivalent:

The following declarations are also equivalent:

This alternative declaration form offers convenience when declaring several arrays at
the same time. The alternative declaration form is also useful when specifying an array
as a return type for a method."

Your explanation, it think, has helped me to have a bit better understanding of how the values are obtained for "min" and "max"

What I think I understand now is that both min and max are initialized to 0. Then, with each iteration through the for, the if statements assign min and max a new value based on whether or not it is < or > its current value, until it cycles through the entire array?

Somehow, if this is the case, I feel like I must have missed something earlier in the book.

Campbell Ritchie
Marshal
Posts: 70724
288
• 1

Ray Gilbert wrote:The book is: Java A Beginners Guide Eigth Edition by Herbert Schilt 2019 . . .

Don't have that book, but I'm afraid its earlier editions didn't get brilliant reviews on our book reviews pages.

Your explanation . . . has helped me to have a bit better understanding . . .  both min and max are initialized to 0. . . . .

Afraid you have missed something. Try my code on jshell and it will confidently tell you that both max and min are not 0 but 99. No, you are setting the values to the first element of the array. Then, as you correctly say, you traverse the array to its end amending the values of max and min if you find larger/smaller values. A for‑each loop traverses the entire array but the classical for loop you showed started at the second element because you had already processed the first element.
There are at least two other ways to findf max and min:-
• 1: I was taught to start with max ridiculously small and vice versa.
• 2: Use an OptionalInt object. You can get different results for a 0‑element array and you can't get confused when an array actually contains Integer.MAX_VALUE. You can create such an optional object with a loop, but the easiest way to do that is to create an IntStream from the array:-
•
Ray Gilbert
Ranch Hand
Posts: 109
1
• 1
Right! *facepalm*  "nums[0]"!! the value there is 99

Now it is clear to me why the for loop begins "int i = 1" rather than i"nt = 0" that was throwing me a bit too.

Thank you so much Campbell Ritchie for your time and patience. I feel like I get it now.

Campbell Ritchie
Marshal
Posts: 70724
288
• 1

Ray Gilbert wrote:. . . the value there is 99 . . . I feel like I get it now.

Well done

Sheriff
Posts: 15958
265
• 2
The statement in question,

demonstrates an aspect of an assignment expression that is often overlooked: that it has a value equal to that being assigned. Java evaluates that line as if it were written like this:

So, if nums[0] == 99, then it's essentially this:

which is essentially this:

You could have more:

The last line will set all four variables to whatever nums[0] is.

Junilu Lacar
Sheriff
Posts: 15958
265
• 1
This is also why you're discouraged from comparing a boolean variable to true or false:

The compiler will accept this code because it is valid syntax. However, because the assignment operator = is used on line 3 instead of ==, then keepGoing will always be true even though line 5 indicates that the intent was to terminate the loop. Code like that is usually a bug that was created when the author inadvertently used = instead of ==. It's better to just use the boolean variable directly like so:

Campbell Ritchie
Marshal
Posts: 70724
288
• 1

Ray Gilbert wrote:. . . why the for loop begins "int i = 1" rather than i"nt = 0" . . . .

Didn't the book explain that bit?

Thank you . . .

That's a pleasure

Ray Gilbert
Ranch Hand
Posts: 109
1

Campbell Ritchie wrote:

Ray Gilbert wrote:. . . why the for loop begins "int i = 1" rather than i"nt = 0" . . . .

Campbell Ritchie wrote:Didn't the book explain that bit?

No, unfortunately it didn't. That would have made things a lot clearer. Again, maybe I missed something in an earlier chapter. I have started this book and my Udemy course over 3 or 4 times now because I keep feeling like I am not fully getting it. I have only made it through 17% of the Udemy and 20% through the book.

Junilu Lacar
Sheriff
Posts: 15958
265
• 1
Learning how to program involves a lot of practice. I'm partial to the book "Think Like a Programmer" by V. Anton Spraul because it focuses on problem solving right away rather than elements of the programming language (C++). In fact, the book isn't really about C++ at all; that just happens to be the language the author chose to use for his examples. The concepts he writes about are applicable to any kind of language.

For instance, here's one of the programming challenges he gives (modified to use Java instead):

Problem: Half of a Square

Write a program that uses only two output statements, System.out.print("#") and System.out.println() to produce a pattern of hash symbols shaped like half of a perfect 5 x 5 square (or a right triangle):

#####
####
###
##
#

Then he goes on and explains the thought process and approach to breaking this problem down and solving it one step at a time.

Even though you're learning Java, I think the ideas this author discusses in his book can help you a lot. Again, the book is "Think Like a Programmer" by V. Anton Spraul.

Campbell Ritchie
Marshal
Posts: 70724
288
Isn't that a NoStarch Press book? If so it will be available for a good price

Campbell Ritchie
Marshal
Posts: 70724
288

Junilu Lacar wrote:. . . System.out.print("#") and System.out.println() . . .

Alternative: myStringBuilder.append("#") and myStringBuilder.append(System.lineSeparator()) and you can finish with System.out.println(myStringBuilder);
Same logic but you won't notice if it has faster performance because it only accesses the screen once

Ray Gilbert
Ranch Hand
Posts: 109
1
• 1
I arranged the values in the array in ascending order, then added some println to the example code and I was able to see each iteration.

If I had done this, I would have been able to understand it right then. I will have
to try this on the next thing I am not getting.

C:\Users\RGFick\Java Files\Beginners Guide Java>java MinMax

min and max are initialized to: 99, 99

min value is now: -9
max value is now: 99

min value is now: -10
max value is now: 99

min value is now: -970
max value is now: 99

min value is now: -970
max value is now: 99

min value is now: -970
max value is now: 99

min value is now: -970
max value is now: 287

min value is now: -970
max value is now: 463

min value is now: -970
max value is now: 5623

min value is now: -970
max value is now: 100123

min and max: -970, 100123

Campbell Ritchie
Marshal
Posts: 70724
288
• 1
You learn a lot by playing with code like that

Junilu Lacar
Sheriff
Posts: 15958
265
• 1
I have a theory that if you teach people to use tests as their "playground" they can learn even more.

How about it, Ray, you up for an experiment in teaching/learning techniques?

Ray Gilbert
Ranch Hand
Posts: 109
1

Junilu Lacar wrote:I have a theory that if you teach people to use tests as their "playground" they can learn even more.

How about it, Ray, you up for an experiment in teaching/learning techniques?

Sure, I have a deep desire to learn to code and develope. What do you propose?

Campbell Ritchie
Marshal
Posts: 70724
288
• 1
I think Junilu would like to take you through the process of testing a class.
It won't quite be a controlled experiment because there is only one of you. Also, something I have seen many a time: everybody seems to learn differently, using different learning modes and at different speeds.

Junilu: how far can you go testing without using JUnit or similar?

Junilu Lacar
Sheriff
Posts: 15958
265
We can go a ways but then it gets tedious. We'll try without the fancy testing tool for now.

Junilu Lacar
Sheriff
Posts: 15958
265
• 1
Let's restate the problem first.

Given an array of int values, find the minimum and maximum numbers in the array and display their values appropriately.

The code example you shared wasn't very useful because it could only handle an array with exactly 10 elements. Program code should be more flexible than that. Also, the approach shown is kind of a "big bang" approach in that it tries to do everything being asked of you all at one go. Program logic that does more than one thing at a time tends to be more complex. To simplify your task, you need to break the problem down. In other words, you need to decompose the problem into smaller problems.

Think of a way to decompose the "ask" of finding the minimum and maximum values in a given array of numbers so that you don't have one huge task to deal with.

Ray Gilbert
Ranch Hand
Posts: 109
1

Junilu Lacar wrote:"Let's restate the problem first.

Given an array of int values, find the minimum and maximum numbers in the array and display their values appropriately.

The code example you shared wasn't very useful because it could only handle an array with exactly 10 elements. Program code should be more flexible than that...."

I don't know if this is in keeping with the concept you propose but this is something I did the other night after Campbell helped me with my confusion over "min = max = nums[0]"

I was playing around with the code, adding println statements to better see what was happening as the for loop iterated through the array. and then I though, if I initialize the array upon declaration like the book's later example, and the way Campbell suggested, then more values could be added and the array could be expanded. That would then mean also remembering to change the iteration value in the for loop. So I made it an enhanced, or for-each for loop, as Campbell suggested and that would make that step unecessary. I also, maybe incorrectly, thought, why initialize min and max to nums[0] rather than just min = max = 0;. So I changed that as well, with seemingly no ill effects.

So, this is the book example code after I added those things to it:

Saloon Keeper
Posts: 7395
66
• 1
is not the same as
Think about what would happen if the nums array contained only negative numbers.

Sheriff
Posts: 7108
184
Ray Gilbert: it's generally a bad idea to edit a post after it's been replied to.  Instead, make a new post.

Ray Gilbert
Ranch Hand
Posts: 109
1

Knute Snortum wrote:Ray Gilbert: it's generally a bad idea to edit a post after it's been replied to.  Instead, make a new post.

Oh, I didn't realize that I had. My apologies.

Junilu Lacar
Sheriff
Posts: 15958
265
• 2
The problem I see with how you're learning is that you're getting bogged down in the minutiae and losing sight of the big picture. The point of writing a program is (generally) to solve a problem or to do something useful. But because you're focusing on the details of the implementation so much, it's like you're creating a car that has all its gears and engine components on the outside for everyone to see and somewhere in that mess are the steering wheel, the gas pedal, and the brakes.  There's a good reason for putting the engine under the hood and keeping the controls available to the driver to minimum, and that's focus. The driver doesn't need to see everything that's going on in the engine to be able to drive the car. Likewise, when I read code, I don't really need to all those detailed calculations.

What I'd rather like to see is something like this:

That's it. It takes me two seconds to read that code and get a sense of what the program's purpose is and what I should expect to see. I don't know if the book you're reading even talks about this approach. The book I recommended does, which is why I like it for beginners.

I think starting beginners with writing tests will help them keep an eye on the big picture and not get lost in all the minutiae of implementation. In my next post, I'll lay out a starter exercise for you that will have you work with similar code except this time, you'll start with a focus on testing. The goal of this exercise is to get you familiar with a test-driven approach to coding.

Junilu Lacar
Sheriff
Posts: 15958
265
• 1
In this exercise, I'll give some starter code that just describes the behavior that you're going to code in the MinMax class. But you won't focus on the MinMax class so much. Instead, you'll start with a class called MinMaxTest. It looks like this:

This is the initial implementation of the MinMax class:

Don't worry if you don't understand everything in that code. You'll slowly discover what each line does as you go through this exercise.

1. The MinMaxTest class is the main class you'll run. Its job is to exercise the methods in the MinMax class and ensure that they work properly.

2. When you run the MinMaxTest class, it will produce a RuntimeException with the message "min() method has not been implemented yet." Identify the line of code in MinMax that causes this to happen and explain why it happened. Reference relevant line numbers in the code in your explanation.

3. Change the MinMax.min() method so that it always returns 0. Then run the MinMaxTest class again. You should see an exception message of "test failed." Examine the exception stack trace and explain what caused that exception to be thrown. Reference relevant line numbers in the code in your explanation.

4. Change the MinMax.min() method so that it always returns 1. Then run the MinMaxTest class again. You should see the message "All tests passed." displayed on the console. Explain why this happened instead of producing a RuntimeException. Reference relevant line numbers in the code in your explanation.

That's the starter exercise. Let's see how you do. (I'll give you an example of how you should write your explanations in my next post)

Junilu Lacar
Sheriff
Posts: 15958
265
Here's an example of how to write the explanations being asked of you in the above exercise:

Given this code:

1. Explain why the program would display the message "5 is under 10."

Sample answer: The program will display that message because of line 5 which will only be executed if the while loop condition on line 4 is true. It would only display that message if the result of the call to rand.nextInt(20) on line 3 is 5 and the next call to rand.nextInt(20) on line 6 returns a value that is greater than or equal to 10.

2. Explain when the program wouldn't display any message.

Sample answer: The program wouldn't display anything if the call to rand.nextInt(20) on line 3 returns a number that is greater than or equal to 10. That would cause the while loop condition on line 5 to be false, thus the while loop body from lines 5-6 will never be executed and the program will end without displaying anything.

Ray Gilbert
Ranch Hand
Posts: 109
1
I've had a lot of things going on so I was not able to get back to this until today. I tried to compile MinMaxTest.java and it failed. This is what I got:

C:\Users\Java Files>javac MinMaxTest.java

MinMaxTest.java:25: error: illegal start of expression
assertEquals(1, min({4, 1, 10, 99});
^
MinMaxTest.java:25: error: not a statement
assertEquals(1, min({4, 1, 10, 99});
^
MinMaxTest.java:25: error: ';' expected
assertEquals(1, min({4, 1, 10, 99});
^
MinMaxTest.java:25: error: illegal start of expression
assertEquals(1, min({4, 1, 10, 99});
^
4 errors

Junilu Lacar
Sheriff
Posts: 15958
265
You can't create array literals like that. You need to pass new int[] {...} instead

Master Rancher
Posts: 3704
44
• 1
Or use varargs: change the declaration of min from

to

and then you can use code like

Note that using varargs like this, you don't need {} at all to declare an array - you just provide the list of arguments, and the JVM wraps them in an array for you.

Ray Gilbert
Ranch Hand
Posts: 109
1

Junilu Lacar wrote:You can't create array literals like that. You need to pass new int[] {...} instead

It was the code you posted for me to try last week.
I think I am too early in my studies of core java to really
understand testing at this point. I'm still slogging through
arrays and how for loops work. lol

Carey Brown
Saloon Keeper
Posts: 7395
66
This won't work:
This is a way of doing it:
And another way:
And, as mentioned, if you tweak min() to use varargs, then you can use this:

Junilu Lacar
Sheriff
Posts: 15958
265

Ray Gilbert wrote:

Junilu Lacar wrote:You can't create array literals like that. You need to pass new int[] {...} instead

It was the code you posted for me to try last week.

Ah, yes, I see it was indeed. My bad.

Junilu Lacar
Sheriff
Posts: 15958
265

Ray Gilbert wrote:I think I am too early in my studies of core java to really understand testing at this point. I'm still slogging through
arrays and how for loops work. lol

That is good feedback. I'd ask you , however, to give it another shot before you give up on starting with tests. Again, don't worry if you don't fully understand what the test code does because we can work through that as we go.  But having a test like that is critical to quickly getting feedback about the main code your developing (assuming the test code is correct and it compiles, of course).

If we tried again with test code that actually compiles, can you have another go at implementing a min() method that makes the test pass?

Ray Gilbert
Ranch Hand
Posts: 109
1
Sure. I will try it.

Junilu Lacar
Sheriff
Posts: 15958
265
Ok, then replace that test with this

Edit: The perils of posting from one's phone. Code was still missing []s. Thanks to Carey for pointing out the omission. All fixed now so it should be good to go.

Ray Gilbert
Ranch Hand
Posts: 109
1
I fixed it, now I am getting:

MinMaxTest.java:1: error: cannot find symbol
import static MinMax.min;
^
symbol: class MinMax
MinMaxTest.java:1: error: static import only from classes and interfaces
import static MinMax.min;
^
MinMaxTest.java:7: error: cannot find symbol
test.runAll();
^
symbol:   variable test
location: class MinMaxTest
MinMaxTest.java:25: error: cannot find symbol
assertEquals(1, min(new int[]{4, 1, 10, 99}));
^
symbol:   method min(int[])
location: class MinMaxTest
4 errors

Campbell Ritchie
Marshal
Posts: 70724
288
You must quote the package name in the import declaration. Since you don't have a package name, you can't implement that import.

Junilu Lacar
Sheriff
Posts: 15958
265
• 1

Campbell Ritchie wrote:You must quote the package name in the import declaration. Since you don't have a package name, you can't implement that import.

Doh! Serves me right for trying to do this off the top of my head. I'll post some starter code that will actually compile in a bit here, with better instructions.

 Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters?