May 2, 2017

How to Define a Java Method within a Class (Displaying an Account)

Java lets you define a method within a class. Imagine a table containing the information about two accounts. (If you __have trouble imagining such a thing, just look at the table below.)

Without Object-Oriented Programming
Name Address Balance
Barry Burd 222 Cyberspace Lane 24.02
Jane Q. Public 111 Consumer Street 55.63

In this table, each account has three things — a name, an address, and a balance. That’s how things were done before object-oriented programming came along. But object-oriented programming involved a big shift in thinking. With object-oriented programming, each account can __have a name, an address, a balance, and a way of being displayed.

In object-oriented programming, each object has its own built-in functionality. An account knows how to display itself. A string can tell you whether it has the same characters inside it as another string has. A PrintStream instance, such as System.out, knows how to do println. In object-oriented programming, each object has its own methods. These methods are little subprograms that you can call to have an object do things to (or for) itself.

And why is this a good idea? It’s good because you’re making pieces of data take responsibility for themselves. With object-oriented programming, all the functionality that’s associated with an account is collected inside the code for the Account class. Everything you have to know about a string is located in the file String.java. Anything having to do with year numbers (whether they have two or four digits, for instance) is handled right inside the Year class. Therefore, if anybody has problems with your Account class or your Year class, he or she knows just where to look for all the code. That’s great!

Imagine an enhanced account table. In this new table, each object has built-in functionality. Each account knows how to display itself on the screen. Each row of the table has its own copy of a display method. Of course, you don’t need much imagination to picture this table. Check out this table.

The Object-Oriented Way
Name Address Balance Display
Barry Burd 222 Cyberspace Lane 24.02 out.print …
Jane Q. Public 111 Consumer Street 55.63 out.print …

An account that displays itself

In the second table, each account object has four things — a name, an address, a balance, and a way of displaying itself on the screen. After you make the jump to object-oriented thinking, you’ll never turn back. The code below shows programs that implement the ideas in the second table above.

In this code, an account displays itself

import static java.lang.System.out;

public class Account {

String name;

String address;

double balance;

public void display() {

out.print(name);

out.print(" (");

out.print(address);

out.print(") has $");

out.print(balance);

}

}

This code uses the improved account class.

public class UseAccount {

public static void main(String args[]) {

Account myAccount = new Account();

Account yourAccount = new Account();

myAccount.name = "Barry Burd";

myAccount.address = "222 Cyberspace Lane";

myAccount.balance = 24.02;

yourAccount.name = "Jane Q. Public";

yourAccount.address = "111 Consumer Street";

yourAccount.balance = 55.63;

myAccount.display();

System.out.println();

yourAccount.display();

}

}

In the first set of code, the Account class has four things in it: a name, an address, a balance, and a display method. These things match up with the four columns in the second table. So each instance of the Account class has a name, an address, a balance, and a way of displaying itself. The way you call these things is nice and uniform. To refer to the name stored in myAccount, you write

myAccount.name

To get myAccount to display itself on the screen, you write

myAccount.display()

The only difference is the parentheses.

When you call a method, you put parentheses after the method’s name.

The display method’s header

Look again at the code above. A call to the display method is inside the UseAccount class’s main method, but the declaration of the display method is up in the Account class. The declaration has a header and a body. The header has three words and some parentheses:

  • The word public serves roughly the same purpose as the word public in the first set of code. Roughly speaking, any code can contain a call to a public method, even if the calling code and the public method belong to two different classes. In the example above, the decision to make the display method public is a matter of taste. Normally, when you create a method that’s useful in a wide variety of applications, you declare the method to be public.
  • The word void tells Java that when the display method is called, the display method doesn’t return anything to the place that called it.
  • The word display is the method’s name. Every method must have a name. Otherwise, you don’t have a way to call the method.
  • The parentheses contain all the things you’re going to pass to the method when you call it. When you call a method, you can pass information to that method on the fly. The display method in the first set of code looks strange because the parentheses in the method’s header have nothing inside them. This nothingness indicates that no information is passed to the display method when you call it.

