tag:blogger.com,1999:blog-28621447226171944172024-02-18T18:44:15.028-08:00A Beginning Programmer's Guide to JavaJava Programming Mysteries Explained for Those Learning to Program for the First Time, and for Experienced Programmers Just Learning Javasaundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comBlogger79125tag:blogger.com,1999:blog-2862144722617194417.post-23092688295009315702014-11-17T03:52:00.000-08:002014-11-17T03:52:51.399-08:00Portability of Java Programming SkillsYou can program in Java (or are learning to.) That's great! But what else can you do with those skills? Are you trapped with Java?<br />
<br />
Not at all. One of the reasons I chose Java as a language for use in the classroom is that Java programming skills translate so well into skills for other languages. Here are some other languages, and a brief look at what your Java programming skills will give you in the way of a head start, and what differences to look out for.<br />
<br />
<b style="color:#ff8800;">C# (C Sharp)</b><br />
C# and Java are practically the same. C#'s roots are in Java, as is the concept of its libraries relative to Java's API. The libraries differ, but if you're used to Java's API you'll have no trouble getting right into C#'s libraries to find the classes you're looking for.<br />
<br />
The major development tools are very similar, or, in many cases, you can use the same IDEs for C# as for Java. You can also do cross-platform development in C# just as you can with Java thanks to tools like Mono (which I highly recommend as a way of becoming familiar with C#) and the forthcoming cross-platform Visual Studio tools from Microsoft.<br />
<br />
<b style="color:#ff8800;">C</b><br />
Java is an object-oriented descendent from the C language. C does not have object-orientation built in, but you should have no trouble understanding much of the code. Imagine writing Java without creating your own classes, or only creating limited classes. This isn't strictly accurate, since it is possible to write object-oriented code in C, it just requires the programmer to do much of the work that Java does in their code. Providing for isolation of data, inheritance, etc. has to be performed through code written explicitly to perform these functions.<br />
<br />
Modern versions of C, such as ANSI C/ISO C (C99) provide a version of C which makes it easier to write good code if you're coming from an object-oriented background.<br />
<br />
Another major hurdle will be dealing with memory management directly (C has no garbage collection), and learning how to use the various functions of C which are often not as predictable as the Java methods you are familiar with.<br />
<br />
The basics of C will already be familiar to you, but you should conduct some formal study of C and use its standard libraries extensively before seeking to start formal projects with it.<br />
<br />
<b style="color:#ff8800;">C++</b><br />
C++ is another object-oriented outgrowth of C, like Java, yet it uses a very different approach. You will find that your Java experience can be very misleading with respect to the handling of data and the operation of methods in C++. Also, C++'s libraries tend to be much more platform-specific than those of Java. In Java you have platform-specific libraries, yet it is possible to write good code that does not rely on it, or that relies on it little enough to allow 90% or more of your code to be written in a non-platform-specific fashion.<br />
<br />
With C++, however, you'll find that while there are standard cross-platform libraries, most code will be best written to the platform to which it is being compiled.<br />
<br />
<b style="color:#ff8800;">Python</b><br />
Python will be very easy to learn once you know Java. Its syntax is quite different, and its approach to what is implicit and what must be explicitly defined is very different to that of Java. Conceptually, however, you will be right at home and will be able to learn the specifics of the language very easily.<br />
<br />
Like Java, Python has extensive libraries. Some are part of Python's core distribution, but others are not. You will find that even in the core libraries there is much less cross-platform support than Python seems to promise. Also, you will need platform-specific libraries for any graphics or audio code. Even in cross-platform libraries, you will find that there are significant differences between platforms. If you are writing code that does not rely on the platform for presentation, however, (for example code that uses a browser), Python works very well in a cross-platform environment.<br />
<br />
<b style="color:#ff8800;">Javascript</b><br />
Javascript is also very similar to Java in many ways, but not as much as the name of the language might lead you to believe. Java has recently acquired many of the constructs that have been favorites of Javascript programmers for years.<br />
<br />
You will find that handling data under Javascript is very different to the means used in Java. You will also find the nomenclature very, very different, despite the similarities in the languages. This will probably be your biggest early hurdle in transitioning from one language to the other.<br />
<br />
The best approach is to set yourself to learn the ways that things are best done in Javascript, before trying to write Java code in Javascript syntax. Once you can write solid small programs, enough will become apparent to you that you can begin to take advantage of your programming knowledge from Java to apply it to your Javascript programs. Some programming languages it is your knowledge of Java syntax and structure that will make those languages easy for you. Javascript isn't one of those languages. The payoff comes after you have learned Javascript syntax and structure, the process of designing well-build object oriented software will pay off.<br />
<br />
With Javascript, the web browser is almost certain to be your "platform." You will need to learn the Domain Object Model to effectively apply Javascript. If you have already been using the DOM with your Java code (over half of Java code is written for the web), then you are already there. Otherwise, it's something else new you'll have to learn.<br />
<br />
<b style="color:#ff8800;">Objective-C</b><br />
The transition from Java to Objective-C is far simpler than to C++. The object-oriented techniques used in Objective-C will make immediate sense to a Java programmer, as will the program structure. Objective-C requires you to do your own memory management, unlike Java, but it provides facilities to do so more simply and effectively than standard C.<br />
<br />
The libraries will differ completely from those of Java, and your platform will almost certainly be iOS or Macintosh, so those are the platforms whose libraries you'll learn. Objective-C differs from Java more than C#, but not so much as to make it extremely difficult to transition to. After C#, Objective-C is probably the easiest non-scripting language for you to learn.<br />
<br />
<b style="color:#ff8800;">Swift</b><br />
Swift is based on Objective-C, and will be even easier for a Java programmer to learn and use. Most of the changes not only make it easier to produce programs in general, but make it conceptually simpler for a Java programmer to make the transition. You'll be reading the code in the first day, and will be able to produce effective code with only a few hours of work. As with Objective-C, there are new libraries for you to learn tied to Swift's platforms (iOS and Mac), but you will find these even easier to navigate than the Java libraries that suffer from Java's early history of development being encased within them.<br />
<br />
<b style="color:#ff8800;">PHP</b><br />
PHP does not have the sort of object-oriented programming facilities that you will be used to from Java, but its syntax will be easy for you to pick up. You will likely feel limited by PHP compared to Java, but PHP has a more limited purpose than Java--it is focused on web programming. While Java is heavily used for server-side web programming, it is much more of a general purpose language than PHP.<br />
<br />
You will need to learn the specifics of PHP's syntax and data structures, but after mastering Java, you will not find this difficult.<br />
<br />
<b style="color:#ff8800;">Summary</b><br />
These cover the most popular programming languages in use at this time. There are other languages, like Scala, that are specifically designed to be like Java yet address shortcomings perceived in Java, either for some specific use, or to change things that are historically embedded in Java's design. These are very easy for a Java programmer to transition to.<br />
<br />
At present, Oracle's support of Java is limiting its market relative to the general use for Java that Sun used to promote. While Java is still widely used, and will continue to be for the foreseeable future, it always behooves a programmer to be competent in multiple languages and to have more than one set of conceptual tools for problem solving at hand. So it is good to know other languages, even if they are scripting languages like Python and Ruby.<br />
<br />
Currently, Microsoft is in the process of making a strong play to the cross-platform development market which Java has served. With C# as part of this, and C# plus Mono (a cross-platform version of .Net) already available, it is very easy for a Java programmer to add this to their programming portfolio to gain a greater range of opportunities for work, and a wider range of tools for solving programming problems.<br />
<br />
I highly recommend, at least, spending some time with C# under Mono or .Net if you are currently a Java programmer. I think you'll find that you feel right at home. <br />
<br />
An advantage of learning .Net is that it will open up Windows-specific programming in C++ to you as well. The C++ language will be new, but you'll already know the libraries that you'll be using. If Microsoft delivers on their recent promises of making their tools fully cross-platform for Mac and Linux, then you'll be able to apply those skills to those platforms as well.<br />
<br />
<b style="color:#ff8800;">Mobile</b><br />
Java is the language you'll use on Android, currently the dominant mobile platform in terms of users. Objective-C is the language for iOS, and it's not a huge jump for a Java programmer to make. Swift is a simplified version of Objective-C, and it is even easier for the Java programmer to learn. If you are planning to develop for iOS, it is worth making the effort to transition to a language built for it, and Swift should be your first stop.saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-66431706408952091372013-11-12T16:42:00.000-08:002013-11-12T16:42:06.292-08:00DozCalc: A More Polished Android Application in JavaSince my post on my <a href="http://beginwithjava.blogspot.com/2013/01/my-first-android-app.html">first Android app</a>, I've done a lot. I went on from that first app to learn how to access a lot more of the device, deal with a wider range of circumstances, and generally get to know Android and the tools for developing for it better.<br />
<br />
Specifically, I have posted an app for Android called <a href="https://play.google.com/store/apps/details?id=com.acedev.dozcalc&hl=en">DozCalc</a>.<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://play.google.com/store/apps/details?id=com.acedev.dozcalc" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjvcU71bv-BldZyDHdsaGm8pectJyJw6uzJPqbaABuPQKQv_zJYYBDWCXcG99tJ3xjM6A54lLr6bJIZIkeMvKfb_-yA43AYgL_TkU699sTrWyf6YWAgEyoca2-KEatBChQ4P7la29biGHI/s320/dozcalc.jpg" /></a></div>DozCalc is a dozenal (base 12) calculator. It doesn't convert back and forth between dozenal and decimal, so be warned. Just like your normal four function calculator that works in base 10 and nothing else, DozCalc works in base 12 and nothing else.<br />
<br />
<b>Java</b><br />
<br />
The "programming", like development in many modern GUI environments, was less about the functional code (in this case in Java) and more about the user interface. While Android allows for UI programming in Java, it's typically simpler to implement it in XML. And this is what I did.<br />
<br />
The only problem I had was dealing with loss of precision in some calculations. At first, I was going to be very clever and write a proper function using numerical analysis to get the value right to some specified number of fractional digits (note: it's not proper to call them 'decimal digits' when you're working strictly in base 12). However, it was simpler and easier to just add a small value to certain calculations (division, for example) to make all the fractional values come out correct. Far simpler to program, just as effective for this use, and every bit as accurate as the average four function calculator.<br />
<br />
Sometimes programming is less about the language, or the algorithm, than about just getting a solution that's accurate enough for the need, then moving forward.<br />
<br />
Thanks to object-oriented design, I was able to re-use the code from DozCalc in another graphical calculator. Unfortunately, I got bogged down in the graphical design, so the steampunk styled version of DozCalc (named Mr Wells' Calculator) has yet to be released, and may not be depending on how my schedule of current projects goes.saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-47578580589477901242013-01-13T00:28:00.001-08:002013-01-13T00:30:55.116-08:00My First Android AppI ordered an Android phone about two weeks ago.<br />
<br />
Last Thursday, I installed the <a gref="http://developer.android.com/sdk/index.html">Android SDK</a>. It went smoothly, I've installed it under two versions of Windows 7, as those are my systems with the most RAM and CPU power (for the Android device emulator. My older Mac and Linux systems lug a bit when doing serious hardware emulation.)<br />
<br />
I started the online tutorials linked on the SDK's opening page. Since the SDK is based on <a href="http://www.eclipse.org/downloads/moreinfo/java.php">Eclipse</a> (my favorite full-fat IDE for Java), it was no problem getting started.<br />
<br />
I got a simple app, modified from the 'getting started' tutorial, running on an emulated Android device within an hour or so of starting.<br />
<br />
The next day--Friday, my phone arrived in the mail. It runs Android 4.1.1.<br />
<br />
After a busy day on Friday interleaved with charging and moving into the phone, I got the Android SDK talking to my phone today, downloaded an updated version of the app (a =very= simple character generator for my RPG, <a href="http://saundby.com/rpg/roonquest/">RoonVenture</a>.) It ran just fine. It's very similar to my online <a href="http://saundby.com/rpg/roonquest/roonventure_char.shtml">RoonVenture Character Generator</a>.<br />
<br />
That is, it's ugly, poorly designed, but bone-simple while producing the essential results.<br />
<br />
Nevertheless, I found my Java skills played right into Android development (so far):<br />
<br />
Android's native language is Java, with some unique libraries.<br />
<br />
The default IDE is Eclipse, a common Java IDE (and one I recommend, though I still do about half my code in something lighter, ranging from vi or vim to Arachnophilia or BlueJ.)<br />
<br />
It's a lot like Java ME development (which I've done to build apps for my older "feature phones".)<br />
<br />
So, if you're doing Java now, I recommend jumping into Android if the opportunity arises. I've found it easier to get started than with Java ME, Blackberry, or Nokia Series 60 development. Though it's worth noting that I'm coming to this with prior experience with all of those first.<br />
<br />
Now I'm taking a break from the computer and reading a hardcopy book, "Creating Android Applications" by Chris Haseman. It's written for the experienced Java programmer who doesn't need 250 pages on Java and Eclipse.<br />
<br />
That should help me make a better app next. :)<br />
<br />
<center><iframe src="http://rcm.amazon.com/e/cm?t=saundbsatari7800&o=1&p=8&l=as1&asins=032178409X&ref=qf_sp_asin_til&fc1=000000&IS2=1<1=_blank&m=amazon&lc1=0000FF&bc1=FFFFFF&bg1=FFFFFF&npa=1&f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe><br />
</center>saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-83901348774692174932012-11-28T20:48:00.000-08:002012-11-28T20:48:12.027-08:00Dino Programmers Need Not Fear JavaWhile most of this blog focuses on assisting beginning programmers to learn Java as their first computer language, I also try to make it useful to those who are "old school" programmers, like myself, that want to make the transition to the newer language.<br />
<br />
I was an accomplished programmer in many procedural and functional languages before I came to any of the Object-Oriented languages. In fact, my favorite language was Modula-2, which worked so well for me doing everything that OO languages were said to do, that I didn't make the transition to OO until about 1994 (a bit late in the game for those who were supposedly active in taking up new languages back then.)<br />
<br />
<b style="color:#ff7700;">Tools Getting in the Way of the Work</b><br />
When I came to OO, I had a real hard time learning the whole OO "thing". Much of it looked no different than language structures that enforced normal coding practices used elsewhere. Other parts of it just looked like un-needed restrictions on data access. It was very frustrating.<br />
<br />
Part of what slowed my transition to OO had nothing to do with the languages, however. The tools were new, too. That is, I was trying to do things as I was advised to by those more experienced than myself. Rather than using my usual technique of starting out with a text editor and command line compiler and linker, I allowed myself to be talked into going whole hog on IDE interfaces I wasn't familiar with. Once I was in them, I did get some information from them as I worked that helped a bit. But they kept me from really understanding the languages themselves for about a year longer (when nibbling at them part time outside my usual work) than it would have otherwise.<br />
<br />
<b style="color:#ff7700;">Welcome, Fellow Dinos!</b><br />
When I started this blog, I strongly considered focusing it on other programmers like myself trying to get comfortable with the move from older languages and programming styles. By the time I did, I was actually pretty comfortable with several OO languages and many development environments and tool chains. But I could still feel the tug of Turbo Pascal when I got frustrated, or plain old <tt>vi</tt> and <tt>make</tt> with <tt>cc</tt> and a system-appropriate linker behind it.<br />
<br />
In fact, I still do. There are a fair few nights I unwind by firing up my Ampro Little Board Z-80 system, which runs CP/M 2.2, and having at Turbo Pascal or ASM. Just for relaxation. <br />
<br />
It's like embroidery or quilting for aging nerds, I guess.<br />
<br />
<b style="color:#ff7700;">Java for Dinos</b><br />
I'm good with being called a dino, so I hope it doesn't put you off if you're an old-timer, too. (Am I really an old timer now? Some folks say so.)<br />
<br />
Java is really awfully easy to use at the command line. Create a source file with your favorite text editor.* Open up a command line (no matter what OS you're on), <tt>cd</tt> to the directory where you saved the file, and compile it with:<br />
<tt style="color:#00ddee;">javac <i>filename</i>.java</tt><br />
<br />
Replace <tt style="color:#00ddee;"><i>filename</i></tt> with your file's name, of course.<br />
At this stage you need to include the <tt style="color:#00ddee;">.java</tt> file extension. It will produce a new file with the same name but a <tt style="color:#00ddee;">.class</tt> extension is on it now.<br />
<br />
Once it completes successfully (and if it doesn't, and old timer should be able to read the error messages and line numbers to fix the code), use the following to run your program:<br />
<tt style="color:#00ddee;">java <i>filename</i></tt><br />
<br />
Note that even though you're running a <tt style="color:#00ddee;">.class</tt> file, you don't specify the file extension for the java runtime. You'll get an error that makes it look like there's something wrong with your file if you do:<br />
<blockquote style="color:00dd00;background-color:black;"><pre>>java Howdy.class
Exception in thread "main" java.lang.NoClassDefFoundError: Howdy/class
Caused by: java.lang.ClassNotFoundException: Howdy.class
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)</pre></blockquote><br />
And, if you go to compile your program and get really, really long lists of errors, don't be discouraged. Remember the old maxim--fix the first error. Chances are most or all of the rest are errors that cascaded from the first one.<br />
<br />
<b style="color:#ff7700;">Why Bother?</b><br />
Java will get you a lot of code that you'd have to write yourself otherwise. Now, this isn't unique to Java these days, it's become the norm for many languages. But you won't find yourself creating a socket driver or string handling routines. Plus, you can treat Java as either a procedural or functional language if that suits you. I did for the most part until about five years ago or so. I got a lot of work done with it, even at that.<br />
<br />
But, I moved on to using Java "as it was meant to be" over time, because it meant rewriting less code, or less work re-using code. I just took getting there one step at a time. Learning how to do everything I did fluently in Modula-2, or LISP, in Java. (Or one of the various Pascals, or C, etc.) Libraries, general purpose re-usable code, flexible data structures, and so on.<br />
<br />
<b style="color:#ff7700;">Come In and Look Around</b><br />
Have a look at my Basic Java Articles, listed in the right column. I strive to post actual working code in my examples, in the form of complete programs. So you don't have to guess about how to fit a snippet into your code.<br />
<br />
To do this, I often strip away code that would be <i>good</i> to have, but which might cloud the issue. So I don't guarantee that my examples are good coding practice, but only that they are complete working examples of what I'm talking about. And I warn you in the article when it's not the greatest. Full code can also be downloaded from <a href="http://saundby.com/beginwithjava/">my Java code repository</a> for this blog (also on the right side of every article here.)<br />
<br />
If my articles are of use to you, or you think I can improve things, drop me an email.<br />
<br />
Thanks.<br />
<br />
*I still do a lot of coding in plain old vi, though I've gotten to like the syntax highlighting in vim as well. If I want an IDE, I usually prefer one of the simpler ones like BlueJ or Greenfoot, though I can bury myself complex ones like Eclipse or NetBeans if I really want to. Occasionally I fire up emacs, though I prefer a stripped version of that, too.<br />
<br />
<br />
saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-5255999393784443182012-06-27T00:21:00.000-07:002012-06-27T00:21:26.351-07:00Java's Assignment OperatorsAn <a href="http://beginwithjava.blogspot.com/2011/06/java-variable-value-assignment-left.html">assignment operator</a> is a way of putting a new value into a variable.<br />
<br />
I covered these briefly in <a href="http://beginwithjava.blogspot.com/2011/05/doing-math-in-java-part-1-operators.html">Doing Math in Java, Part 1</a>. Now I'll go into a bit more detail.<br />
<br />
<b style="color:#ff7700;">The Simple Assignment Operator</b><br />
<br />
The simple assignment operator is <tt style="color:#77ff00;">=</tt>.<br />
<br />
It places the value from the expression on its right side into the variable on its left.<br />
This is covered in detail in <a href="http://beginwithjava.blogspot.com/2011/06/java-variable-value-assignment-left.html">Left Becomes Right</a>.<br />
<br />
Also see the <a href="http://docs.oracle.com/javase/specs/">Java Language Specification</a>: <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.1">The Simple Assignment Operator</a>.<br />
<br />
<b style="color:#ff7700;">The Compound Assignment Operators</b><br />
<br />
The compound assignment operators are:<br />
<tt style="color:#77ff00;">+=</tt>, "plus-equals",<br />
<tt style="color:#77ff00;">-=</tt>, "minus-equals",<br />
<tt style="color:#77ff00;">*=</tt>, "times-equals" or "star-equals",<br />
<tt style="color:#77ff00;">/=</tt>, "divided by-equals" or "slash-equals",<br />
<tt style="color:#77ff00;">%=</tt>, "remainder-equals" or "percent-equals",<br />
<tt style="color:#77ff00;">&=</tt>, "and-equals",<br />
<tt style="color:#77ff00;">|=</tt>, "or-equals",<br />
<tt style="color:#77ff00;">^=</tt>, "exor-equals" or "caret-equals",<br />
<tt style="color:#77ff00;">>>=</tt>, "signed-shift-right-equals",<br />
<tt style="color:#77ff00;"><<=</tt>, "shift-left-equals",<br />
<tt style="color:#77ff00;">>>>=</tt>, "unsigned-shift-right-equals".<br />
<br />
<b style="color:#ff7700;">Commonality</b><br />
Each of these operators has a variable to assign a value to before it, and an expression that results in a value after it:<br />
<tt style="color:#0077ff;">variable</tt> <tt style="color:#77ff00;">operator</tt> <tt style="color:#ff0077;">expression</tt><br />
<br />
The expression has to result in a value that is compatible with <tt style="color:#0077ff;">variable</tt>'s type.<br />
<br />
Java will calculate the value of <tt style="color:#ff0077;">expression</tt>,<br />
<br />
perform the calculation <tt style="color:#0077ff;">variable</tt> <tt style="color:#77ffff;">optype</tt> <tt style="color:#ff0077;">expression</tt>, where <tt style="color:#77ffff;">optype</tt> is the assignment operator without the equals sign.<br />
<br />
Then it will place the result of that calculation into <tt style="color:#0077ff;">variable</tt>.<br />
<br />
<b style="color:#ff7700;"><tt style="color:#77ff00;">+=</tt>, "Plus-Equals"</b><br />
Plus-equals adds the value after += to the original value of the variable, then puts the result into the variable.<br />
<br />
<b style="color:#ff7700;"><tt style="color:#77ff00;">-=</tt>, "Minus-Equals"</b><br />
This subtracts the value after the operator from the original value in the variable, then stores the result in the variable.<br />
<br />
<b style="color:#ff7700;"><tt style="color:#77ff00;">*=</tt>, "Times-Equals"</b><br />
Multiply the variable by the value on the right of the operator, put the result in variable.<br />
<br />
<b style="color:#ff7700;"><tt style="color:#77ff00;">/=</tt>, "Divided by-Equals"</b><br />
Same as the above, but for division.<br />
<br />
<b style="color:#ff7700;"><tt style="color:#77ff00;">%=</tt>, "Remainder-Equals"</b><br />
This finds the <i>remainder</i> of the variable's initial value divided by the value after the operator. That <i>remainder</i> is then put into the variable.<br />
<br />
See <a href="http://beginwithjava.blogspot.com/2012/05/javas-modulo-function-wrapping-around.html">Java's Modulo Operator--Wrapping Around</a> for more information on how the remainder (or modulo) operator <tt style="color:#77ff00;">%</tt> works.<br />
<br />
<b style="color:#ff7700;"><tt style="color:#77ff00;">&=</tt>, "And-Equals"</b><br />
And-equals does a bit-wise AND of the value after the assignment operator with the original value of the variable, then puts the results in the variable.<br />
<br />
<b style="color:#ff7700;"><tt style="color:#77ff00;">|=</tt>, "Or-Equals"</b><br />
Or-equals does a bit-wise OR of the variable and the value after the operator. The result is placed in the variable.<br />
<br />
<b style="color:#ff7700;"><tt style="color:#77ff00;">^=</tt>, "Exor-Equals"</b><br />
Exor-equals is short of Exclusive-Or Equals (and it is often written xor-equals). It does a bitwise exclusive-or of the variable and the value after the assignment operator, then puts the result into the variable.<br />
<br />
<b style="color:#ff7700;"><tt style="color:#77ff00;">>>=</tt>, "Signed-Shift-Right-Equals"</b><br />
This does a signed right shift of the variable a number of times equal to the expression after the assignment operator. The result is placed in variable.<br />
<br />
<b style="color:#ff7700;"><tt style="color:#77ff00;"><<=</tt>, "Shift-Left-Equals"</b><br />
This does the same thing as signed-shift-right-equals, except it does a signed left shift (each bit in the variable gets moved to the left <i>expression</i> times.<br />
<br />
<b style="color:#ff7700;"><tt style="color:#77ff00;">>>>=</tt>, "Unsigned-Shift-Right-Equals"</b><br />
This one moves all the bits, unlike the signed shifts which leave the sign bit (highest order bit) alone.<br />
<br />
<b style="color:#ff7700;">Not Quite the Whole Story</b><br />
That covers how these operators behave with numerical and other simple values. These operators have other behaviors when used with Strings, Arrays, and other complex value types. That goes beyond the scope of this article, however, more on that can be found at the links given under "Additional Information".<br />
<br />
<b style="color:#ff7700;">Additional Information</b><br />
See the <a href="http://docs.oracle.com/javase/specs/">Java Language Specification</a>: <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2">Compound Assignment Operators</a>, <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17">Multiplicative Operators</a>, <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.18">Additive Operators</a>, <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.22">Bit-wise and Logical Operators</a>.<br />
<br />
saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-14174086531779425632012-05-14T14:23:00.000-07:002012-05-14T14:32:07.967-07:00Java's Modulo Function--Wrapping AroundI've previously discussed <a href="http://beginwithjava.blogspot.com/2011/05/doing-math-in-java-part-1-operators.html">operators</a> in Java, where I gave a brief introduction to the <b>modulo</b> operator, <b><tt>%</tt></b>.<br />
<br />
The percent sign is used in many computer languages as a brief, single-character symbol for the remainder of a division, not for a percentage of a number, as you might expect.<br />
<br />
<b style="color:#ff7700;">What's Left Over</b><br />
<br />
In many calculations in normal day to day life, the remainder of a division is not very important. It's just the odd change left over at the end of doing division. With computer programs, however, modulos can be very useful and powerful.<br />
<br />
One of its most important uses is to limit the range of a value. For example, if we're only interested in having a value be a number from 0 to 99, and any value over that is something we don't want, we can use modulo as a way of cutting any number we get down to size. Since the remainder of a division can never be as large or larger than the divisor, we know that any remainder from a division by 100 can never be more than 99 (in integers.) So we can take any number, find the modulo by some number that we want as an unreachable cap on our values, and never get a number that's too big.<br />
<br />
<b style="color:#77ff00;"><tt>limitedNumber = someNumber % 100</tt></b><br />
<br />
<tt>limitedNumber</tt> will never be higher than 99.<br />
<br />
<b style="color:#ff7700;">Real World Analogies</b><br />
<br />
A real world version of this is a knob that you can turn around without a stop on it. The knob's setting can vary over a range of values all the way around it. But when you turn it past some point, it goes from its highest setting to its lowest setting.<br />
<center><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/d/db/Radio_set_dial.jpg/480px-Radio_set_dial.jpg" alt="Radio dial, image by John McComb of Oakland, CA." width="450" height="450" /></center><br />
For example, a radio dial that goes up in frequency until you hit the top of the radio band, then starts tuning over again from the bottom of the band.<br />
<br />
<b style="color:#ff7700;">Computer Applications</b><br />
<br />
One of the most common uses of the modulo in computer programs uses that same ability with computer graphics. How many computer games have you seen where an object goes off one side of the computer's screen then reappears on the other side? That's an example of the modulo function. Let's look at an asteroid object that has its horizontal location on screen tracked by the member variable <tt>xLoc</tt> (short for x location):<br />
<br />
<tt style="color:#0077ff;">Class Asteroid{<br />
int xLoc, yLoc, xSpeed, ySpeed, size;<br />
.<br />
.<br />
.<br />
}</tt><br />
<br />
We'll assume the class has all the methods it needs to do what Asteroids do. Our instance is:<br />
<br />
<tt style="color:#0077ff;">Asteroid asteroid = new Asteroid();</tt><br />
(If this is unfamiliar to you, you may want to read <a href=http://beginwithjava.blogspot.com/2008/08/creating-java-variable-two-steps.html">Creating a Java Variable, Two Steps</a>.)<br />
<br />
Now let's say our asteroid is presented on a screen area that is 800 pixels wide and 600 pixels high. That means our xLoc value can vary from 0 (the leftmost location on screen) to 799 (the rightmost location on screen) since we have a screen area 800 pixels wide. Remember, when we start counting at 0 our highest number is one less than the total number of pixels.<br />
<br />
We can move our asteroid from left to right as follows:<br />
<br />
<tt style="color:#0077ff;">xLoc = xLoc + xSpeed;</tt><br />
<br />
Where <tt>xSpeed</tt> is how fast we're moving across the screen.<br />
<br />
The problem is, what do we do when we hit the right edge of the screen? That is, what do we do when xLoc is higher than 799?<br />
<br />
If we want our asteroid to "wrap around" from the right side to the left side of our screen, the modulo operator is just what we want. We can do this to make it wrap around that way:<br />
<br />
<tt style="color:#0077ff;">xLoc = xLoc + xSpeed;<br />
xLoc = xLoc % 800; // Hard-coded screen width, for now.</tt><br />
<br />
That will make xLoc always be from 0 (when there is a zero remainder) to 799 (the highest possible remainder when dividing by 800.)<br />
<br />
We might have a method in Asteroid like the following:<br />
<br />
<tt style="color:#0077ff;">public int moveHoriz(int howFar){<br />
// Moves the Asteroid horizontally by howFar pixels on an 800 pixel wide screen.<br />
// returns the new pixel location.<br />
return (xLoc + howFar) % 800;<br />
}</tt><br />
<br />
This glosses over a few other problems (like going from the left edge of the screen to the right), but illustrates the use of modulo to bring the object around from right to left again.<br />
<br />
<br />
<b style="color:#ff7700;">An Expanded Example</b><br />
<br />
Here's a more developed example that deals with speeds higher than the screen width, and wraps both ways:<br />
<br />
<tt style="color:#0077ff;">public int moveHoriz(int howFar){<br />
// Moves the Asteroid horizontally by howFar pixels on a screen.<br />
// It returns the new horizontal pixel location.<br />
<br />
// We have a screen width available to us in member variable xWidth,<br />
// and our x location in xLoc.<br />
// Wraps from right to left, or left to right.<br />
<br />
//Use modulo to trim speed if it's too high.<br />
if (howFar > xWidth) howFar %= xWidth; <br />
<br />
// Calculate the new x location and return it.<br />
return (xLoc + howFar + xWidth) % xWidth;<br />
}</tt><br />
<br />
<h6>Radio Dial image by John McComb.</h6>saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-67608073397428525022012-03-21T03:24:00.000-07:002012-03-21T03:24:00.745-07:00Java Introspection and Using Collections without GenericsIn my prior article on <a href="http://beginwithjava.blogspot.com/2012/03/generics-in-java.html">Generics</a> we looked at how to use Generics to associate at type with data stored in a Collection.<br /><br />You might wonder why would anyone want to store information in a Collection without its type being preserved. Well, it's possible that you'd want to store many Objects of different types in one collection. In that case, the only parent those types might have in common is java.lang.Object. So using a Generic won't do you any good.<br /><br />But, once you pull that data back out of the Collection, how do you find out what it was?<br /><br />Fortunately, the object itself has that information stored with it.<br /><br />There are two easy ways to find out what it is. <tt>instanceof</tt> can test if it is a specific type of Object:<br /><pre style="color:#0033ff;"><br />if (anObject instanceof String) { aString = (String)anObject); }<br /></pre><br /><br />You can also have an Object tell you its type:<br /><pre style="color:#0033ff;"><br />Class myClass = anObject.getClass();<br /></pre><br />or<br /><pre style="color:#0033ff;"><br />String myClassName = anObject.getClass().getName();<br /></pre><br /><br />A look at the documentation for <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html">Object</a> and <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html">Class</a> gives all sorts of useful methods for dealing with classes of data objects in Java.<br /><br />Here's some sample code:<br /><pre style="color:#00dd33;"><br />import java.util.*;<br /><br />public class NoGenerics2{<br />// This is an example of using introspection<br />// to determine types of Objects stored in a<br />// Collection without a Generic declaration.<br /><br /> public static void main(String[] arg){<br /> ArrayList myList = new ArrayList(); // No Generic <String> declaration.<br /> String myString="Boss Moss";<br /> String yourString="Snorkledorf";<br /><br /> // put the strings into the List<br /> myList.add(myString);<br /> myList.add(yourString);<br /><br /> for (Object anObject: myList){<br /> System.out.println(anObject.getClass().getName());<br /> if (anObject instanceof String){<br /> String aString = (String)anObject; <br /> }<br /> else{<br /> System.out.println("Not a String, Sheriff!");<br /> }<br /> }<br /> }<br />}<br /></pre>saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-79426047618662357322012-03-07T09:19:00.006-08:002012-03-07T09:54:04.218-08:00Generics in JavaGenerics are an oddly-named thing in Java that associate objects stored in a Collection with a particular type. Let's take a look at a piece of code that uses a Collection to store some Strings. It uses an ArrayList. Here's the code:<br /><br /><pre style="color:#dd0000;"><br />import java.util.*;<br />public class NoGenerics{<br />// This is an example of what happens <br />// when you don't declare a class<br />// for a Collection using Generics. <br />// It won't compile!<br /><br /> public static void main(String[] arg){<br /> // No Generic <String> declaration.<br /> ArrayList myList = new ArrayList();<br /> String myString="Boss Moss";<br /> String yourString="Snorkledorf";<br /><br /> // put the strings into the ArrayList<br /> myList.add(myString);<br /> myList.add(yourString);<br /><br /> for (String aString: myList){<br /> // We can't do String methods on the items from myList.<br /> if (aString.startsWith("Boss")){<br /> System.out.println(aString + ":");<br /> System.out.println("Make sure you spell it right!");<br /> }<br /> else{<br /> System.out.println(aString + ":");<br /> System.out.println("I am so pretty!");<br /> }<br /> }<br /> }<br />}<br /></pre><br />What happens here to upset <tt>javac</tt> is that once the String is placed in the ArrayList, its type is lost, and it is known only as an Object. To be treated as a String again, it would have to be cast as a String. If any errors are made in casting the data, the program will fail at runtime, not when it is being compiled--when the programmer has it in their hands to fix it.<br /><br /><p style="font-family:monospace;color:#0077ff;">Feel free to take the above code and try to compile it to see the error you'll get. It <em>is</em> instructive.</p><br /><br /><b style="color:#ff7700;">The Fix for Lost Types</b><br /><br />In Java version 1.5 "Generics" were added to fix this. Now Collections like the ArrayList can associate a type with the data put in them, and the compiler can do type checking. Here's the above code, with the Generic declaration <String> added:<br /><br /><pre style="color:#0033ff;"><br />import java.util.*;<br /><br />public class Generics{<br />// This is an example of what happens <br />// when you declare a data class<br />// for a Collection using Generics.<br /><br /> public static void main(String[] arg){<br /> // Generic <String> declaration.<br /> ArrayList<String> myList = new ArrayList<String>();<br /> String myString="Boss Moss";<br /> String yourString="Snorkledorf";<br /><br /> // put the strings into the ArrayList<br /> myList.add(myString);<br /> myList.add(yourString);<br /><br /> for (String aString: myList){<br /> // Now when we can do String methods on the List items.<br /> if (aString.startsWith("Boss")){<br /> System.out.println(aString + ":");<br /> System.out.println("Make sure you spell it right!");<br /> }<br /> else{<br /> System.out.println(aString + ":");<br /> System.out.println("I am so pretty!");<br /> }<br /> }<br /> }<br />}<br /></pre><br /><b style="color:#ff7700;">Generics = Typed Collections</b><br />So if you are going to use a collection on Objects all of a specific type (rather than mixing and matching), put on a Generic declaration.saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-18450452228919292372012-01-23T17:15:00.000-08:002012-01-23T17:26:26.952-08:00Java under Mac OS X 10.7 LionLion is the first version of Mac OS X that doesn't come with Java already installed. Earlier versions not only had the <a href="http://beginwithjava.blogspot.com/2008/07/java-virtual-machine-adapter-cables-for.html">Java Virtual Machine</a> or runtime element installed, but they also had the JDK installed, which is the part that lets you write your own Java programs.<br /><br />Once, Java was an important part of Apple's strategy. They maintained their own version of Java for the Mac and encouraged its use by developers every bit as much as they encouraged the use of Objective-C.<br /><br />The success of the iPhone and the iPad have changed that, however. Apple decided that Java would not be part of those platforms. The lack of Java is the very reason I've chosen not to get an iPhone. Instead, I get phones with Java so that I can run my own Java applications that I write for my own use.<br /><br />Now that Lion doesn't have Java pre-installed, what do you do? Fortunately, a deal has been struck where Java is still available for the Mac. It's much the same arrangement as Java for other platforms. In fact, it's easier to install Java on your Mac than any other platform. And you get the JDK along with the runtime (JVM) environment.<br /><br />Simply use Finder to go to Applications=>Utilities. There, start Terminal. Once Terminal starts, type in the command 'javac'. Your Mac will tell you that Java isn't installed, and let you install it.<br /><br />I'm pleased that the Mac has not entirely forsaken Java, even if it's not an integral part as it has been. The basic software supplied with the Mac has declined severely over the past few years, but fortunately Java is still available and easy to install when you want it.saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-20543685025997227112012-01-06T23:58:00.000-08:002012-01-07T00:18:36.661-08:00Embedded JavaEmbedded Java sounds almost like an oxymoron. Taking a high level, large, interpreted language like Java and using it in an application field dominated by assembly and C certainly seems odd. But it's a reality.<br /><br />For one thing, the microcontrollers of today are not the limited 1K to 2K ROM, 8-bit, 200kHz machine cycle rate CPUs of yesteryear. They're more powerful than the desktop systems of 10-15 years ago in many cases. And we were playing Quake II on those. So maybe Java isn't quite such a stretch, after all.<br /> <br /><a href="http://www.harbaum.org/till/nanovm/index.shtml">NanoVM</a> is a small, subscale Java-ish virtual machine that runs on tiny 8-bit microcontrollers like the AVR ATMega8. It's not a full Java, but it covers most of what's interesting to the microcontroller programmer.<br /><br />The <a href="http://www.systronix.com/jstamp/">JStamp</a> is a Java development system for the aJile micros. It's also not a full Java SE implementation (what would you do with the extra bits, even if it was?), but it is a verifiable real-time Java system for embedded development.<br /><br />Also, <a href="http://www.is2t.com/en/index.php">IS2T</a> has MicroEJ, another embedded Java for a number of processors. Everything from the basics of execution and I/O up to GUIs, SOAs, and safety-critical libraries are available.<br /><br />I still remember when it was considered laughable to consider a C-language embedded development system. But it has either nudged assembly out of the top spot for embedded development or is close to it, now. Any language that is popular enough can be brought to the task now, and Java is no exception.<br /><br />It's all just a bunch of ones and zeroes in the end.saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-39961889508264852952011-10-20T19:47:00.000-07:002011-10-20T20:23:01.198-07:00Mobile JavaOne of the nice things about Java is that is supported on more than desktop platforms, and has been for a long time. This means there is not only a large library of existing software, but also well-tuned development systems to use with mobile platforms.<br /><br />By "mobile platform", I'm referring to smartphones and tablets. There are other mobile platforms, but these are the most common ones. Netbooks may also run a "mobile" operating system, or they may run a normal desktop OS. Those that run a normal desktop OS will run normal <a href="http://www.oracle.com/technetwork/java/javase/overview/index.html">Java SE</a> applications. Java SE is "Java, Standard Edition", the version that typically runs on a desktop or laptop computer.<br /><br /><a href="http://www.oracle.com/technetwork/java/javame/index.html">Java ME</a> is Java, Mobile Edition. It runs on most smartphones, and many tablets. It is very similar to the Java SE version covered in most of my articles. In fact, it is possible to write many applications using a subset of Java that will run without change under both Java SE and Java ME.<br /><br />But normally a Java ME application will use user interface objects and interfaces that are specific to Java ME. In many ways these are more sophisticated than the ones for Java SE. Creating many types of graphical interfaces, such as tiled graphics, is easier in the mobile edition than in standard Java.<br /><br />I have been writing small, simple applications for my cellphones for about ten years now. It's nice to be able to write your own little application for your own unique needs. I started writing Java applications for my <a href="http://en.wikipedia.org/wiki/Nokia_3600/3650">Nokia 3650</a>, called a "feature phone" at the time I got it. It was a Symbian Series 60 phone that ran an early version of Java ME with a very basic library of GUI features.<br /><br />My next phone was a step up the Java ladder. It was a <a href="http://catsonkeyboards.blogspot.com/2009/05/sciphone-g2-first-impressions.html">Sciphone G2</a>, a fake Android phone. I didn't mind that it was "fake", it ran a real version of Java ME with updated GUI capabilities, which made it far easier to write applications for.<br /><br />My current phone is a <a href="http://us.blackberry.com/smartphones/blackberrycurve8900/">Blackberry Curve 8900</a>. It runs Java ME with all the latest bells and whistles, plus a lot of Blackberry add-ons that make it easy to access the phone's features.<br /><br />With my Nokia, I had a special Java development environment provided by Nokia that included a simulation of my phone, so that I could see how my programs would run before I put them on the phone. With the G2 I was on my own. I ran a standard Java ME development environment from within <a href="http://eclipseme.org/">Eclipse</a>, a great Java <a href="http://beginwithjava.blogspot.com/2008/07/killer-java-ides-for-beginners-bluej.html">integrated development environment</a>. The version linked above is a version specific to Java ME.<br /><br />Now I'm back to having a <a href="http://supportforums.blackberry.com/t5/Java-Development/tkb-p/java_dev%40tkb?labels=tutorial">development environment</a> provided by my phone's maker. I have a program that simulates my phone on my computer, which again allows me to try out my programs before I put them on the phone (with my G2 I tested them as well as I could, then loaded them on the phone and hoped for the best.) It is build on Eclipse, so it is still very familiar. There is also a slew of information on the Blackberry site (linked above) about Java development.<br /><br />Unfortunately, the tutorials on the site don't exactly match the actual current version of the software, but it's close enough it's not too hard to figure out. One thing that confused me, however, is the installation instructions. I thought I had to install the version of Eclipse they called for before installing the "Blackberry Java Eclipse Add-On". It's an add-on, right?<br /><br />Well, it turns out that the "add-on" from Blackberry is actually the entire thing, Eclipse and all. So you just need to do that one download to get the development environment. Then download the simulator for your phone and any others you want to test your software on. Finally, apply for a signature key to make it so that you can "sign" your software to allow it to be installed on the phone through the software manager or Over The Air (OTA) when using the Blackberry-specific libraries.<br /><br />If you'd rather not do this, you can develop software using a plain-jane version of Java ME, then transfer the software to your phone however you please. I put the software I developed for my Sciphone G2 on the memory card for my Blackberry, and it runs just fine.<br /><br />Translating applications between Java SE and Java ME can be simple for ones with minimal amounts of graphics, like programs that mainly use text, buttons, and text entry boxes for communication. Things like games, with a more involved use of graphics, take more effort to translate between the two versions of Java. For these, I usually re-use the game logic code without changes, then rewrite the graphical display parts of the program from scratch. Because I use good object-oriented coding practices (most of the time), this isn't too much effort.<br /><br />Java ME applets are easy to translate, though I write almost all of my Java software as applications now.saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-56005509054728508382011-09-05T21:00:00.000-07:002011-09-05T21:37:50.859-07:00Numeric Literal ValuesJava 7 has added a new feature, binary literals for integer number types (byte, short, int, and long.) Before we can get excited about this, we need to know what that means. In earlier versions of Java, we have had several other types of literal value.<br /><br /><b style="color:#ff7700;">Let's Get Literal</b><br /><br />What is a "literal"? A literal is an explicit value. For example, in this line:<br /><tt style="color:#0077ff;">int number=123;</tt><br />the value <tt style="color:#0077ff;">123</tt> is a "literal". Since it's a normal base-10 value, we might say it is a "decimal literal". Decimal values don't have to be marked in any special way.<br /><br />A hexadecimal literal looks like this:<br /><tt style="color:#0077ff;">int number=0x007b;</tt><br />The value <tt style="color:#0077ff;">0x007b</tt> is a hexadecimal (base 16) number that is expressed literally (stated explicitly.) The <tt style="color:#0077ff;">0x</tt> at the beginning is what marks it as a hexadecimal value. The leading zero shows that it's a numerical value, not a variable name or keyword or something like that. The x marks it as a hexadecimal number.<br /><br />Hexadecimal numbers take binary values four bits at a time (a bit is a single one or zero value) and puts them into a single digit. Octal (base 8) digits each represent the values of three bits.<br /><br />To tell Java you're using an octal value, place a leading zero in front of the number itself:<br /><tt style="color:#0077ff;">int number=0173;</tt><br />Here the number <tt style="color:#0077ff;">0173</tt> is an octal value equal to 123 in decimal. If we accidentally put a zero in front of a decimal integer, we'll either get an error (if we use the digits 8 or 9 in that number) or the value will be interpreted incorrectly. For example, if we want to put the value of one hundred twenty-three into a variable, but instead of the line we have above we accidentally add a zero, like this:<br /><tt style="color:#0077ff;">int number=0123;</tt><br />The value of the number will be interpreted as eighty-three, not one hundred twenty-three. So watch out for that.<br /><br /><b style="color:#ff7700;">New for Java 7--Binary Literals</b><br />In Java 7 we get a new ability, the use of binary numbers. Since you know that you can encode binary values into both octal and hex either three or four bits at a time, this may not seem like a really big deal. In fact, there's been a request to add this feature to Java for a long time, but it's been low priority.<br /><br />But now it's finally here.<br /><br />So you can define values as individual bits, like this:<br /><tt style="color:#0077ff;">int number=0b01111011;</tt><br />That's the binary for one hundred twenty-three, by the way. Why is this important?<br /><br />As Java becomes more mature, and more widely used, it is used in more places. Over time, high level languages that deal with things at a very abstract level tend to get used in more situations where it is nice to have the high level features while also having the ability to have low level control or simulation of the actual computer hardware. In cases like these, it is nice to be able to manipulate single bits in places where they represent specific individual signals in the computer system or simulation.<br /><br />For example, let's say we want to recreate an old 1980s computer in a Java program, like a Commodore 64. The Commodore 64 reads several signal lines directly on its joystick ports. We want to be able to simulate the behavior of these ports so that we can play old C-64 games in our simulation. Each of the lines represents a switch in the joystick. So we may take a particular keypress and represent it as the following binary value:<br /><br /><tt style="color:#0077ff;">byte stick_up=0b00001;</tt><br /><br />In this case, we show it setting the lowest order bit. We might have another like this:<br /><br /><tt style="color:#0077ff;">byte fire_switch=0b100000;</tt><br /><br />Since these each equate to specific electrical signals that get "turned into bits" in the C-64's CIA chip, it's nice to be able to tell them to Java as bits. We could have used hex or octal, but it's a bit nicer to see them as individual bits.saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-64042733458570003692011-06-24T17:16:00.000-07:002011-06-24T18:03:22.487-07:00Java Variable Value Assignment: Left Equals Right, Left Becomes RightOne of those things that vexes beginning programmers is assigning values to a variable in Java. Part of what makes it so vexing is that the problem is practically invisible to an experienced programmer. Another part of it is that we use the equals sign (=) to do the assignment.<br /><br />Take a look at these statements:<br /><br /><code style="color:#33ff33;">int i = 1;</code><br /><code style="color:#33ff33;">j=7;</code><br /><code style="color:#ff3333;">7+count=c;</code><br /><code style="color:#ff3333;">b+14=a+9;</code><br /><br />The first two are fine (assuming that 7 is a valid value for whatever type of variable <tt>j</tt> is), but the last two are wrong.<br /><br /><b style="color:#ff7700;">Remember All That Algebra We Taught You? Well, We Broke It.</b><br /><br />After you've gone to all the trouble to learn how to deal with things like <tt>7+count=c</tt> and <tt>b+14=a+9</tt> in algebra class, now we take what you know and turn it on its ear in programming class. Sweet, eh?<br /><br />The problem is that the <tt>=</tt> we use in programming has pretty much nothing to do with the <tt>=</tt> that you use in math. It's just close enough to be confusing. In Java, the equals sign is an <em>assignment</em> operator, not an indicator of equality between values as it is in math. There is a comparison operator for equality in Java, it's <tt>==</tt>, and we'll talk about it shortly. First, let's talk assignment.<br /><br /><b style="color:#ff7700;">Assignment</b><br /><br />In computers, we use the term assignment to describe sticking a value into the computer's memory so that we can get it back later. It's like using the memory in a programmable calculator. We put some number into our calculator's memory so that we can get it back later for another part of our calculation. It's pretty much the same thing with computers.<br /><br />With Java, we can store all kinds of values, not just numbers. We can store sections of text, called <em>strings</em> in a <tt>String</tt> variable, for example. (Java prefers the term "member" over variable, in general. For what we're talking about now, the two terms are interchangeable.) We can also store more than one thing at a time, like all the information about a bicycle in a Bicycle object that keeps track of a bicycle's color, frame size, tire size, gear ratios, etc., all together in one object.<br /><br />But we're here to just look at assignment today, not the wide variety of things we can assign as values.<br /><br />To store a value on a calculator, you use some key sequence like <tt>M+</tt> or <tt>STO 00</tt> to store the value in the calculator's display to memory. With Java, we use the equals sign to store some value on the right into whatever is on the left side of the equals sign. We read from left to right like this:<br /><br /><tt>count = a;</tt><br />"count equals a"<br /><br />This means we take the value of <tt>a</tt> and place it in <tt>count</tt>. But a better way to read that equals sign is to use the word "becomes" instead of "equals":<br /><br /><tt>count = 9;</tt><br />"count <b>becomes</b> nine"<br /><br />This makes it more obvious that we're putting in a new value that changes the value of <tt>count</tt>. In this case, we're putting in a value of 9. The statement up above would be "count becomes a" or, better yet, "count becomes a's value." Because what we're doing in <tt>count= a;</tt> is taking the value in variable <tt>a</tt> and copying it into <tt>count</tt>. If we then print the value in <tt>count</tt>, it will be the same as whatever is in <tt>a</tt> at that time.<br /><br />We can also compute a value to put into our variable.<br /><br /><tt>count = a + 1;</tt><br />"count becomes a plus one"<br /><br />This makes the value in <tt>count</tt> be one more than the current value of <tt>a</tt>.<br /><br />What we <b>can't</b> do is change sides around the equals sign. In algebra, <em>c = a + 1</em> is the same as <em>a + 1 = c</em>. But in Java that doesn't work:<br /><br /><tt style="color:#ff3333;">a + 1 = count</tt><br />This is wrong in Java. Does not compute. Norman, Norman, help me Norman!<br /><br />We would be trying to make a+1 become the value in count. The problem is, you can't have a storage location named "a+1". Java doesn't see this the way your algebra trained eyes do.<br /><br /><b style="color:#ff7700;">Comparisons</b><br /><br />In normal math, when we use the equals sign we are making a comparison. We are stating that what's on one side of the equals sign is the same as what's on the other side. For most algebra problems, we assume that the statement is true and try to find values for the variables that result in that.<br /><br />Another use of equals in some math problems is to state that two things are equal when they may or may not be, then determine whether that statement is true or not. You remember those problems, they looked something like this:<br /><br /><tt>State whether each of the following is true or false.</tt><br /><tt>1. 11 = 6 + 5<br />2. 14 = 3 x 7<br />3 65 - 14 = 17 x 3</tt><br /><br />In Java, the equals sign is already used for assigning values to variables. How do we do a comparison to see whether it's true or not?<br /><br /><b style="color:#ff7700;">The == Operator</b><br /><br />In some languages, <tt>=</tt> does both jobs. But in Java, there's a second operator for doing equality comparisons, <tt>==</tt>, "equals equals". When we want to see if two values are the same, we compare them using a statement something like this:<br /><br /><tt>if (count == 100) then stop();</tt><br /><br />This compares <tt>count</tt> to the value <tt>100</tt>, and executes the method <tt>stop()</tt> if the result of the comparison is <tt>true</tt>.<br /><br /><br /><b style="color:#ff7700;">The Dangers of the = Operator</b><br /><br />Something to look out for is using <tt>=</tt> by accident in such a situation. Like this:<br /><br /><tt style="color:#ff3333;">if (count = 100) then stop();</tt><br />Don't do this if you want to compare count to 100!<br /><br />What this does is <em>assign</em> the value 100 to <tt>count</tt>. If the assignment is successful (which it almost certainly will be, if the program compiles), the program will then do <tt>stop()</tt> every time it hits this statement! Because the assignment was successful, so the result is considered to be <tt>true</tt>.<br /><br /><b style="color:#ff7700;">Summary</b><br /><br />The equals sign makes the variable on the left equal the computed value from the right side of the equals sign:<br /><br /><tt>name = "Mergatroyd";</tt><br />"name becomes Mergatroyd"<br /><br />It doesn't work the other way around (putting something from the left into the variable on the right.)<br /><br />If you want to compare to values to see if they're equal, use "equals equals":<br /><tt>if (state == "done") then exit();</tt><br />"if state equals equals done then exit" or<br />"if state is equal to done then exit"saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-86390494994494657392011-06-07T13:16:00.000-07:002011-06-07T14:49:10.645-07:00Doing Math in Java part 2:FunctionsThe basics of math in Java using operators was covered in <a href="http://beginwithjava.blogspot.com/2011/05/doing-math-in-java-part-1-operators.html">Part 1: Operators</a>. There I went over the standard operations built into the language itself, rather than in its APIs (libraries).<br /><br />But that's hardly the end of useful math operations. Especially when doing graphics, where all those geometric and trigonometric functions come in so useful. Square root, cosine, absolute values, etc.<br /><br />If you're wandering into the Java APIs unguided, the java.math package might catch your eye right away. Unfortunately, it's a false trail when what you're looking for is a simple general purpose math package (it's a nice special-purpose math package for particular sorts of calculation, however.) <br /><br />What you really want is the <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Math.html">java.lang.Math</a> class, in the java.lang package.<br /><br />This has most of the standard math functions you're used to. They're defined as static methods, so you don't need to create a Math object to use them. You just call them like this:<br /><br /><pre style="color:#0077ff;"><tt> float distance = Math.sqrt(dx*dx + dy*dy);<br /> float speed = Math.abs(velocity);</tt></pre><br /><br />These call the square root function <code>Math.sqrt()</code> and absolute value function <code>Math.abs()</code>. There are a slew of others like degree to radian conversion, the standard trig functions, and so on.<br /><br /><b style="color:#ff7700;">Date Calculations</b><br /><br />Calculations with dates are another standard sort of math that's not covered by standard operators. In the package java.util we've got <a href="http://download.oracle.com/javase/6/docs/api/java/util/Calendar.html">the Calendar class</a>. The Calendar class itself is an abstract class. This means that it's a class used to build other classes with, not to use directly. The <a href="http://download.oracle.com/javase/6/docs/api/java/util/GregorianCalendar.html">GregorianCalendar</a> class is a concrete implementation of <code>Calendar</code> that you can use directly. The Calendar object's add() method will add or subtract some amount of time--days, minutes, hours, etc.--to or from a given date (the date that the object is set to:<br /><ol><br /><li>Create a GregorianCalendar Object</li><br /><li>Set its date</li><br /><li>Use its add() method to add or subtract the time difference.</li><br /></ol><br />Example:<br /><pre><tt style="color#00ff33;">GregorianCalendar myDate;<br />myDate = new GregorianCalendar(2011, 6, 7); //set the date to 07 June 2011.<br />myDate.add(Calendar.Date, 165); // add 165 days to that date.<br /></tt></pre><br /><br /><code>before()</code>, <code>after()</code> and <code>compareTo</code> will return whether one date occurs before or after another. Computing the number of days between two dates is a bit more complex, unfortunately, as are similar calculations. Basically, the procedure is to use getTime() to convert both dates to time values, get the difference, then divide that by the time units you want to see the difference in (e.g. divide by 24 hours periods to get the difference in days.)<br /><br />Unfortunately, the Calendar class demonstrates one of the problems with much of Java. It's an overly generalized class that prevents simple solutions to many simple and obvious problems. The older Date class took a more direct approach, but it has been deprecated in favor of the Calendar based classes. Unfortunately, even obtaining a printable date value according to the system's current locale takes a fair bit of set up in Java. A better solution would have been a very general class like Calendar behind a more usable class for solving conventional problems, but Java's development got it backward. We got the simple class first, it's inflexibility for solving certain problems resulted in criticism, then came a general class, which is no good at doing simple and obvious things for most users. The extra layer that we should have to make Calendar more usable has not yet appeared in the standard API (and possibly never will.)<br /><br />So it takes a lot of code to do what should only take a line or two, when working with dates.<br /><br />Still, give the Calendar and GregorianCalendar class a look-over. Even though it takes some extra code and set-up to do some simple tasks, the solutions to these problems are well established and many examples are available. It's just not as simple as System.out.println(myDate);<br /><br />I'll be adding articles dealing specifically with dates myself at a future date.saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-44860909021118249622011-05-27T14:31:00.000-07:002011-05-27T15:30:41.208-07:00Doing Math in Java part 1: OperatorsOne of the most valuable uses of a computer is...computing. That is, acting as a mathematical calculator. Java has a plethora of tools for doing computation.<br /><br /><b style="color:#ff7700;">Operators</b><br /><br />The standard math functions that are built into the Java language are called <em>operators</em>. These are the sort of math functions you would expect to find on a simple calculator, plus some extras:<br /><br /><b><tt><pre>+ - * / % ++ --</pre></tt></b><br /><br />There are other operators used for comparisons, these are the math operators. You can learn more about them in the <a href="http://java.sun.com/docs/books/jls/">Java Language Specification</a>, specifically in <a href="http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.2">Integer Operations</a>, <a href="http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.4">Floating-Point Operations</a>, and more extensively through <a href="http://java.sun.com/docs/books/jls/third_edition/html/expressions.html">Chapter 15, Expressions</a>.<br /><br /><tt>+</tt> and <tt>-</tt> do what you would expect, they add and subtract one value from another. <tt>*</tt> is the symbol used for multiplication, instead of the × used in math class. <tt>*</tt> is used because it's easier for the computer to recognize it as a math operator, × just looks like a letter 'x' to the computer. Similarly, <tt>/</tt> is used for division. The ÷ sign isn't on most keyboards, but / has been common on keyboards even before they were attached to computers.<br /><br />The % sign doesn't do what you might, at first, expect. It doesn't calculate a percentage, as it does on most calculators. It returns the remainder of a division. For example, if you do 10/3 (ten divided by three), the result will be 3. But what if you want to get the remainder? That's what % does. 10%3 will return a value of 1. '%' is sometimes called "modulo". It's a bit of a misnomer, mathematically, but the use of the term is common and well understood, so it's not unusual to pronounce 10%3 as "ten modulo three". This is a very valuable function for keeping a value within a certain range, such as keeping an object located onscreen in graphics by having it "wrap" from one side of the screen to the other when it reaches an edge.<br /><br /><tt>++</tt> and <tt>--</tt> are the "increment" and "decrement" operators. Increment means "go up by one unit", and decrement "go down by one unit". So if you've got a variable like:<br /><br /><code>int i = 5;</code><br /><br />And you do <code>i++</code>, the value of <code>i</code> will become 6. Doing <code>i--</code> will take away 1. <tt>++</tt> and <tt>--</tt> can be placed either before or after the value they act on, for example:<br /><br /><code>number = i++;<br />count = --j;</code><br /><br />There will be different effects on your program depending on whether they come before or after the value. You can find information on that in the Java Language Specification as well, in sections <a href="http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.14">15.14</a> and <a href="http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.15">15.15</a> which cover the two ways of using these operators. In general, it's best to stick to using them <em>after</em> your value until you understand the differences.<br /><br /><b style="color:#ff7700;">Assignment Operators</b><br /><br />You can also do math as part of assigning a value. For example, let's say we want to add three to a value in our program. The obvious way to do this would be:<br /><br /><code>i = i + 3;</code><br /><br />This takes the prior value of <tt>i</tt>, adds 3 to it, then puts the result back into variable <tt>i</tt>. With an <em>assignment operator</em> we can do the same thing more tersely:<br /><br /><code>i += 3;</code><br /><br />We've combined the <tt>+</tt> with <tt>=</tt> to create an operator. This does the same thing as <code>i = i + 3;</code>. Your program doesn't care which way you type it. The same thing can be done with the other operators that take two values:<br /><br /><code style="color:#0077ff;">i *= 4; // Multiply i by four, store result back in i.<br />i /= 2; // Divide i in half.<br />i %= 3; // Put the remainder of i/3 in i.<br />i -= 7; //Subtract seven from i.</code><br /><br /><b style="color:#ff7700;">More Complex Math</b><br /><br />This is what we can do with the basic math operators built into the language. To get more operations, like those found on a scientific or programmer's calculator, we use methods of some of the standard packages of Java. Which I'll cover in a future article.<br /><br />Until then, have a look at <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Math.html">java.lang.Math</a>.saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-54241006882924301782011-05-20T13:49:00.000-07:002011-05-20T14:52:29.270-07:00Your Own Java ClassesTo use Java effectively, you want to create and use your own classes. This is one of the great powers of object-oriented languages--the ability to construct programs out of independent building-blocks that cut large problems down into small, easily solvable ones. There's a lot more that can be said, and much of it is elsewhere. So I'll get right into a very simple, very basic example here.<br /><br />We're going to create a very simple object class that will print a "Hello" message to the screen when called. This class will have two different methods that will do the same thing, though we'll vary the messages they print a bit so that we can see which one is doing the work.<br /><br />Here's our class: <a href="http://saundby.com/beginwithjava/code/HelloClass.java">(download HelloClass.Java)</a><br /><br /><pre style="color:#0077ff;">public class HelloClass{<br /><br />/**<br /> * sayHello() prints "Hello!" to the Java console output.<br /> */<br /> public void sayHello(){<br /> System.out.println("Hello!\n");<br /> }<br /><br />/**<br /> * doHello() prints "Hello, hello!" to the Java console output.<br /> * It's static, so you don't need to instatiate a HelloClass <br /> * object to use it.<br /> */<br /> public static void doHello(){<br /> System.out.println("Hello, hello!\n");<br /> }<br /><br />} // End of HelloClass</pre><br /><br />The two methods we have to print messages are <tt>sayHello()</tt> and <tt>doHello()</tt>. To use <tt>sayHello()</tt>, we need to have a <tt>HelloClass</tt> object created, then call that object's <tt>sayHello()</tt> method.<br /><br /><tt>doHello()</tt>, however, is a <tt>static</tt> method. This means is belongs to the class, not to any object of the class. So we can use it without any <tt>HelloClass</tt> objects being created first.<br /><br />Here's a class that uses these methods as described: <a href="http://saundby.com/beginwithjava/code/UseHello.java">(download UseHello.java)</a><br /><br /><pre style="color:#00ff77;">public class UseHello{<br /> public static void main(String[] arg){<br /><br /> // We can use doHello() without a HelloClass object:<br /> HelloClass.doHello(); // call the HelloClass's doHello() method.<br /><br /> // But we need to create a HelloClass object to use sayHello():<br /> HelloClass hello=new HelloClass();<br /> hello.sayHello(); // call hello's sayHello() method.<br /><br /> }<br />} // End of UseHello.</pre><br /><br />If we try to call <tt>sayHello()</tt> without first creating a HelloClass object, like this:<br /><tt>HelloClass.sayHello();</tt><br /><br />then we'll get the dreaded "calling a non-static method from a static context" error message. That's letting you know that you need to instantiate (or create) a HelloClass object first, then tell that object to call its method.<br /><br />Static methods are useful for things like general arithmetic and calculation or other methods that might be used in a way where state information is unimportant. But beware, it's easy to create static methods when what's really wanted is an object that does what you want.<br /><br />Files available for download through: <a href="http://saundby.com/beginwithjava/">http://saundby.com/beginwithjava/</a>.saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-57002865052272581842011-05-13T11:35:00.000-07:002011-05-18T11:19:36.216-07:00A Java CSV File ReaderOne of the most common types of data file is a CSV (Comma Separated Value) file. They can be exported by many popular applications, notable spreadsheet programs like Excel and Numbers. They are easy to read into your Java programs once you know how.<br /><br />Reading the file is as simple as <a href="http://beginwithjava.blogspot.com/2011/05/java-file-save-and-file-load-text.html">reading a text file</a>. The file has to be opened, a BufferedReader object is created to read the data in a line at a time.<br /><br />Once a line of data has been read, we make sure that it's not <tt>null</tt>, or empty. If it is, we've hit the end of the file and there's no more data to read. If it isn't, we then use the split() method that's a member of Java's String object. This will split a string into an array of Strings using a delimiter that we give it.<br /><br />The delimiter for a CSV file is a comma, of course. Once we've split() the string, we have all the element in an Array from which our Java programs can use the data. For this example, I just use a <tt>for</tt> loop to print out the data, but I could just as well sort on the values of one of the cells, or whatever I need to do with it in my program.<br /><br /><b style="color:#ff7700;">The Steps</b><br /><br /><ol><li>Open the file with a BufferedReader object to read it a line at a time.</li><br /><li>Check to see if we've got actual data to make sure we haven't finished the file.</li><br /><li>Split the line we read into an <i>Array</i> of String using String.split()</li><br /><li>Use our data.</li></ol><br /><br /><b style="color:#ff7700;">The Program</b><br /><pre style="color:#0077ff;"><span style="color:#00ff77;">// CSVRead.java<br />//Reads a Comma Separated Value file and prints its contents.</span><br /><br />import java.io.*;<br />import java.util.Arrays;<br /><br />public class CSVRead{<br /><br /> public static void main(String[] arg) throws Exception {<br /><br /> BufferedReader CSVFile = <br /> new BufferedReader(new FileReader("Example.csv"));<br /><br /> String dataRow = CSVFile.readLine(); <span style="color:#00ff77;">// Read first line.</span><br /><span style="color:#00ff77;"> // The while checks to see if the data is null. If <br /> // it is, we've hit the end of the file. If not, <br /> // process the data.</span><br /><br /> while (dataRow != null){<br /> String[] dataArray = dataRow.split(",");<br /> for (String item:dataArray) { <br /> System.out.print(item + "\t"); <br /> }<br /> System.out.println(); // Print the data line.<br /> dataRow = CSVFile.readLine(); <span style="color:#00ff77;">// Read next line of data.</span><br /> }<br /><span style="color:#00ff77;"> // Close the file once all data has been read.</span><br /> CSVFile.close();<br /><br /><span style="color:#00ff77;"> // End the printout with a blank line.</span><br /> System.out.println();<br /><br /> } <span style="color:#00ff77;">//main()</span><br />} <span style="color:#00ff77;">// CSVRead</span></pre><br /><br /><b style="color:#ff7700;">Downloads</b><br /><br /><a href="http://saundby.com/beginwithjava/code/CSVRead.java">This program</a>, and <a href="http://saundby.com/beginwithjava/code/Example.csv">an example CSV file</a> to use it with (a section of a spreadsheed I use to keep track of my integrated circuits) are available at <a href="http://saundby.com/beginwithjava/index.shtml">my code archive</a>.<br /><br /><b style="color:#ff7700;">Writing to CSV Files with Java</b><br /><br />Writing to a CSV file is as simple as <a href="http://beginwithjava.blogspot.com/2011/05/java-file-save-and-file-load-text.html">writing a text file</a>. In this case, we write a comma between each field, and a newline at the end of each record.<br /><br />Give it a try, starting with <a href="http://saundby.com/beginwithjava/code/TextSave.java">TextSave.java</a>, modify it appropriately, then see what your favorite spreadsheet program thinks of the results.saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-20808859460927513342011-05-06T12:58:00.000-07:002011-05-06T13:51:16.186-07:00Java File Save and File Load: TextWe've looked at <a href="http://beginwithjava.blogspot.com/2011/04/java-file-save-and-file-load-objects.html">saving and loading objects</a> to files. If we need to exchange information for use by a different program than our own it will seldom be convenient to save objects. Text files are commonly used to do this.<br /><br />Text files are even simpler to deal with than Object files, thanks to classes in the java.io package. FileWriter gives us everything we need to write from our program to a text file. All we need to do is feed it String data.<br /><br />FileReader lets us access a file, but using a BufferedReader makes it a lot easier to handle reading data from a file as lines of text.<br /><br /><span style="color:#77ff00;">As with object files, the basic steps are:<br />1. Open a file.<br />2. Write or read data.<br />3. Close the file.</span><br /><br />Here are example programs, the first writes a simple text file. After you run it, you can take a look at the file it creates (in the same directory) using your favorite text viewer. You'll see normal text written line by line.<br /><br />Then run the second program. It reads in the information line by line. It takes advantage of the fact that we know the format of the data file to read what's in it back into Java objects. You can do the same thing with any file that you either know the format of, or can detect the format of. For example, reading data from CSV files saved by spreadsheets (I'll provide a specific example of this in a future article.)<br /><br />As always, you can download the program files from <a href="http://saundby.com/beginwithjava/index.shtml">the Begin With Java Code Archive</a>.<br /><br /><h3><a href="http://saundby.com/beginwithjava/code/TextSave.java">TextSave.java</a></h3><pre style="color:#0077ff;"><br />import java.io.*;<br /><br />public class TextSave{<br /><br /> public static void main(String[] arg) throws Exception {<br /> // Create some data to write.<br /> int x=1, y=2, z=3;<br /> String name = "Galormadron", race = "elf";<br /> boolean hyperactive = true;<br /><br /> // Set up the FileWriter with our file name.<br /> FileWriter saveFile = new FileWriter("TextSave.txt");<br /><br /> // Write the data to the file.<br /> saveFile.write("\n");<br /> saveFile.write(x + "\n");<br /> saveFile.write(y + "\n");<br /> saveFile.write(z + "\n");<br /> saveFile.write(name + "\n");<br /> saveFile.write(race + "\n");<br /> saveFile.write(Boolean.toString(hyperactive) + "\n");<br /> saveFile.write("\n");<br /><br /> // All done, close the FileWriter.<br /> saveFile.close();<br /><br /> } //main()<br />} // TextSave</pre><br /><br /><h3><a href="http://saundby.com/beginwithjava/code/TextRead.java">TextRead.java</a></h3><pre style="color:#00ff77;"><br />import java.io.*;<br /><br />public class TextRead{<br /><br /> public static void main(String[] arg) throws Exception {<br /> int x, y, z;<br /> String name = "", race = "";<br /> boolean hyperactive;<br /><br /> BufferedReader saveFile=<br /> new BufferedReader(new FileReader("TextSave.txt"));<br /><br /> // Throw away the blank line at the top.<br /> saveFile.readLine(); <br /> // Get the integer value from the String.<br /> x = Integer.parseInt(saveFile.readLine()); <br /> y = Integer.parseInt(saveFile.readLine());<br /> z = Integer.parseInt(saveFile.readLine());<br /> name = saveFile.readLine();<br /> race = saveFile.readLine();<br /> hyperactive = Boolean.parseBoolean(saveFile.readLine());<br /> // Not needed, but read blank line at the bottom.<br /> saveFile.readLine(); <br /><br /> saveFile.close();<br /><br /> // Print out the values.<br /> System.out.println("x=" + x + " y=" + y + " z=" + z + "\n");<br /> System.out.println("name: " + name + " race: " + race + "\n");<br /> if (hyperactive) <br /> System.out.println("Oh, yeah. He's hyperactive all right.");<br /> else System.out.println("What a mellow dude.");<br /> System.out.println();<br /><br /> } //main()<br />} // TextRead</pre>saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-18055130516373401352011-04-14T12:51:00.000-07:002012-10-02T07:46:16.614-07:00Java File Save and File Load: Objects<a href="#restore"><tt>Jump to Reading Data from Files with Java>></tt></a><br />
<br />
<a name="save"><h3>Saving Data to Files with Java</h3></a><br />
Saving objects to a file in Java has a few steps to it, but it's pretty easy. We open a file to write to, create a "stream" for putting objects into the file, write the objects to that stream to put them in the file, then close the stream and file when we're done.<br />
<br />
To reiterate:<br />
<span style="color:#77dd00;"><br />
1. Open a file.<br />
<br />
2. Open an object stream to the file.<br />
<br />
3. Write the objects to that stream.<br />
<br />
4. Close the stream and file.<br />
</span><br />
<b style="color:#ff7700;">1. Opening the File</b><br />
To open a file for writing, we use a FileOutputStream object. When we construct the new FileOutputStream, we give it a file name to open. If the file name exists, it opens the existing file. Otherwise, it creates a new file. To keep things simple, we're not going to check for a file existing here, or anything like that.<br />
<br />
Example:<br />
<span style="color:#00aa00;">FileOutputStream saveFile = new FileOutputStream("saveFile.sav");</span><br />
<br />
<b style="color:#ff7700;">2. Open an Object Stream</b><br />
To write objects to the FileOutputStream, we create an ObjectOutputStream. We give it the FileOutputStream object we've set up when we construct the new ObjectOutputStream object.<br />
<br />
Example:<br />
<span style="color:#00aa00;">ObjectOutputStream save = ObjectOutputStream(saveFile);</span><br />
<br />
<b style="color:#ff7700;">3. Write Objects</b><br />
When we write objects to the ObjectOutputStream, they are sent out through it to the FileOutputStream and into the file.<br />
<br />
Example:<br />
<span style="color:#00aa00;">save.writeObject(objectToSave);</span><br />
<br />
<b style="color:#ff7700;">4. Close Up</b><br />
When we close the ObjectOutputStream, it'll also close our FileOutputStream for us, so this is just one step.<br />
<br />
Example:<br />
<span style="color:#00aa00;">save.close();</span><br />
<br />
Example Program:<br />
<pre style="color:#0077ee;font-size:9pt;">import java.io.*;
import java.util.ArrayList;
public class SaveObjects{
public static void main(String[] arg){
// Create some data objects for us to save.
boolean powerSwitch=true;
int x=9, y=150, z= 675;
String name="Galormadron", setting="on", plant="rutabaga";
ArrayList<string> stuff = new ArrayList<string>();
stuff.add("One");
stuff.add("Two");
stuff.add("Three");
stuff.add("Four");
stuff.add("Five");
try{ // Catch errors in I/O if necessary.
// Open a file to write to, named SavedObj.sav.
FileOutputStream saveFile=new FileOutputStream("SaveObj.sav");
// Create an ObjectOutputStream to put objects into save file.
ObjectOutputStream save = new ObjectOutputStream(saveFile);
// Now we do the save.
save.writeObject(powerSwitch);
save.writeObject(x);
save.writeObject(y);
save.writeObject(z);
save.writeObject(name);
save.writeObject(setting);
save.writeObject(plant);
save.writeObject(stuff);
// Close the file.
save.close(); // This also closes saveFile.
}
catch(Exception exc){
exc.printStackTrace(); // If there was an error, print the info.
}
}
}
</pre><br />
<a name="restore"><h3>Reading Data Files with Java</h3></a><br />
Now we need to know how to get data back from a file with Java. Since the data objects were stored using an ObjectOutputStream, they are saved in a way that makes them easy to read back using an ObjectInputStream.<br />
<br />
There's one problem with ObjectImputStream, however. It doesn't return objects of the specific classes that they were originally. It just returns generic Objects. To get things back into their original class, we have to cast them into that type. Usually that means we need to know what their class was when they were written. It's possible to save class information along with the data, but in this case we just assume that we're reading back a file we have written, so we already know what class everything should be. I'll go into the details of reading other files in another article.<br />
<br />
The steps are practically the same as for writing objects to a file:<br />
<span style="color:#77dd00;"><br />
1. Open a file.<br />
<br />
2. Open an object stream from the file.<br />
<br />
3. Read the objects to that stream.<br />
<br />
4. Close the stream and file.<br />
</span><br />
<b style="color:#ff7700;">1. Opening the File</b><br />
To open a file for <i>reading</i>, we use a FileInputStream object. When we construct the new FileIntputStream, we give it a file name to open. If the file name exists, it opens the existing file. Otherwise, we get an error which will print out a nastygram when we get to our catch statement. To keep things simple, we're not going to check for a file existing here.<br />
<br />
Example:<br />
<span style="color:#00aa00;">FileInputStream saveFile = new FileInputStream("saveFile.sav");</span><br />
<br />
<b style="color:#ff7700;">2. Open an Object Stream</b><br />
To read objects to the FileInputStream, we create an ObjectInputStream. We give it the FileInputStream object we've set up when we construct the new ObjectInputStream.<br />
<br />
Example:<br />
<span style="color:#00aa00;">ObjectInputStream restore = ObjectInputStream(saveFile);</span><br />
<br />
<b style="color:#ff7700;">3. Read Objects</b><br />
When we read objects from the ObjectInputStream, it gets then from the file.<br />
<br />
Example:<br />
<span style="color:#00aa00;">Object obj = restore.readObject();</span><br />
<br />
<b style="color:#ff7700;">3 and a half. Cast Back to Class</b><br />
Step 3. only restores a generic Object. If we know the original class, we should cast the Object back to its original class when we read it. If we had stored a String object, we'd read it something like this:<br />
<span style="color:#00aa00;">String name = (String) restore.readObject();</span><br />
<br />
<b style="color:#ff7700;">4. Close Up</b><br />
When we close the ObjectInputStream, it'll also close our FileInputStream for us, so this is just one step.<br />
<br />
Example:<br />
<span style="color:#00aa00;">restore.close();</span><br />
<br />
Here's an example program to read back information saved by the first example program:<br />
<pre style="color:#0077ee;font-size:9pt;">import java.io.*;
import java.util.ArrayList;
public class RestoreObjects{
public static void main(String[] arg){
// Create the data objects for us to restore.
boolean powerSwitch=false;
int x=0, y=0, z=0;
String name="", setting="", plant="";
ArrayList<string> stuff = new ArrayList<string>();
// Wrap all in a try/catch block to trap I/O errors.
try{
// Open file to read from, named SavedObj.sav.
FileInputStream saveFile = new FileInputStream("SaveObj.sav");
// Create an ObjectInputStream to get objects from save file.
ObjectInputStream save = new ObjectInputStream(saveFile);
// Now we do the restore.
// readObject() returns a generic Object, we cast those back
// into their original class type.
// For primitive types, use the corresponding reference class.
powerSwitch = (Boolean) save.readObject();
x = (Integer) save.readObject();
y = (Integer) save.readObject();
z = (Integer) save.readObject();
name = (String) save.readObject();
setting = (String) save.readObject();
plant = (String) save.readObject();
stuff = (ArrayList<string>) save.readObject();
// Close the file.
save.close(); // This also closes saveFile.
}
catch(Exception exc){
exc.printStackTrace(); // If there was an error, print the info.
}
// Print the values, to see that they've been recovered.
System.out.println("\nRestored Object Values:\n");
System.out.println("\tpowerSwitch: " + powerSwitch);
System.out.println("\tx=" + x + " y=" + y + " z=" + z);
System.out.println("\tname: " + name);
System.out.println("\tsetting: " + setting);
System.out.println("\tplant: " + plant);
System.out.println("\tContents of stuff: ");
System.out.println("\t\t" + stuff);
System.out.println();
// All done.
}
}
</pre><br />
<a href="#save"><<Return to How to Save to a File with Java</a><br />
<br />
The example programs can be downloaded at:<br />
<a href="http://saundby.com/beginwithjava/">Begin With Java Code Downloads</a>saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-464923330778865772011-03-20T16:22:00.000-07:002011-03-20T16:49:18.721-07:00Cleaning Out the Sun ReferencesToday I'm going to start cleaning out the references in old posts to Sun Microsystems. Sun is gone now, except for a page that tells you it's gone and points toward Oracle. Oracle bought Sun, and now owns Java.<br /><br />Many of my old articles point toward the previous Sun website. I'll be changing those to point to current locations for the same resources, mostly to be found on <a href="http://java.net/">java.net</a>.<br /><br />If you come across something I appear to have missed, feel free to email me with the article title so that I can fix it. Thanks!<br /><br /><b style="color:#ff7700;">One More Thing</b><br /><br />It's worth noting that since some of these articles were written, the official online resources have improved. I still think there are some major gotchas for new learners in Java, but things are definitely better than when I started this blog.saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-23474816356571833492011-01-25T11:52:00.000-08:002011-01-25T13:07:04.658-08:00Java's File Names and Class NamesJava is picky about the file names you use.<br /><br />Each source file can contain one public class. The source file's name has to be the name of that class. By convention, the source file uses a <b><tt>.java</tt></b> filename extension (a tail end of a file name that marks the file as being of a particular type of file.)<br /><br />So, for a class declared as such:<br /><pre style="color:#ff0000;"><br />public class HelloWorld{<br />...</pre><br />The file it is stored in should be named <b><tt>HelloWorld.java</tt></b>.<br /><br />The capitalization should be the same in both cases. Some operating systems don't notice whether file names are capitalized or not. It doesn't matter, you should be in the habit of using the correct capitalization in case you work on a system that does care about capitalization.<br /><br />When you compile your file with javac, you pass the full file name to javac:<br /><br /><pre style="color:#00ff00;">javac HelloWorld.java</pre><br />Let's say we save the file under a different name. We write the following program:<br /><br /><pre style="color:#00ffff;">public class HelloThere{<br /> public static void main(String arg[]){<br /> System.out.println("Hello There.");<br /> }<br />}</pre><br />Then we save it as HelloWorld.java, and try to compile it:<br /><pre style="color:#ff0000; font-size: 9pt;"><br />>javac HelloWorld.java<br />FileName.java:1: class HelloThere is public, should be declared <br />in a file named HelloThere.java<br />public class HelloThere{<br /> ^<br />1 error</pre><br /><br />Java lets us know that it won't compile until we rename the file appropriately (according to its rules.)<br /><br />So let's rename the file. Let's call it <b><tt>HelloThere.javasource</tt></b>. Seems a bit more explicit than just <b><tt>.java</b></tt>, right? Let's run the compiler:<br /><br /><pre style="color:#ff0000; font-size: 9pt;"><br />>javac HelloThere.javasource <br />error: Class names, 'HelloThere.javasource', are only accepted <br />if annotation processing is explicitly requested<br />1 error</pre><br />Java's still not happy with us. Annotation processing? That's when we include extra information in the program about the program itself. We're not bothering with that just now. So we should just name the file <b><tt>HelloThere.java</tt></b>, and not get fancy with our file names.<br /><br />But, under the right circumstances, javac <i>does</i> allow file name extensions other than <b><tt>.java</b></tt>. That's why we always type in the full file name, including <b><tt>.java</b></tt>, when we use javac. We say 'javac HelloThere.java', not just 'javac HelloThere'. Javac can't assume that we mean a <b><tt>.java</b></tt> file, though that's what it will usually be.<br /><br /><b style="color:#ffff00;">The Class File</b><br /><br />Once we make javac happy with a proper file name, and a program with no errors, javac produces a new file. This file will have the original file name, but with <b><tt>.java</b></tt> replaced with <b><tt>.class</b></tt>. This is your <i>bytecode</i> file, the file that the Java Virtual Machine can run.<br /><br />When we run the program with Java, we're running the .class file. In the case of HelloThere, we're running the <b><tt>HelloThere.class</b></tt> file. But we don't type in the full file name. Why?<br /><br />Unlike javac, java <i>requires</i> a .class file. That's all it will work with. There's no opportunity to have a different extension to the file name. So it <i>assumes</i> the .class part of the file name. But that's not the whole story.<br /><br />If you add .class yourself, here's what you'll get:<br /><pre style="color:#ff0000; font-size: 9pt;"><br />>java HelloThere.class<br />Exception in thread "main" java.lang.NoClassDefFoundError: <br /> HelloThere/class<br />Caused by: java.lang.ClassNotFoundException: HelloThere.class<br /> at java.net.URLClassLoader$1.run(URLClassLoader.java:202)<br /> at java.security.AccessController.doPrivileged(Native Method)<br /> at java.net.URLClassLoader.findClass(URLClassLoader.java:190)<br /> at java.lang.ClassLoader.loadClass(ClassLoader.java:307)<br /> at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)<br /> at java.lang.ClassLoader.loadClass(ClassLoader.java:248)<br /></pre><br />Pretty ugly. What we're actually doing when we type "<tt>java HelloThere</tt>" is telling Java to run the <i>class</i> <tt>HelloThere</tt>. Java assumes that it will find this in a file called "<tt>HelloThere.class</tt>", so that's what it's looking for first. <br /><br />We're <i>not</i> telling Java to run the <i>file</i> <tt>HelloThere.class</tt>, we're telling it to run the <i>class</i> HelloThere, which it expects to find in the file <tt>HelloThere.class</tt>.<br /><br />But what if we ask for another class that doesn't have its own .class file?<br /><br />Just for fun, let's change HelloThere.java like this, and see what happens:<br /><pre style="color:#00ffff;">public class HelloThere{<br /> public static void main(String[] arg){<br /> System.out.println("Hello.");<br /> }<br />}<br /><br /><span style="color:#ffff00;">class HelloZoik{<br /> public static void main(String[] arg){<br /> System.out.println("Zoiks!");<br /> }<br />}</span></pre><br />After we edit it, we compile with '<tt>javac HelloThere.java</tt>' and hold our breath.<br /><br />Hurray! No errors!<br /><br />Now we have a second class, HelloZoik, in the <tt>HelloThere.class</tt> file. Can Java find it?<br /><br />Let's try:<br /><pre style="color:#00ff00;"> java HelloZoik<br />Zoiks!</pre><br />It worked! Java found our class inside <tt>HelloThere.class</tt>.<br /><br />This shows it's not the file name that we're calling with the 'java' command, it's the class name.<br /><br />If Java doesn't find the class inside a file with the same name as the class followed by .class, it'll look in the other .class files available.saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-86689022425573854612011-01-04T23:13:00.000-08:002011-01-04T23:59:10.067-08:00Should I Still Learn Java?With all the controversy surrounding Java thanks to the purchase of Sun by Oracle, the lawsuits flying back and forth over the Java Community Process, the Apache Foundation, Android, and all the rest, <i style="color:#00FF77;">does it still make sense to learn Java?</i><br /><br />After all, the demise and abandonment of Java is being predicted practically every day.<br /><br />I say <b>Yes</b>, now is the time to learn Java. No matter what your programming skill or background, Java is a valuable language to learn, it will be used and useful for a <i>long</i> time to come.<br /><br /><b style="color:#ff7700;">Never a Dull Moment</b><br /><br />The Java language has been a-swirl in controversy since its public announcement. It has not become "the" language in many of the areas it originally claimed to be "the" language to use, but yet it <i>has</i> become popular in many other areas. In fact, Java is neck and neck with the language C for being the most popular computer language:<br /><br /><a href="http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html">TIOBE Software Community Index</a> (of most popular programming languages.)<br /><br /><a href="http://langpop.com/">langpop.com</a> Programming Language Popularity Rankings.<br /><br /><a href="http://www.devtopics.com/most-popular-programming-languages/">Devtopics.com</a> Most Popular Programming Languages.<br /><br /><b style="color:#ff7700;">Why Popularity Matters</b><br /><br />Why does popularity matter? Because it entrenches a programming language, not just for now, but for many years to come. In fact, every language that has ever become deeply entrenched is still with us, so there's no way of knowing just how long popularity will keep a programming language alive.<br /><br />When I was first learning to program, the big languages were assembly (the "<i>real</i>" programmer's language of the time), BASIC, FORTRAN, and COBOL. Every single one of those is still a viable language today. Though if you'd asked me then, I would never have thought COBOL would still be with us today. I would never have believed how popular it is, either.<br /><br />But COBOL was re-invented in the late 80's. And there were a lot of big-money installations running on it. ADA failed to displace it. It's still here, and it's still a valuable part of a programmer's resume for many jobs.<br /><br />FORTRAN is a language I expected to re-invent itself. It had already done so by the time I learned it (I first programmed in the original FORTRAN, but FORTRAN IV was already in common use.) But with the promulgation of Pascal, Modula-2, and C in the 80's I figured FORTRAN would be pushed into the recesses of obscurity. I was wrong.<br /><br />Modula-2 was mishandled by the company that owned the rights to it, so it never took off as well as it might have. Pascal took off even though it was never intended to be anything but a classroom language. C took off since it didn't have Modula-2's licensing disadvantages and it had enough of its advantages to become the "next generation language" of its day.<br /><br />Modula-2 is still with us, but it's insignificant among languages today. Because it never got popular. The others I mentioned got popular, and they're still popular today. Yeah, even Pascal. You could learn Pascal today and do a lot with it (though I don't recommend it unless you want the academic challenge of broadening yourself as a programmer.) I still write software in Pascal, though mostly for my own use, and only for older computer systems.<br /><br />The key to a programming language's longevity is popularity. Once a language becomes sufficiently popular, for all practical purposes it will never die.<br /><br />Java is that popular.<br /><br /><b style="color:#ff7700;">The Many Javas</b><br /><br />Java has become deeply ingrained into the modern computer infrastructure. Not only does the <a href="http://beginwithjava.blogspot.com/2008/07/java-virtual-machine-adapter-cables-for.html">Java Virtual Machine</a> support a lot more languages than Java itself, but Java has spawned other languages so close to itself that if you know Java you can pick up the other languages without significant effort. C# is the most popular of these spin off languages.<br /><br />Plus, there are different versions of Java. The Mobile Edition, used on cell phones, smart phones, and PDAs, is a major programming language for these platforms. Each of these platforms has its individual programming suite, and associated language. Their second language, the Esperanto of the portable world, is Java. Programmers that want their software to move easily between platforms often choose to write their code in Java.<br /><br />The use of Java on servers is rife as well. Java Enterprise Edition became the most popular use of the Java language when Java was still struggling to be used as an applications programming language over a decade ago. Some say that Java on the server saved the Java language. Certainly this is what makes Java a good language to learn for professional reasons.<br /><br /><br /><b style="color:#ff7700;">The Most Important Reason</b><br /><br />The most important reason to ignore all the hullabaloo about Java's impending demise and not worry about learning it is that:<br /><ul><br /><li>it is a good language that's fairly easy to learn,</li><br /><li>expressive enough to do a lot of different things effectively, </li><br /><li>easy to develop sophisticated modern programs in</li><br /><li>without too much work for an individual or small group of developers,</li><br /><li>gives access to all the important parts of the machine (graphics, sound, filesystem, peripherals)</li><br /><li>and what you learn travels well to other languages when you go on to learn them.</li><br /></ul><br /><br />It's not going to go away any time soon. There's too much momentum. There's no need to worry. Ever since the launch of Java I've heard that it's going to be gone or unusable tomorrow. History shows that just doesn't happen to popular programming languages.<br /><br />If you learn Java now, you may still be using it 20 years from now. Or 30.<br /><br />When I sat down to a card punch to write my first program 38 years ago as I write this, the computer lab know-it-all came to look over my shoulder.<br /><br />"FORTRAN!" he said. "Why are you wasting your time with <i>that</i> language? It's a dead, old language. Did you know it's the <i>oldest</i> computer language? If you really want to be a programmer, you should start right out in BAL*! That's what real programmers use, and you're going to be behind if you waste your time on anything else."<br /><br />FORTRAN doesn't make the "top 10" in programming languages much any more, but it gave me a good start. It's still among the most popular languages, around #20, or just out of the top 10 if you only count general purpose programming languages (that is, not counting scripting languages, query languages, application-specific languages, and so on.)<br /><br />And learning FORTRAN never kept me from learning structured languages, AI languages, Object Oriented languages, and so on. Even though my first program included the "dreaded" GO TO statement.<br /><br />There's never been a better time to learn to program. And there's never been a better time to learn Java (the language is in the best shape it's ever been!)<br /><br />*Basic Assembly Language, a version of assembly language for IBM computers.saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-1456936951648991202010-09-02T09:49:00.000-07:002010-09-16T17:50:02.975-07:00Interactive Keyboard Input In Java: KeyListenersIn a console application, you can get keyboard input using the <a href="http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html">Scanner</a> class, as described in <a href="http://beginwithjava.blogspot.com/2008/07/getting-keyboard-input-for-console-apps.html">Keyboard Input for Console Apps</a>. In an graphical app, though, you can use one of the classes built to accept text input (e.g. <a href="http://download.oracle.com/javase/6/docs/api/java/awt/TextArea.html">TextArea</a> or <a href="http://download.oracle.com/javase/6/docs/api/javax/swing/JTextField.html">JTextField</a>) or add code to your application to respond directly to the keyboard.<br /><br /><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi-I4yrbe1a5eWiaZaZXMnueD6nBStUGUp3urqH_X3QzhFY0C1XKYn23xm8BhVI8sBwzsX3WthOA5On7n8EGxyCCCfVO3bQDMLt_WsNVb_EbZdre8qenVOHKFPHA8nDxja5cndUWLn4jQc/" width="480" height="320" style="display: block; margin-left: auto; margin-right: auto; " alt="Keyboard input in the Java GUI made simple." /><h5 align="center">Playing with Today's Program</h5><br />There are two basic ways of doing this. One is to set up <a href="http://download.oracle.com/javase/tutorial/uiswing/misc/keybinding.html">Key Bindings</a>, which maps keystrokes to actions in your application similar to accelerator keys or menu keyboard equivalents. The other is to use a <a href="http://download.oracle.com/javase/tutorial/uiswing/events/keylistener.html">Key Listener</a>, similar to the <a href="http://download.oracle.com/javase/tutorial/uiswing/events/mouselistener.html">Mouse Listener</a>, which I detailed in <a href="http://beginwithjava.blogspot.com/2008/08/simple-mouse-interaction-in-java.html">Simple Mouse Interaction</a>.<br /><br />In this example we're going to use Key Listeners. There is less overhead to setting up a KeyListener when you just need to use a few keys. Key Bindings require more overhead to set up, but when you want to bind actions to a lot of different keystrokes, and manage the actions bound to particular keystrokes at a higher level, Key Bindings are better to use than a simple KeyListener.<br /><br />As its name implies, a KeyListener is an <a href="http://download.oracle.com/javase/tutorial/uiswing/events/intro.html">Event Listener</a>. If you're not sure what that is, read my <a href="http://beginwithjava.blogspot.com/2009/01/listeners-can-java-hear-you.html">article on Listeners</a> or follow the prior link to Oracle/Sun's description.<br /><br />Here's a program that demonstrates simple keyboard interaction. It's based on the <a href="http://saundby.com/beginwithjava/code/MousePanel.java">MousePanel</a> program I presented in <a href="http://beginwithjava.blogspot.com/2008/08/simple-mouse-interaction-in-java.html">Simple Mouse Interaction</a>. It acts as a sort of "Etch-a-Sketch". You can <a href="http://saundby.com/beginwithjava/code/KeyPanel.java">download the KeyPanel program source</a> from my <a href="http://saundby.com/beginwithjava/">Java code site</a>.<br /><br /><pre style="font-family: sans; color:#ff7700; font-size:90%;">// Import the basic necessary classes.<br />import java.awt.*;<br />import java.awt.event.*;<br />import javax.swing.*;<br /><br />public class KeyPanel extends JPanel implements KeyListener{<br /><br /> public KeyPanel(){<br /> super();<br /> pointX=0;<br /> pointY=0;<br /> oldX=0;<br /> oldY=0;<br /> addKeyListener(this);<br /> }<br /><br /> int pointX, pointY, oldX, oldY;<br /> boolean erase;<br /><br /> public void paintComponent(Graphics g){<br /> // Erase the board if it's been requested.<br /> if (erase) {<br /> g.clearRect(0, 0 , getBounds().width, getBounds().height);<br /> erase = false; // We're done, turn off this flag now.<br /> }<br /><br /> // Draw gray where the pointer was..<br /> g.setColor(Color.GRAY); <br /> g.fillRect(oldX-2, oldY-2, 4, 4);<br /> // Draw "Cursor" at current location in black.<br /> g.setColor(Color.BLACK);<br /> g.fillRect(pointX-2,pointY-2, 4, 4);<br /> }<br /><br /> public void keyPressed(KeyEvent key){<br /><br /> // Copy the last clicked location into the 'old' variables.<br /> oldX=pointX;<br /> oldY=pointY;<br /> // Move the current point depending on which key was pressed.<br /> if (key.getKeyCode() == key.VK_DOWN){<br /> pointY=pointY+5;<br /> if (pointY > getBounds().height){<br /> pointY=getBounds().height;<br /> }<br /> }<br /> if (key.getKeyCode() == key.VK_UP){<br /> pointY=pointY-5;<br /> if (pointY < 0){pointY=0;}<br /> }<br /> if (key.getKeyCode() == key.VK_LEFT){<br /> pointX=pointX-5;<br /> if (pointX < 0){pointX=0;}<br /> }<br /> if (key.getKeyCode() == key.VK_RIGHT){<br /> pointX=pointX+5;<br /> if (pointX > getBounds().width){<br /> pointX=getBounds().width;<br /> }<br /> }<br /><br /> <span style="color:#dddd00;">// Set a flag to erase the screen if Space is pressed.<br /> if (key.getKeyCode() == key.VK_SPACE){<br /> erase = true;<br /> }</span><br /><br /> // Tell the panel that we need to redraw things.<br /> repaint();<br /> }<br /><br />/* The following methods have to be here to comply<br /> with the MouseListener interface, but we don't<br /> use them, so their code blocks are empty. */<br /> public void keyTyped(KeyEvent key){ } <br /> public void keyReleased(KeyEvent key){ }<br /><br /> public static void main(String arg[]){<br /> JFrame frame = new JFrame("Use Arrows to Draw, Space to Erase.");<br /> frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);<br /> frame.setSize(640,480);<br /><br /> KeyPanel panel = new KeyPanel();<br /> frame.setContentPane(panel);<br /> frame.setVisible(true);<br /><br /> <span style="color:#dddd00;">// We *must* do this to see KeyEvents.<br /> panel.setFocusable(true);</span><br /><br /> // Initialize the drawing pointer.<br /> panel.oldX=panel.getBounds().width/2;<br /> panel.oldY=panel.getBounds().height/2;<br /> panel.pointX=panel.oldX;<br /> panel.pointY=panel.oldY;<br /><br /> }<br />}</pre><br />Using this technique with the <a href="http://beginwithjava.blogspot.com/2010/08/simple-java-video-game-kernel.html">Simple Video Game Kernel</a> would be similar. The VGKernel would extend KeyListener, register itself, and implement the KeyListener methods. But in those methods, rather than performing the operations that result from the keypress, as in this program, you would want to simply set a flag to show that the key has been pressed. Then, in your core game logic you would test to see whether the key has been pressed, and perform the appropriate actions.<br /><br />That way the actions are performed at the appropriate time in your game, and not just whenever the key happens to get pressed. Reacting to a key when it is pressed is appropriate for a turn-based game, but not for a real-time game. In a real-time game the action happens according to the timing of the TimerTask that drives the game, which is why we just note that a key has been pressed, and wait until the TimerTask occurs to actually conduct the action related to that key. This would be similar to what we do with the space key here, which sets a flag to tell paintComponent() to erase the screen.<br /><br />Give this program a try, see if you can extend it to allow the user to select colors to draw with or change the size of the drawing pen.saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-16961981980461868532010-08-26T12:12:00.000-07:002010-08-26T23:26:57.835-07:00Calling System Commands in JavaLet's suppose you want to run another program on your system from within Java. Personally, I first decided I wanted to do this for the sake of a prank. You may have more businesslike purposes in mind, yourself.<br /><br />It's not too hard to do this since Java 1.5, which added the <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Process.html">Process</a> and <a href="http://download.oracle.com/javase/6/docs/api/java/lang/ProcessBuilder.html">ProcessBuilder</a> classes.<br /><br />Here's an example program that starts up Firefox at a particular website:<br /><pre style="color:#ff7700;">public class OpenSite{<br /> public static void main(String arg[]){<br /> try { Process p = new ProcessBuilder("firefox", <br /> "http://beginwithjava.blogspot.com/").start(); }<br /> catch(java.io.IOException io){ }<br /> }<br />}</pre><br />I've compressed the various parts of the action down to one line here:<br /><pre style="color:#ff7700;">Process p = new ProcessBuilder("firefox", "http://beginwithjava.blogspot.com/").start();</pre><br />I'm creating an "anonymous" ProcessBuilder object, calling its start() method, which returns a Process, which I name simply "p".<br /><br />The whole thing is wrapped up in a try...catch structure because javac wants to see us deal with any I/O errors that result. In this program, I just ignore them.<br /><br />So you'll want to make sure that you either catch those errors and deal with them, or that they will be unimportant enough that they don't matter.<br /><br />Also note that the Java program's process will last as long as the external program you call. So if you don't shut down this instance of the firefox process, you'll have Java still running.<br /><br />If you want to see something fun you can do with this on Mac, check out my article on <a href="http://catsonkeyboards.blogspot.com/">my other blog</a> about <a href="http://catsonkeyboards.blogspot.com/2010/08/making-mac-speak-in-java.html">adding speech</a> to the <a href="http://beginwithjava.blogspot.com/2010/08/simple-java-video-game-kernel.html">Simple Video Game Kernel</a>.saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.comtag:blogger.com,1999:blog-2862144722617194417.post-75881402781374788142010-08-24T18:23:00.000-07:002010-08-24T18:37:25.481-07:00Using Game Controllers with JavaIn the past, I've covered using <a href="http://beginwithjava.blogspot.com/2008/08/simple-mouse-interaction-in-java.html">mice</a> as input devices, and covered the general input mechanism of <a href="http://beginwithjava.blogspot.com/2009/01/listeners-can-java-hear-you.html">Listeners</a>. I've also discussed <a href="http://beginwithjava.blogspot.com/2008/07/getting-keyboard-input-for-console-apps.html">keyboard</a> input for console applications, and I'll soon be covering <a href="http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html">Key Bindings</a> as a way of using the keyboard in GUI applications.<br /><br />But there's no facility in Java itself that deals with game pads easily. To date, it's been necessary to create your own ActionListeners from scratch. But not any more. Thanks to the <a href="https://jinput.dev.java.net/">JInput</a> project, there's an easier way to hook up game controllers to your software.<br /><br />JInput attempts to do discovery on your game controller, to figure out what its setting are, what buttons and controls it has, what the center positions are of analog sticks, and so on. All that messy stuff that makes rolling your own so darn painful. It's not 100% universal, but for most controllers and most games, it will do the job admirably. If you want better for a specific controller of your own, you can extend the classes to handle your stick (and maybe feed that information back to the JInput team so that they can decide whether to include it in future releases.<br /><br />It's multi-platform, Windows, Mac OS X, and Linux. So it doesn't have the limitations of a lot of the other gamepad code implementations that use native code, thus limiting themselves to one platform (usually Windows.)<br /><br />If you want to see an implementation using JInput, check out <a href="http://www.greenfoot.org/doc/gamepad/">Greenfoot with Gamepads</a>. It's a good, clear example of using JInput in a general fashion.saundbyhttp://www.blogger.com/profile/05472603072142005189noreply@blogger.com