Celebrating AnandTech’s 20th Anniversary: 1997 - 2017

This morning we’re celebrating a rather special occasion over here at AnandTech: our 20th anniversary. Though in a lot of ways it seems like the years __have gone by in a flash, the calendar doesn’t lie: it means we’ve now been doing this for two decades, starting from a quaint CPU review in 1997 and branching out to oh so much more by 2017.

I’ve admittedly never been one for public sentimentality, but as the second Editor-in-chief of AnandTech and a reader for most of its history, it’s a milestone that makes me very proud. When Anand created the site in 1997 it may __have just been a hobby, but by taking it seriously and defining a core set of principles that we still work by today, AnandTech has grown to leave its mark on technology journalism and the products around it, and I intend to continue leaving our mark and helping to shape the technology ecosystem in our own nerdy way.

For the start of AnandTech’s 21st year in the technology news business, I’d like to commemorate the occasion with a look back at what we’ve done, a brief look forward at where we’re going next, and finally, thank the many readers and groups out there who have made it possible. The latter point is especially important to me; while a commemoration is all about the entity or event being remembered, none of this would be possible without everyone who has supported us over the years. So in a way, I consider this an event for you guys as well as it is for us, because you have absolutely had a part in shaping how we go about writing articles and how we interact with hardware vendors.

For that reason, I’m also happy to announce that we’re launching our largest hardware giveaway ever. Over the next 20 days we’ll be giving away piles of hardware as a thank you to our readers who have made this all possible. Even that, I feel, isn’t a big enough thank you for what you guys mean to us. But it’s a start, and it means we can do something fun for you guys on our anniversary.

But first, let’s do a little commemorating.

A Bit of History

AnandTech was founded in 1997 by a then 14 year old Anand Shimpi during his freshman year of high school. At the time the Web was still relatively young, and Anand’s Hardware Tech Page as it was then named didn’t even have its own domain name. Instead, like many other hobby websites, it was hosted on the now long-defunct GeoCities.

In true AnandTech tradition right from the start, the first AnandTech article was the AMD K6 Review. That review is admittedly a mess by modern standards – none of us came into tech writing knowing a fraction of what we do now – but it marked the start of something greater. It reflected Anand’s desire to learn more and to share what he learned with the world, a core mantra that has driven AnandTech all of these years, and still drives us today.

In the intervening 20 years, far too much has happened to even begin to recap it all. AnandTech became a business, and a successful business at that. The Web transformed how technology journalism worked; no longer were articles bound to the rules of print, a month out of date and limited in length to what would fit. Instead articles could go as deep as they needed, and be posted to the wider world as soon as they were ready. Tech news became rapid-fire, and, outside of dedicated technology journals, writers could do more than ever before.

A lot of other organizations had the same idea and covered the PC hardware space as well. Some of those sites are still with us today; many more are not. Between the Dot-com bubble popping and the Great Recession, conditions have winnowed the number of tech sites significantly. AnandTech’s surviving and thriving these events is a combination of hard work and careful planning, to do what needed to be done to survive. But more than that, it’s thanks to you, the readers, who have supported us over all of these years and continue to support us today.


Guess The Interfaces

Meanwhile the technology landscape has changed dramatically over the last 20 years. The PC market was once the growth market for hardware, and over the years we’ve reaped the benefits of improved engineering, improved manufacturing, and improved economy of scale. The $1000 PC I bought in 1997 was, even by the standards of the time, a piece of junk, pairing a Pentium MMX 200 with what ended up being a rather dodgy Socket 7 motherboard. Now one can buy a half-decent laptop for a fraction of the price, and the inflation-adjusted $1500 will buy you an awesome computer, likely with money to spare. The PC industry is still alive and well these days – and we continue to labor hard to cover it – but it’s now a stable, mature industry that doesn’t move at the pace it once did.

A number of hardware companies have folded or been acquired in the intervening years. 3dfx, Cyrix, Abit, BFG. Others have continued to burn brightly the whole time – Intel is still as powerful as they ever have been – and others still have skirted with death only to stage a dramatic comeback. We’ve watched AMD rise, fall, and then Ryzen (again), as the perpetual plucky underdog has always kept the rest of the PC industry off-balance.

The story for the second decade of AnandTech’s existence has been the mobile industry, which for most of that decade has burnt with same fire that forged AnandTech in the beginning. The rapid evolution of smartphones and tablets is nothing short of remarkable, and it has forever changed the face of computing, even for us PC enthusiasts. Mobile devices are a product of the extreme integration we’ve seen over the years, and I would be lying if I said the lack of end-user customization didn’t bother me on some level, but at the same time they’ve expanded our horizons as tech writers and significantly changed how we look at the development of new technology.

1997 was also the year of Microsoft’s famous $150 million investment into Apple, which perpetuated their rise to becoming the most valuable company in the world. The company, whose computers were based around the odd-man-out PowerPC architecture at the time, switched over to x86 in 2005 and has made a significant mark on laptop design, all the while pioneering the modern smartphone and tablet.

(As an aside, at some point early in the previous decade, I talked Anand into trying out a Mac as his desktop workstation. This didn’t go quite as planned, as Anand ended up liking it perhaps a bit too much. Sorry about that.)

A Bit of the Future

Now the technology industry is at a new set of crossroads. Like the PC market before it, the mobile market is maturing and reaching saturation. Meanwhile Moore’s Law, while still alive, is definitely reaching its end-game for traditional silicon. The technology industry has always been remarkable for its continued and sustained growth, and while I’m optimistic that it will continue, no one knows quite what that future will look like.

What I do know is that no matter what, AnandTech will be there to cover it, with the depth our readers deserve and crave. One of Anand’s criticisms of technology journalism – and what’s now one of our core principles – is avoiding the cable TV-ificaition of the Web: the focus on traffic and business over the needs of the readers, leading to shallow, 10 o’clock news-style technology reporting. I will make no effort to hide or downplay the fact that AnandTech is part of a larger business (Purch), but my vision for the site and the focus of the editors of AnandTech remains unchanged. As much as we can, we have to do right by you, the reader, by continuing to learn more about technology and sharing what we learn with you in a deep-but-accessible manner.

While I don’t have any grand plans to announce, over the coming months you’ll be seeing some new faces around AnandTech as we continue to expand and diversify. I am happy with our depth but I feel like we aren’t doing enough in total; we need more reviews, more news, and more articles discussing how things work and how the future will be shaped. So that is my goal for the mid-term, to bring you guys more of what you come to AnandTech for.

We also have some other plans on the drawing board. The site is due for an overhaul, and Ian Cutress might kill me if I don’t let him improve Bench even more. HTTPS is also everywhere, and real soon now we will be enabling it across the site. I don’t have anything specific to announce here, but we aren’t standing by idly. If nothing else, a more regular podcast would be fun to do.

Thank Yous

Making it to 20 years could not have happened without the help of many people over the years, some who are quite public and others who like to blend in and do what they do in quiet.

The biggest thank you goes of course to Anand. While he’s off doing goodness-knows-what at Apple (I don’t know guys, seriously!), the site he founded and the principles he laid out has enabled us to do everything we’ve done for the past 20 years. It’s allowed us to focus on quality and depth, and perhaps more simply than that, make a living out of learning.

But the second biggest thank you goes to the many writers AnandTech has had over the years, Anand’s early collaborators and later hires alike. It’s only by having writers specialize in their fields and become masters that we’ve been able to dive as deep as we have, and while many of those writers have moved on to other jobs, they’ve left their mark on AnandTech. Over the years AnandTech’s writers have endured a number of sleepless nights, working holidays, canceled social engagements, and uncomfortable flights, all in the name of bringing more information to you. Their efforts are what have allowed AnandTech to thrive over the years.

A thank you also goes to the hardware vendors out there, many of whom have been putting up with us for the last 20 years. We’ve killed hardware, we’ve asked uncomfortable questions, and we’ve pushed vendors to reveal more than they’d necessarily like to share. Practically speaking, hardware vendors could lock us out, but I think that we’ve found a much better path in working together. The amount of access we get to engineers to ask questions and bring these stories to life has only happened because hardware vendors see the value in the AnandTech mission. And that has been to the benefit of everyone.

AnandTech’s publisher, Purch, also deserves a thank you. And I know what you’re thinking here, but Purch has genuinely earned this. Purch has taken a largely hands-off approach and allowed AnandTech to continue to do what we need to do, even if it doesn’t necessarily make business sense at the time. As a result we’ve continued to be able to innovate and stumble at our own pace, operating with the agility that’s required to remain at the cutting edge of technology.

Finally, none of this would be possible without you, the readers. You’re our support, the reason we suffer through sleepless nights to get a 20 page article up for a 9am Eastern embargo. You’re our critics, letting us know when we’ve let you down or could do better. You’re our customers, helping to pay the bills over the years accepting our advertising and buying products through our affiliates. But most of all you’re our peers, the people we strive to share our knowledge with so that all of us can know a little more and be a little smarter.

Thank you to everyone for the last 20 years, and here’s to what I hope to be the next 20 years.

May 1, 2017

How to Create a Class Definition in Python

A class need not be particularly complex. In fact, you can create just the container and one class element in Python and call it a class. Of course, the resulting class won’t do much, but you can instantiate it (tell Python to build an object using your class as a blueprint) and work with it as you would any other class.

The following steps help you understand the basics behind a class by creating the simplest class possible.

1Open a Python Shell window.

You see the familiar Python prompt.

2Type the following code (pressing Enter after each line and pressing Enter twice after the last line):

class MyClass: MyVar = 0

The first line defines the class container, which consists of the keyword class and the class name, which is MyClass. Every class you create must begin precisely this way. You must always include class followed by the class name.

The second line is the class suite. All the elements that comprise the class are called the class suite. In this case, you see a class variable named MyVar, which is set to a value of 0. Every instance of the class will __have the same variable and start at the same value.

3Type MyInstance = MyClass() and press Enter.

You __have just created an instance of MyClass named MyInstance. Of course, you’ll want to verify that you really have created such an instance. Step 4 accomplishes that task.

Typing a new class in Python

4Type MyInstance.MyVar and press Enter.

The output of 0 demonstrates that MyInstance does indeed have a class variable named MyVar.

Testing a class in Python.

5Type MyInstance.__class__ and press Enter.

Python displays the class used to create this instance. The output tells you that this class is part of the __main__ module, which means that you typed it directly into the shell.

How to Handle Nested Exceptions in Python

Sometimes you need to place one exception-handling routine within another in a process called nesting. When you nest exception-handling routines, Python tries to find an exception handler in the nested level first and then moves to the outer layers. You can nest exception-handling routines as deeply as needed to make your code safe.

One of the more common reasons to use a dual layer of exception-handling code is when you want to obtain input from a user and need to place the input code in a loop to ensure that you actually get the required information. The following steps demonstrate how this sort of code might work.

1Open a Python File window.

You see an editor in which you can type the example code.

2Type the following code into the window — pressing Enter after each line:

TryAgain = Truewhile TryAgain: try:  Value = int(input("Type a whole number. ")) except ValueError:  print("You must type a whole number!")  try:   DoOver = input("Try again (y/n)? ")  except:   print("OK, see you next time!")   TryAgain = False  else:   if (str.upper(DoOver) == "N"):   TryAgain = False except KeyboardInterrupt:  print("You pressed Ctrl+C!")  print("See you next time!")  TryAgain = False else:  print(Value)  TryAgain = False

The code begins by creating an input loop. Using loops for this type of purpose is actually quite common in applications because you don’t want the application to end every time an input error is made. This is a simplified loop, and normally you create a separate function to hold the code.

When the loop starts, the application asks the user to type a whole number. It can be any integer value. If the user types any non-integer value or presses Ctrl+C, Cmd+C, or another interrupt key combination, the exception-handling code takes over. Otherwise, the application prints the value that the user supplied and sets TryAgain to False, which causes the loop to end.

A ValueError exception can occur when the user makes a mistake. Because you don’t know why the user input the wrong value, you __have to ask if the user wants to try again. Of course, getting more input from the user could generate another exception. The inner try … except code block handles this secondary input.

Notice the use of the str.upper() function when getting character input from the user. This function makes it possible to receive y or Y as input and accept them both. Whenever you ask the user for character input, it’s a good idea to convert lowercase characters to uppercase so that you can perform a single comparison (reducing the potential for error).

The KeyboardInterrupt exception displays two messages and then exits automatically by setting TryAgain to False. The KeyboardInterrupt occurs only when the user presses a specific key combination designed to end the application. The user is unlikely to want to continue using the application at this point.

3Choose Run→Run Module.

You see a Python Shell window open. The application asks the user to input a whole number.

4Type Hello and press Enter.

The application displays an error message and asks whether you want to try again.

Answering a yes or no question in Python.

5Type Y and press Enter.

The application asks you to input a whole number again.

6Type 5.5 and press Enter.

The application again displays the error message and asks whether you want to try again.

7Press Ctrl+C, Cmd+C, or another key combination to interrupt the application.

The application ends. Notice that the message is the one from the inner exception. The application never gets to the outer exception because the inner exception handler provides generic exception handling.

An input loop in Python.

8Choose Run→Run Module.

You see a Python Shell window open. The application asks the user to input a whole number.

Press Ctrl + c to interrupt the Python application.

9Press Ctrl+C, Cmd+C, or another key combination to interrupt the application.

The application ends. Notice that the message is the one from the outer exception. In the preious steps, the user ends the application by pressing an interrupt key. However, the application uses two different exception handlers to address the problem.

How to Create Randomness in Java

As part of your programming with Java, you may be looking to create randomness. Achieving real randomness is surprisingly difficult. Mathematician Persi Diaconis says that if you flip a coin several times, always starting with the head side up, you’re likely to toss heads more often than tails. If you toss several more times, always starting with the tail side up, you’ll likely toss tails more often than heads. In other words, coin tossing isn’t really fair.*

* Diaconis, Persi. “The Search for Randomness.” American Association for the Advancement of Science annual meeting. Seattle. 14 Feb. 2004.

Computers aren’t much better than coins and human thumbs. A computer mimics the generation of random sequences, but in the end the computer just does what it’s told and does all of this in a purely deterministic fashion. So, when the computer executes

import java.util.Random;

int randomNumber = new Random().nextInt(10) + 1;

the computer appears to give a randomly generated number — a whole number between 1 and 10. But it’s all a fake. The computer only follows instructions. It’s not really random, but without bending a computer over backward, it’s the best that anyone can do.

Once again, you will simply __have to take this code on blind faith. Don’t worry about what new Random().nextInt means until you __have more experience with Java. Just copy this code into your own programs and have fun with it. And if the numbers from 1 to 10 aren’t in your flight plans, don’t fret. To roll an imaginary die, write the statement

int rollEmBaby = new Random().nextInt(6) + 1;

With the execution of this statement, the variable rollEmBaby gets a value from 1 to 6.

Apr 28, 2017

JavaFX: Bloom and Glow Classes

Here, you find out how to make your ordinary JavaFX shapes bloom and glow, all with the help of two simple classes, unsurprisingly named Bloom and Glow. This table shows the members of these two classes.

The Bloom and Glow Classes
Constructor Explanation
Bloom() Creates a new Bloom effect with default parameters.
Glow() Creates a new Glow effect with default parameters.
Bloom Method Explanation
void setThreshhold(double value) Sets the luminosity threshold. The bloom effect will be applied
to portions of the shape that are brighter than the threshold. The
value can be 0.0 to 1.0. The default value is 0.3.
Glow Method Explanation
void setLevel(double value) Sets the intensity of the effect’s glow level. The value
can be 0.0 to 1.0. The default value is 0.3.

The figure shows the effect of the Bloom and Glow effects. All three of the text shapes shown in the figure are combined with a rectangle in a group. The following code was used to create the first group (shown at the top of the figure):

Rectangle r1 = new Rectangle(50, 50, 400, 100);r1.setFill(Color.BLACK);r1.setStroke(Color.BLACK);Text t1 = new Text("Plain Text");t1.setX(130);t1.setY(125);t1.setFont(new Font("Times New Roman", 60));t1.setFill(Color.LIGHTGRAY);Group g1 = new Group();g1.getChildren().addAll(r1, t1);

Similar code was used to create the second group (shown in the middle of the figure), but a Bloom effect was added:

Rectangle r2 = new Rectangle(50, 50, 400, 100);r2.setFill(Color.BLACK);r2.setStroke(Color.BLACK);Text t2 = new Text("Blooming Text");t2.setX(70);t2.setY(125);t2.setFont(new Font("Times New Roman", 60));t2.setFill(Color.LIGHTGRAY);Group g2 = new Group();g2.getChildren().addAll(r2, t2);Bloom e1 = new Bloom();e1.setThreshold(0.3);g2.setEffect(e1);

For the third group, a Glow effect was added instead:

Three texts with bloom and glow effects created on JavaFX.

Rectangle r3 = new Rectangle(50, 50, 400, 100);r3.setFill(Color.BLACK);r3.setStroke(Color.BLACK);Text t3 = new Text("Glowing Text");t3.setX(80);t3.setY(125);t3.setFont(new Font("Times New Roman", 60));t3.setFill(Color.LIGHTGRAY);Group g3 = new Group();g3.getChildren().addAll(r3, t3);Glow e2 = new Glow();e2.setLevel(1.0);g3.setEffect(e2);

The difference between the bloom and glow effect is subtle. To be honest, it’s barely noticeable. If you look very closely, you’ll see that the glowing text is just a tad brighter than the blooming text. (The distinction between glow and bloom is more noticeable when colors other than black and white are used.)

JavaFX Controls: ScrollBar

The ScrollBar control in JavaFX is not usually used by itself; instead, it is used by other controls such as ScrollPane or ListView to display the scroll bar that lets the user scroll the contents of a panel or other region.

However, there are occasions when you might want to use a scroll bar for some purpose other than scrolling a region. In fact, you can actually use a scroll bar in much the same way as you use a slider, as the two are very similar.

One difference is that unlike a slider, a scroll bar does not allow tick marks. But on the other hand, a scroll bar has increment and decrement buttons on either end of the bar, which allows the user to set the scroll bar’s value up or down in fixed increments.

This figure shows a version of an audio mixer, only implemented with scroll bars. As in the slider version, each scroll bar is paired with a Text object that displays the scroll bar’s value whenever the user manipulates the control.

You can use the following helper method to create each combined scroll bar and Text object:

Using JavaFX scroll bars to create a mixer board.
Using JavaFX scroll bars to create a mixer board.
private Node makeScrollBar(int value){    Text text = new Text();    text.setFont(new Font("sans-serif", 10));    ScrollBar sb = new ScrollBar();    sb.setOrientation(Orientation.VERTICAL);    sb.setPrefHeight(150);    sb.valueProperty().addListener(        (observable, oldvalue, newvalue) ->        {            int i = newvalue.intValue();            text.setText(Integer.toString(100-i));        }        );    sb.setValue(value);    VBox box = new VBox(10, sb, text);    box.setPadding(new Insets(10));    box.setAlignment(Pos.CENTER);    box.setMinWidth(30);    box.setPrefWidth(30);    box.setMaxWidth(30);    return box;}