You 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?
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.
C# (C Sharp)
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.
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.
C
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.
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.
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.
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.
C++
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.
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.
Python
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.
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.
Javascript
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.
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.
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.
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.
Objective-C
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.
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.
Swift
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.
PHP
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.
You will need to learn the specifics of PHP's syntax and data structures, but after mastering Java, you will not find this difficult.
Summary
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.
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.
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.
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.
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.
Mobile
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.
Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts
Monday, November 17, 2014
Portability of Java Programming Skills
Labels:
Android,
API,
application,
C,
C#,
C++,
cross-platform,
environment,
graphics,
IDE,
Java,
Javascript,
PHP,
Swift,
web,
why java
Tuesday, November 12, 2013
DozCalc: A More Polished Android Application in Java
Since my post on my first Android app, 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.
Specifically, I have posted an app for Android called DozCalc.
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.
Java
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.
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.
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.
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.
Specifically, I have posted an app for Android called DozCalc.
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.
Java
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.
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.
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.
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.
Labels:
Android,
API,
application,
calculations,
Java,
JVM,
operators,
why java
Sunday, January 13, 2013
My First Android App
I ordered an Android phone about two weeks ago.
Last Thursday, I installed the Android SDK. 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.)
I started the online tutorials linked on the SDK's opening page. Since the SDK is based on Eclipse (my favorite full-fat IDE for Java), it was no problem getting started.
I got a simple app, modified from the 'getting started' tutorial, running on an emulated Android device within an hour or so of starting.
The next day--Friday, my phone arrived in the mail. It runs Android 4.1.1.
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, RoonVenture.) It ran just fine. It's very similar to my online RoonVenture Character Generator.
That is, it's ugly, poorly designed, but bone-simple while producing the essential results.
Nevertheless, I found my Java skills played right into Android development (so far):
Android's native language is Java, with some unique libraries.
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.)
It's a lot like Java ME development (which I've done to build apps for my older "feature phones".)
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.
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.
That should help me make a better app next. :)
Last Thursday, I installed the Android SDK. 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.)
I started the online tutorials linked on the SDK's opening page. Since the SDK is based on Eclipse (my favorite full-fat IDE for Java), it was no problem getting started.
I got a simple app, modified from the 'getting started' tutorial, running on an emulated Android device within an hour or so of starting.
The next day--Friday, my phone arrived in the mail. It runs Android 4.1.1.
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, RoonVenture.) It ran just fine. It's very similar to my online RoonVenture Character Generator.
That is, it's ugly, poorly designed, but bone-simple while producing the essential results.
Nevertheless, I found my Java skills played right into Android development (so far):
Android's native language is Java, with some unique libraries.
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.)
It's a lot like Java ME development (which I've done to build apps for my older "feature phones".)
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.
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.
That should help me make a better app next. :)
Wednesday, November 28, 2012
Dino Programmers Need Not Fear Java
While 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.
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.)
Tools Getting in the Way of the Work
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.
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.
Welcome, Fellow Dinos!
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 vi and make with cc and a system-appropriate linker behind it.
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.
It's like embroidery or quilting for aging nerds, I guess.
Java for Dinos
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.)
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), cd to the directory where you saved the file, and compile it with:
javac filename.java
Replace filename with your file's name, of course.
At this stage you need to include the .java file extension. It will produce a new file with the same name but a .class extension is on it now.
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:
java filename
Note that even though you're running a .class 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:
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.
Why Bother?
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.
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.
Come In and Look Around
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.
To do this, I often strip away code that would be good 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 my Java code repository for this blog (also on the right side of every article here.)
If my articles are of use to you, or you think I can improve things, drop me an email.
Thanks.
*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.
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.)
Tools Getting in the Way of the Work
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.
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.
Welcome, Fellow Dinos!
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 vi and make with cc and a system-appropriate linker behind it.
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.
It's like embroidery or quilting for aging nerds, I guess.
Java for Dinos
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.)
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), cd to the directory where you saved the file, and compile it with:
javac filename.java
Replace filename with your file's name, of course.
At this stage you need to include the .java file extension. It will produce a new file with the same name but a .class extension is on it now.
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:
java filename
Note that even though you're running a .class 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:
>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)
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.
Why Bother?
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.
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.
Come In and Look Around
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.
To do this, I often strip away code that would be good 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 my Java code repository for this blog (also on the right side of every article here.)
If my articles are of use to you, or you think I can improve things, drop me an email.
Thanks.
*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.
Labels:
beginner,
command line,
environment,
Java
Wednesday, June 27, 2012
Java's Assignment Operators
An assignment operator is a way of putting a new value into a variable.
I covered these briefly in Doing Math in Java, Part 1. Now I'll go into a bit more detail.
The Simple Assignment Operator
The simple assignment operator is =.
It places the value from the expression on its right side into the variable on its left.
This is covered in detail in Left Becomes Right.
Also see the Java Language Specification: The Simple Assignment Operator.
The Compound Assignment Operators
The compound assignment operators are:
+=, "plus-equals",
-=, "minus-equals",
*=, "times-equals" or "star-equals",
/=, "divided by-equals" or "slash-equals",
%=, "remainder-equals" or "percent-equals",
&=, "and-equals",
|=, "or-equals",
^=, "exor-equals" or "caret-equals",
>>=, "signed-shift-right-equals",
<<=, "shift-left-equals",
>>>=, "unsigned-shift-right-equals".
Commonality
Each of these operators has a variable to assign a value to before it, and an expression that results in a value after it:
variable operator expression
The expression has to result in a value that is compatible with variable's type.
Java will calculate the value of expression,
perform the calculation variable optype expression, where optype is the assignment operator without the equals sign.
Then it will place the result of that calculation into variable.
+=, "Plus-Equals"
Plus-equals adds the value after += to the original value of the variable, then puts the result into the variable.
-=, "Minus-Equals"
This subtracts the value after the operator from the original value in the variable, then stores the result in the variable.
*=, "Times-Equals"
Multiply the variable by the value on the right of the operator, put the result in variable.
/=, "Divided by-Equals"
Same as the above, but for division.
%=, "Remainder-Equals"
This finds the remainder of the variable's initial value divided by the value after the operator. That remainder is then put into the variable.
See Java's Modulo Operator--Wrapping Around for more information on how the remainder (or modulo) operator % works.
&=, "And-Equals"
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.
|=, "Or-Equals"
Or-equals does a bit-wise OR of the variable and the value after the operator. The result is placed in the variable.
^=, "Exor-Equals"
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.
>>=, "Signed-Shift-Right-Equals"
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.
<<=, "Shift-Left-Equals"
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 expression times.
>>>=, "Unsigned-Shift-Right-Equals"
This one moves all the bits, unlike the signed shifts which leave the sign bit (highest order bit) alone.
Not Quite the Whole Story
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".
Additional Information
See the Java Language Specification: Compound Assignment Operators, Multiplicative Operators, Additive Operators, Bit-wise and Logical Operators.
I covered these briefly in Doing Math in Java, Part 1. Now I'll go into a bit more detail.
The Simple Assignment Operator
The simple assignment operator is =.
It places the value from the expression on its right side into the variable on its left.
This is covered in detail in Left Becomes Right.
Also see the Java Language Specification: The Simple Assignment Operator.
The Compound Assignment Operators
The compound assignment operators are:
+=, "plus-equals",
-=, "minus-equals",
*=, "times-equals" or "star-equals",
/=, "divided by-equals" or "slash-equals",
%=, "remainder-equals" or "percent-equals",
&=, "and-equals",
|=, "or-equals",
^=, "exor-equals" or "caret-equals",
>>=, "signed-shift-right-equals",
<<=, "shift-left-equals",
>>>=, "unsigned-shift-right-equals".
Commonality
Each of these operators has a variable to assign a value to before it, and an expression that results in a value after it:
variable operator expression
The expression has to result in a value that is compatible with variable's type.
Java will calculate the value of expression,
perform the calculation variable optype expression, where optype is the assignment operator without the equals sign.
Then it will place the result of that calculation into variable.
+=, "Plus-Equals"
Plus-equals adds the value after += to the original value of the variable, then puts the result into the variable.
-=, "Minus-Equals"
This subtracts the value after the operator from the original value in the variable, then stores the result in the variable.
*=, "Times-Equals"
Multiply the variable by the value on the right of the operator, put the result in variable.
/=, "Divided by-Equals"
Same as the above, but for division.
%=, "Remainder-Equals"
This finds the remainder of the variable's initial value divided by the value after the operator. That remainder is then put into the variable.
See Java's Modulo Operator--Wrapping Around for more information on how the remainder (or modulo) operator % works.
&=, "And-Equals"
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.
|=, "Or-Equals"
Or-equals does a bit-wise OR of the variable and the value after the operator. The result is placed in the variable.
^=, "Exor-Equals"
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.
>>=, "Signed-Shift-Right-Equals"
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.
<<=, "Shift-Left-Equals"
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 expression times.
>>>=, "Unsigned-Shift-Right-Equals"
This one moves all the bits, unlike the signed shifts which leave the sign bit (highest order bit) alone.
Not Quite the Whole Story
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".
Additional Information
See the Java Language Specification: Compound Assignment Operators, Multiplicative Operators, Additive Operators, Bit-wise and Logical Operators.
Labels:
assignment,
beginner,
calculations,
equals,
expressions,
Java,
numeric,
operators,
percent sign,
type,
variables
Monday, May 14, 2012
Java's Modulo Function--Wrapping Around
I've previously discussed operators in Java, where I gave a brief introduction to the modulo operator, %.
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.
What's Left Over
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.
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.
limitedNumber = someNumber % 100
limitedNumber will never be higher than 99.
Real World Analogies
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.
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.
Computer Applications
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 xLoc (short for x location):
Class Asteroid{
int xLoc, yLoc, xSpeed, ySpeed, size;
.
.
.
}
We'll assume the class has all the methods it needs to do what Asteroids do. Our instance is:
Asteroid asteroid = new Asteroid();
(If this is unfamiliar to you, you may want to read Creating a Java Variable, Two Steps.)
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.
We can move our asteroid from left to right as follows:
xLoc = xLoc + xSpeed;
Where xSpeed is how fast we're moving across the screen.
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?
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:
xLoc = xLoc + xSpeed;
xLoc = xLoc % 800; // Hard-coded screen width, for now.
That will make xLoc always be from 0 (when there is a zero remainder) to 799 (the highest possible remainder when dividing by 800.)
We might have a method in Asteroid like the following:
public int moveHoriz(int howFar){
// Moves the Asteroid horizontally by howFar pixels on an 800 pixel wide screen.
// returns the new pixel location.
return (xLoc + howFar) % 800;
}
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.
An Expanded Example
Here's a more developed example that deals with speeds higher than the screen width, and wraps both ways:
public int moveHoriz(int howFar){
// Moves the Asteroid horizontally by howFar pixels on a screen.
// It returns the new horizontal pixel location.
// We have a screen width available to us in member variable xWidth,
// and our x location in xLoc.
// Wraps from right to left, or left to right.
//Use modulo to trim speed if it's too high.
if (howFar > xWidth) howFar %= xWidth;
// Calculate the new x location and return it.
return (xLoc + howFar + xWidth) % xWidth;
}
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.
What's Left Over
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.
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.
limitedNumber = someNumber % 100
limitedNumber will never be higher than 99.
Real World Analogies
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.
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.
Computer Applications
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 xLoc (short for x location):
Class Asteroid{
int xLoc, yLoc, xSpeed, ySpeed, size;
.
.
.
}
We'll assume the class has all the methods it needs to do what Asteroids do. Our instance is:
Asteroid asteroid = new Asteroid();
(If this is unfamiliar to you, you may want to read Creating a Java Variable, Two Steps.)
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.
We can move our asteroid from left to right as follows:
xLoc = xLoc + xSpeed;
Where xSpeed is how fast we're moving across the screen.
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?
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:
xLoc = xLoc + xSpeed;
xLoc = xLoc % 800; // Hard-coded screen width, for now.
That will make xLoc always be from 0 (when there is a zero remainder) to 799 (the highest possible remainder when dividing by 800.)
We might have a method in Asteroid like the following:
public int moveHoriz(int howFar){
// Moves the Asteroid horizontally by howFar pixels on an 800 pixel wide screen.
// returns the new pixel location.
return (xLoc + howFar) % 800;
}
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.
An Expanded Example
Here's a more developed example that deals with speeds higher than the screen width, and wraps both ways:
public int moveHoriz(int howFar){
// Moves the Asteroid horizontally by howFar pixels on a screen.
// It returns the new horizontal pixel location.
// We have a screen width available to us in member variable xWidth,
// and our x location in xLoc.
// Wraps from right to left, or left to right.
//Use modulo to trim speed if it's too high.
if (howFar > xWidth) howFar %= xWidth;
// Calculate the new x location and return it.
return (xLoc + howFar + xWidth) % xWidth;
}
Radio Dial image by John McComb.
Labels:
assignment,
beginner,
calculations,
comparison,
Java,
modulo,
percent sign,
variables,
video game
Wednesday, March 21, 2012
Java Introspection and Using Collections without Generics
In my prior article on Generics we looked at how to use Generics to associate at type with data stored in a Collection.
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.
But, once you pull that data back out of the Collection, how do you find out what it was?
Fortunately, the object itself has that information stored with it.
There are two easy ways to find out what it is. instanceof can test if it is a specific type of Object:
You can also have an Object tell you its type:
or
A look at the documentation for Object and Class gives all sorts of useful methods for dealing with classes of data objects in Java.
Here's some sample code:
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.
But, once you pull that data back out of the Collection, how do you find out what it was?
Fortunately, the object itself has that information stored with it.
There are two easy ways to find out what it is. instanceof can test if it is a specific type of Object:
if (anObject instanceof String) { aString = (String)anObject); }
You can also have an Object tell you its type:
Class myClass = anObject.getClass();
or
String myClassName = anObject.getClass().getName();
A look at the documentation for Object and Class gives all sorts of useful methods for dealing with classes of data objects in Java.
Here's some sample code:
import java.util.*;
public class NoGenerics2{
// This is an example of using introspection
// to determine types of Objects stored in a
// Collection without a Generic declaration.
public static void main(String[] arg){
ArrayList myList = new ArrayList(); // No Genericdeclaration.
String myString="Boss Moss";
String yourString="Snorkledorf";
// put the strings into the List
myList.add(myString);
myList.add(yourString);
for (Object anObject: myList){
System.out.println(anObject.getClass().getName());
if (anObject instanceof String){
String aString = (String)anObject;
}
else{
System.out.println("Not a String, Sheriff!");
}
}
}
}
Labels:
collection,
comparison,
generics,
Java,
List,
objects,
type,
variables
Wednesday, March 7, 2012
Generics in Java
Generics 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:
What happens here to upset javac 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.
The Fix for Lost Types
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 added:
Generics = Typed Collections
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.
import java.util.*;
public class NoGenerics{
// This is an example of what happens
// when you don't declare a class
// for a Collection using Generics.
// It won't compile!
public static void main(String[] arg){
// No Genericdeclaration.
ArrayList myList = new ArrayList();
String myString="Boss Moss";
String yourString="Snorkledorf";
// put the strings into the ArrayList
myList.add(myString);
myList.add(yourString);
for (String aString: myList){
// We can't do String methods on the items from myList.
if (aString.startsWith("Boss")){
System.out.println(aString + ":");
System.out.println("Make sure you spell it right!");
}
else{
System.out.println(aString + ":");
System.out.println("I am so pretty!");
}
}
}
}
What happens here to upset javac 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.
Feel free to take the above code and try to compile it to see the error you'll get. It is instructive.
The Fix for Lost Types
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
import java.util.*;
public class Generics{
// This is an example of what happens
// when you declare a data class
// for a Collection using Generics.
public static void main(String[] arg){
// Genericdeclaration.
ArrayListmyList = new ArrayList ();
String myString="Boss Moss";
String yourString="Snorkledorf";
// put the strings into the ArrayList
myList.add(myString);
myList.add(yourString);
for (String aString: myList){
// Now when we can do String methods on the List items.
if (aString.startsWith("Boss")){
System.out.println(aString + ":");
System.out.println("Make sure you spell it right!");
}
else{
System.out.println(aString + ":");
System.out.println("I am so pretty!");
}
}
}
}
Generics = Typed Collections
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.
Labels:
collection,
declaration,
generics,
Java,
objects,
type,
variables
Monday, January 23, 2012
Java under Mac OS X 10.7 Lion
Lion is the first version of Mac OS X that doesn't come with Java already installed. Earlier versions not only had the Java Virtual Machine or runtime element installed, but they also had the JDK installed, which is the part that lets you write your own Java programs.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Labels:
beginner,
command line,
environment,
Java,
Java version,
JDK,
JVM,
why java
Friday, January 6, 2012
Embedded Java
Embedded 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.
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.
NanoVM 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.
The JStamp 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.
Also, IS2T 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.
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.
It's all just a bunch of ones and zeroes in the end.
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.
NanoVM 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.
The JStamp 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.
Also, IS2T 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.
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.
It's all just a bunch of ones and zeroes in the end.
Labels:
embedded,
environment,
IDE,
Java,
JVM,
source code,
virtual machine,
why java
Thursday, October 20, 2011
Mobile Java
One 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.
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 Java SE applications. Java SE is "Java, Standard Edition", the version that typically runs on a desktop or laptop computer.
Java ME 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.
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.
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 Nokia 3650, 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.
My next phone was a step up the Java ladder. It was a Sciphone G2, 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.
My current phone is a Blackberry Curve 8900. 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.
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 Eclipse, a great Java integrated development environment. The version linked above is a version specific to Java ME.
Now I'm back to having a development environment 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.
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?
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.
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.
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.
Java ME applets are easy to translate, though I write almost all of my Java software as applications now.
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 Java SE applications. Java SE is "Java, Standard Edition", the version that typically runs on a desktop or laptop computer.
Java ME 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.
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.
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 Nokia 3650, 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.
My next phone was a step up the Java ladder. It was a Sciphone G2, 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.
My current phone is a Blackberry Curve 8900. 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.
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 Eclipse, a great Java integrated development environment. The version linked above is a version specific to Java ME.
Now I'm back to having a development environment 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.
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?
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.
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.
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.
Java ME applets are easy to translate, though I write almost all of my Java software as applications now.
Labels:
applet,
application,
beginner,
environment,
Java,
Java version,
JVM,
source code,
video game,
why java
Monday, September 5, 2011
Numeric Literal Values
Java 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.
Let's Get Literal
What is a "literal"? A literal is an explicit value. For example, in this line:
int number=123;
the value 123 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.
A hexadecimal literal looks like this:
int number=0x007b;
The value 0x007b is a hexadecimal (base 16) number that is expressed literally (stated explicitly.) The 0x 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.
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.
To tell Java you're using an octal value, place a leading zero in front of the number itself:
int number=0173;
Here the number 0173 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:
int number=0123;
The value of the number will be interpreted as eighty-three, not one hundred twenty-three. So watch out for that.
New for Java 7--Binary Literals
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.
But now it's finally here.
So you can define values as individual bits, like this:
int number=0b01111011;
That's the binary for one hundred twenty-three, by the way. Why is this important?
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.
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:
byte stick_up=0b00001;
In this case, we show it setting the lowest order bit. We might have another like this:
byte fire_switch=0b100000;
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.
Let's Get Literal
What is a "literal"? A literal is an explicit value. For example, in this line:
int number=123;
the value 123 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.
A hexadecimal literal looks like this:
int number=0x007b;
The value 0x007b is a hexadecimal (base 16) number that is expressed literally (stated explicitly.) The 0x 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.
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.
To tell Java you're using an octal value, place a leading zero in front of the number itself:
int number=0173;
Here the number 0173 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:
int number=0123;
The value of the number will be interpreted as eighty-three, not one hundred twenty-three. So watch out for that.
New for Java 7--Binary Literals
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.
But now it's finally here.
So you can define values as individual bits, like this:
int number=0b01111011;
That's the binary for one hundred twenty-three, by the way. Why is this important?
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.
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:
byte stick_up=0b00001;
In this case, we show it setting the lowest order bit. We might have another like this:
byte fire_switch=0b100000;
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.
Labels:
initializer,
Java,
Java version,
literal,
numeric
Friday, June 24, 2011
Java Variable Value Assignment: Left Equals Right, Left Becomes Right
One 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.
Take a look at these statements:
The first two are fine (assuming that 7 is a valid value for whatever type of variable j is), but the last two are wrong.
Remember All That Algebra We Taught You? Well, We Broke It.
After you've gone to all the trouble to learn how to deal with things like 7+count=c and b+14=a+9 in algebra class, now we take what you know and turn it on its ear in programming class. Sweet, eh?
The problem is that the = we use in programming has pretty much nothing to do with the = that you use in math. It's just close enough to be confusing. In Java, the equals sign is an assignment operator, not an indicator of equality between values as it is in math. There is a comparison operator for equality in Java, it's ==, and we'll talk about it shortly. First, let's talk assignment.
Assignment
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.
With Java, we can store all kinds of values, not just numbers. We can store sections of text, called strings in a String 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.
But we're here to just look at assignment today, not the wide variety of things we can assign as values.
To store a value on a calculator, you use some key sequence like M+ or STO 00 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:
count = a;
"count equals a"
This means we take the value of a and place it in count. But a better way to read that equals sign is to use the word "becomes" instead of "equals":
count = 9;
"count becomes nine"
This makes it more obvious that we're putting in a new value that changes the value of count. 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 count= a; is taking the value in variable a and copying it into count. If we then print the value in count, it will be the same as whatever is in a at that time.
We can also compute a value to put into our variable.
count = a + 1;
"count becomes a plus one"
This makes the value in count be one more than the current value of a.
What we can't do is change sides around the equals sign. In algebra, c = a + 1 is the same as a + 1 = c. But in Java that doesn't work:
a + 1 = count
This is wrong in Java. Does not compute. Norman, Norman, help me Norman!
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.
Comparisons
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.
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:
State whether each of the following is true or false.
1. 11 = 6 + 5
2. 14 = 3 x 7
3 65 - 14 = 17 x 3
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?
The == Operator
In some languages, = does both jobs. But in Java, there's a second operator for doing equality comparisons, ==, "equals equals". When we want to see if two values are the same, we compare them using a statement something like this:
if (count == 100) then stop();
This compares count to the value 100, and executes the method stop() if the result of the comparison is true.
The Dangers of the = Operator
Something to look out for is using = by accident in such a situation. Like this:
if (count = 100) then stop();
Don't do this if you want to compare count to 100!
What this does is assign the value 100 to count. If the assignment is successful (which it almost certainly will be, if the program compiles), the program will then do stop() every time it hits this statement! Because the assignment was successful, so the result is considered to be true.
Summary
The equals sign makes the variable on the left equal the computed value from the right side of the equals sign:
name = "Mergatroyd";
"name becomes Mergatroyd"
It doesn't work the other way around (putting something from the left into the variable on the right.)
If you want to compare to values to see if they're equal, use "equals equals":
if (state == "done") then exit();
"if state equals equals done then exit" or
"if state is equal to done then exit"
Take a look at these statements:
int i = 1;
j=7;
7+count=c;
b+14=a+9;
The first two are fine (assuming that 7 is a valid value for whatever type of variable j is), but the last two are wrong.
Remember All That Algebra We Taught You? Well, We Broke It.
After you've gone to all the trouble to learn how to deal with things like 7+count=c and b+14=a+9 in algebra class, now we take what you know and turn it on its ear in programming class. Sweet, eh?
The problem is that the = we use in programming has pretty much nothing to do with the = that you use in math. It's just close enough to be confusing. In Java, the equals sign is an assignment operator, not an indicator of equality between values as it is in math. There is a comparison operator for equality in Java, it's ==, and we'll talk about it shortly. First, let's talk assignment.
Assignment
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.
With Java, we can store all kinds of values, not just numbers. We can store sections of text, called strings in a String 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.
But we're here to just look at assignment today, not the wide variety of things we can assign as values.
To store a value on a calculator, you use some key sequence like M+ or STO 00 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:
count = a;
"count equals a"
This means we take the value of a and place it in count. But a better way to read that equals sign is to use the word "becomes" instead of "equals":
count = 9;
"count becomes nine"
This makes it more obvious that we're putting in a new value that changes the value of count. 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 count= a; is taking the value in variable a and copying it into count. If we then print the value in count, it will be the same as whatever is in a at that time.
We can also compute a value to put into our variable.
count = a + 1;
"count becomes a plus one"
This makes the value in count be one more than the current value of a.
What we can't do is change sides around the equals sign. In algebra, c = a + 1 is the same as a + 1 = c. But in Java that doesn't work:
a + 1 = count
This is wrong in Java. Does not compute. Norman, Norman, help me Norman!
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.
Comparisons
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.
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:
State whether each of the following is true or false.
1. 11 = 6 + 5
2. 14 = 3 x 7
3 65 - 14 = 17 x 3
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?
The == Operator
In some languages, = does both jobs. But in Java, there's a second operator for doing equality comparisons, ==, "equals equals". When we want to see if two values are the same, we compare them using a statement something like this:
if (count == 100) then stop();
This compares count to the value 100, and executes the method stop() if the result of the comparison is true.
The Dangers of the = Operator
Something to look out for is using = by accident in such a situation. Like this:
if (count = 100) then stop();
Don't do this if you want to compare count to 100!
What this does is assign the value 100 to count. If the assignment is successful (which it almost certainly will be, if the program compiles), the program will then do stop() every time it hits this statement! Because the assignment was successful, so the result is considered to be true.
Summary
The equals sign makes the variable on the left equal the computed value from the right side of the equals sign:
name = "Mergatroyd";
"name becomes Mergatroyd"
It doesn't work the other way around (putting something from the left into the variable on the right.)
If you want to compare to values to see if they're equal, use "equals equals":
if (state == "done") then exit();
"if state equals equals done then exit" or
"if state is equal to done then exit"
Labels:
assignment,
comparison,
equals,
Java,
operators,
type,
variables
Tuesday, June 7, 2011
Doing Math in Java part 2:Functions
The basics of math in Java using operators was covered in Part 1: Operators. There I went over the standard operations built into the language itself, rather than in its APIs (libraries).
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.
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.)
What you really want is the java.lang.Math class, in the java.lang package.
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:
These call the square root function
Date Calculations
Calculations with dates are another standard sort of math that's not covered by standard operators. In the package java.util we've got the Calendar class. 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 GregorianCalendar class is a concrete implementation of
Example:
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.)
So it takes a lot of code to do what should only take a line or two, when working with dates.
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);
I'll be adding articles dealing specifically with dates myself at a future date.
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.
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.)
What you really want is the java.lang.Math class, in the java.lang package.
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:
float distance = Math.sqrt(dx*dx + dy*dy);
float speed = Math.abs(velocity);
These call the square root function
Math.sqrt()
and absolute value function Math.abs()
. There are a slew of others like degree to radian conversion, the standard trig functions, and so on.Date Calculations
Calculations with dates are another standard sort of math that's not covered by standard operators. In the package java.util we've got the Calendar class. 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 GregorianCalendar class is a concrete implementation of
Calendar
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:- Create a GregorianCalendar Object
- Set its date
- Use its add() method to add or subtract the time difference.
Example:
GregorianCalendar myDate;
myDate = new GregorianCalendar(2011, 6, 7); //set the date to 07 June 2011.
myDate.add(Calendar.Date, 165); // add 165 days to that date.
before()
, after()
and compareTo
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.)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.)
So it takes a lot of code to do what should only take a line or two, when working with dates.
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);
I'll be adding articles dealing specifically with dates myself at a future date.
Labels:
API,
calculations,
dates,
Java,
Math,
methods,
trigonometry
Friday, May 27, 2011
Doing Math in Java part 1: Operators
One 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.
Operators
The standard math functions that are built into the Java language are called operators. These are the sort of math functions you would expect to find on a simple calculator, plus some extras:
There are other operators used for comparisons, these are the math operators. You can learn more about them in the Java Language Specification, specifically in Integer Operations, Floating-Point Operations, and more extensively through Chapter 15, Expressions.
+ and - do what you would expect, they add and subtract one value from another. * is the symbol used for multiplication, instead of the × used in math class. * 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, / is used for division. The ÷ sign isn't on most keyboards, but / has been common on keyboards even before they were attached to computers.
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.
++ and -- 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:
And you do
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 15.14 and 15.15 which cover the two ways of using these operators. In general, it's best to stick to using them after your value until you understand the differences.
Assignment Operators
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:
This takes the prior value of i, adds 3 to it, then puts the result back into variable i. With an assignment operator we can do the same thing more tersely:
We've combined the + with = to create an operator. This does the same thing as
More Complex Math
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.
Until then, have a look at java.lang.Math.
Operators
The standard math functions that are built into the Java language are called operators. These are the sort of math functions you would expect to find on a simple calculator, plus some extras:
+ - * / % ++ --
There are other operators used for comparisons, these are the math operators. You can learn more about them in the Java Language Specification, specifically in Integer Operations, Floating-Point Operations, and more extensively through Chapter 15, Expressions.
+ and - do what you would expect, they add and subtract one value from another. * is the symbol used for multiplication, instead of the × used in math class. * 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, / is used for division. The ÷ sign isn't on most keyboards, but / has been common on keyboards even before they were attached to computers.
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.
++ and -- 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:
int i = 5;
And you do
i++
, the value of i
will become 6. Doing i--
will take away 1. ++ and -- can be placed either before or after the value they act on, for example:number = i++;
count = --j;
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 15.14 and 15.15 which cover the two ways of using these operators. In general, it's best to stick to using them after your value until you understand the differences.
Assignment Operators
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:
i = i + 3;
This takes the prior value of i, adds 3 to it, then puts the result back into variable i. With an assignment operator we can do the same thing more tersely:
i += 3;
We've combined the + with = to create an operator. This does the same thing as
i = i + 3;
. Your program doesn't care which way you type it. The same thing can be done with the other operators that take two values:i *= 4; // Multiply i by four, store result back in i.
i /= 2; // Divide i in half.
i %= 3; // Put the remainder of i/3 in i.
i -= 7; //Subtract seven from i.
More Complex Math
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.
Until then, have a look at java.lang.Math.
Friday, May 20, 2011
Your Own Java Classes
To 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.
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.
Here's our class: (download HelloClass.Java)
The two methods we have to print messages are sayHello() and doHello(). To use sayHello(), we need to have a HelloClass object created, then call that object's sayHello() method.
doHello(), however, is a static method. This means is belongs to the class, not to any object of the class. So we can use it without any HelloClass objects being created first.
Here's a class that uses these methods as described: (download UseHello.java)
If we try to call sayHello() without first creating a HelloClass object, like this:
HelloClass.sayHello();
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.
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.
Files available for download through: http://saundby.com/beginwithjava/.
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.
Here's our class: (download HelloClass.Java)
public class HelloClass{
/**
* sayHello() prints "Hello!" to the Java console output.
*/
public void sayHello(){
System.out.println("Hello!\n");
}
/**
* doHello() prints "Hello, hello!" to the Java console output.
* It's static, so you don't need to instatiate a HelloClass
* object to use it.
*/
public static void doHello(){
System.out.println("Hello, hello!\n");
}
} // End of HelloClass
The two methods we have to print messages are sayHello() and doHello(). To use sayHello(), we need to have a HelloClass object created, then call that object's sayHello() method.
doHello(), however, is a static method. This means is belongs to the class, not to any object of the class. So we can use it without any HelloClass objects being created first.
Here's a class that uses these methods as described: (download UseHello.java)
public class UseHello{
public static void main(String[] arg){
// We can use doHello() without a HelloClass object:
HelloClass.doHello(); // call the HelloClass's doHello() method.
// But we need to create a HelloClass object to use sayHello():
HelloClass hello=new HelloClass();
hello.sayHello(); // call hello's sayHello() method.
}
} // End of UseHello.
If we try to call sayHello() without first creating a HelloClass object, like this:
HelloClass.sayHello();
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.
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.
Files available for download through: http://saundby.com/beginwithjava/.
Friday, May 13, 2011
A Java CSV File Reader
One 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.
Reading the file is as simple as reading a text file. The file has to be opened, a BufferedReader object is created to read the data in a line at a time.
Once a line of data has been read, we make sure that it's not null, 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.
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 for 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.
The Steps
The Program
Downloads
This program, and an example CSV file to use it with (a section of a spreadsheed I use to keep track of my integrated circuits) are available at my code archive.
Writing to CSV Files with Java
Writing to a CSV file is as simple as writing a text file. In this case, we write a comma between each field, and a newline at the end of each record.
Give it a try, starting with TextSave.java, modify it appropriately, then see what your favorite spreadsheet program thinks of the results.
Reading the file is as simple as reading a text file. The file has to be opened, a BufferedReader object is created to read the data in a line at a time.
Once a line of data has been read, we make sure that it's not null, 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.
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 for 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.
The Steps
- Open the file with a BufferedReader object to read it a line at a time.
- Check to see if we've got actual data to make sure we haven't finished the file.
- Split the line we read into an Array of String using String.split()
- Use our data.
The Program
// CSVRead.java
//Reads a Comma Separated Value file and prints its contents.
import java.io.*;
import java.util.Arrays;
public class CSVRead{
public static void main(String[] arg) throws Exception {
BufferedReader CSVFile =
new BufferedReader(new FileReader("Example.csv"));
String dataRow = CSVFile.readLine(); // Read first line.
// The while checks to see if the data is null. If
// it is, we've hit the end of the file. If not,
// process the data.
while (dataRow != null){
String[] dataArray = dataRow.split(",");
for (String item:dataArray) {
System.out.print(item + "\t");
}
System.out.println(); // Print the data line.
dataRow = CSVFile.readLine(); // Read next line of data.
}
// Close the file once all data has been read.
CSVFile.close();
// End the printout with a blank line.
System.out.println();
} //main()
} // CSVRead
Downloads
This program, and an example CSV file to use it with (a section of a spreadsheed I use to keep track of my integrated circuits) are available at my code archive.
Writing to CSV Files with Java
Writing to a CSV file is as simple as writing a text file. In this case, we write a comma between each field, and a newline at the end of each record.
Give it a try, starting with TextSave.java, modify it appropriately, then see what your favorite spreadsheet program thinks of the results.
Friday, May 6, 2011
Java File Save and File Load: Text
We've looked at saving and loading objects 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.
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.
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.
As with object files, the basic steps are:
1. Open a file.
2. Write or read data.
3. Close the file.
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.
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.)
As always, you can download the program files from the Begin With Java Code Archive.
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.
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.
As with object files, the basic steps are:
1. Open a file.
2. Write or read data.
3. Close the file.
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.
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.)
As always, you can download the program files from the Begin With Java Code Archive.
TextSave.java
import java.io.*;
public class TextSave{
public static void main(String[] arg) throws Exception {
// Create some data to write.
int x=1, y=2, z=3;
String name = "Galormadron", race = "elf";
boolean hyperactive = true;
// Set up the FileWriter with our file name.
FileWriter saveFile = new FileWriter("TextSave.txt");
// Write the data to the file.
saveFile.write("\n");
saveFile.write(x + "\n");
saveFile.write(y + "\n");
saveFile.write(z + "\n");
saveFile.write(name + "\n");
saveFile.write(race + "\n");
saveFile.write(Boolean.toString(hyperactive) + "\n");
saveFile.write("\n");
// All done, close the FileWriter.
saveFile.close();
} //main()
} // TextSave
TextRead.java
import java.io.*;
public class TextRead{
public static void main(String[] arg) throws Exception {
int x, y, z;
String name = "", race = "";
boolean hyperactive;
BufferedReader saveFile=
new BufferedReader(new FileReader("TextSave.txt"));
// Throw away the blank line at the top.
saveFile.readLine();
// Get the integer value from the String.
x = Integer.parseInt(saveFile.readLine());
y = Integer.parseInt(saveFile.readLine());
z = Integer.parseInt(saveFile.readLine());
name = saveFile.readLine();
race = saveFile.readLine();
hyperactive = Boolean.parseBoolean(saveFile.readLine());
// Not needed, but read blank line at the bottom.
saveFile.readLine();
saveFile.close();
// Print out the values.
System.out.println("x=" + x + " y=" + y + " z=" + z + "\n");
System.out.println("name: " + name + " race: " + race + "\n");
if (hyperactive)
System.out.println("Oh, yeah. He's hyperactive all right.");
else System.out.println("What a mellow dude.");
System.out.println();
} //main()
} // TextRead
Thursday, April 14, 2011
Java File Save and File Load: Objects
Jump to Reading Data from Files with Java>>
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.
To reiterate:
1. Open a file.
2. Open an object stream to the file.
3. Write the objects to that stream.
4. Close the stream and file.
1. Opening the File
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.
Example:
FileOutputStream saveFile = new FileOutputStream("saveFile.sav");
2. Open an Object Stream
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.
Example:
ObjectOutputStream save = ObjectOutputStream(saveFile);
3. Write Objects
When we write objects to the ObjectOutputStream, they are sent out through it to the FileOutputStream and into the file.
Example:
save.writeObject(objectToSave);
4. Close Up
When we close the ObjectOutputStream, it'll also close our FileOutputStream for us, so this is just one step.
Example:
save.close();
Example Program:
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.
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.
The steps are practically the same as for writing objects to a file:
1. Open a file.
2. Open an object stream from the file.
3. Read the objects to that stream.
4. Close the stream and file.
1. Opening the File
To open a file for reading, 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.
Example:
FileInputStream saveFile = new FileInputStream("saveFile.sav");
2. Open an Object Stream
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.
Example:
ObjectInputStream restore = ObjectInputStream(saveFile);
3. Read Objects
When we read objects from the ObjectInputStream, it gets then from the file.
Example:
Object obj = restore.readObject();
3 and a half. Cast Back to Class
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:
String name = (String) restore.readObject();
4. Close Up
When we close the ObjectInputStream, it'll also close our FileInputStream for us, so this is just one step.
Example:
restore.close();
Here's an example program to read back information saved by the first example program:
<<Return to How to Save to a File with Java
The example programs can be downloaded at:
Begin With Java Code Downloads
Saving Data to Files with Java
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.
To reiterate:
1. Open a file.
2. Open an object stream to the file.
3. Write the objects to that stream.
4. Close the stream and file.
1. Opening the File
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.
Example:
FileOutputStream saveFile = new FileOutputStream("saveFile.sav");
2. Open an Object Stream
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.
Example:
ObjectOutputStream save = ObjectOutputStream(saveFile);
3. Write Objects
When we write objects to the ObjectOutputStream, they are sent out through it to the FileOutputStream and into the file.
Example:
save.writeObject(objectToSave);
4. Close Up
When we close the ObjectOutputStream, it'll also close our FileOutputStream for us, so this is just one step.
Example:
save.close();
Example Program:
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"; ArrayListstuff = new ArrayList (); 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. } } }
Reading Data Files with Java
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.
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.
The steps are practically the same as for writing objects to a file:
1. Open a file.
2. Open an object stream from the file.
3. Read the objects to that stream.
4. Close the stream and file.
1. Opening the File
To open a file for reading, 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.
Example:
FileInputStream saveFile = new FileInputStream("saveFile.sav");
2. Open an Object Stream
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.
Example:
ObjectInputStream restore = ObjectInputStream(saveFile);
3. Read Objects
When we read objects from the ObjectInputStream, it gets then from the file.
Example:
Object obj = restore.readObject();
3 and a half. Cast Back to Class
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:
String name = (String) restore.readObject();
4. Close Up
When we close the ObjectInputStream, it'll also close our FileInputStream for us, so this is just one step.
Example:
restore.close();
Here's an example program to read back information saved by the first example program:
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=""; ArrayListstuff = new ArrayList (); // 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 ) 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. } }
<<Return to How to Save to a File with Java
The example programs can be downloaded at:
Begin With Java Code Downloads
Friday, July 11, 2008
The Java Virtual Machine: Adapter Cables for Your Computer's Insides
One of the problems programmers have is that different computer systems all require different ways to program them. Each computer has its own way of doing graphics and sound, its own way to talk to the keyboard and mouse, and so on. So a program written for one system wouldn't run on another.
We used to have this problem with the hardware on computers, too. If you had a Windows computer and an Apple display, they wouldn't hook up to each other. Apple computers and PCs used different video connectors. The keyboards and mice also had different connectors. The same was true of Unix workstations. They had their own connectors for their monitors, keyboards, and so on, and the connectors for Sun workstations were different from those for HP workstations.
While the outsides of computers are pretty standard now--you can hook up a PC monitor to a Mac and vice versa, the same for USB keyboards and mice--the insides are still just as weird as the outsides used to be. Each computer maker has their own connection for programs that want to talk to graphics, sound, keyboard and mouse, and so on.
Back in the old days we could hook up hardware from different manufacturers sometimes using adapter cables. In other cases, we had adapters that not only connected from one connector to another, but also translated the electronic signals.
For programmers that want to write programs that run on lots of different computer systems, the Java Virtual Machine (JVM) is like a bundle of adapter cables between your program and the computer system it's running on. No matter what system you are on, the JVM makes it look the same to your program:
This is why it's called a "virtual" machine. Java provides a sort of make-believe computer that we can program for. Then the JVM makes other computer systems pretend to be that make-believe computer. So programs written for that make-believe computer will run on any computer that has the JVM on it.
In this way the JVM acts like a whole bunch of adapter cables. On a Windows system it takes the oddball connector from its graphics system and adapts it to your program so that you can use familiar graphics objects and their methods. Similarly, it adapts the sound from OS X to your program, so that you can play music or sound effects. It adapts the filesystem from Unix so that you can read and write files using the same objects and methods as you would use on Windows or OS X. And so on. The JVM adapts all the major parts of a computer to your program, so that you can wrote one program and have it run on all major computer systems, rather than having to spend your time writing it over and over for different systems.
The system isn't perfect. The biggest problem has to do with how programs are "packaged" on each of the different systems. Your program will be the same, but the way you get it to act like a native program on each system for the user varies. The program itself will be the same, but it may need a "helper" file or some other item on each host system to make it look just like a program written directly for that system.
This will typically not be a concern for you as a programmer when you're starting out. And packaging your programs for each operating systems is a lot less work than learning all the ins and outs of how to program each system (or even just one of the systems.)
The JVM is such a useful tool that languages other than Java are being written to take advantage of it. Jython, for example, is a version of the python language that's written to use the JVM. It lets you write python programs that will run on any system with a JVM on it. Groovy is another such language. There's a long list of languages that run on the JVM in addition to Java.
We used to have this problem with the hardware on computers, too. If you had a Windows computer and an Apple display, they wouldn't hook up to each other. Apple computers and PCs used different video connectors. The keyboards and mice also had different connectors. The same was true of Unix workstations. They had their own connectors for their monitors, keyboards, and so on, and the connectors for Sun workstations were different from those for HP workstations.
While the outsides of computers are pretty standard now--you can hook up a PC monitor to a Mac and vice versa, the same for USB keyboards and mice--the insides are still just as weird as the outsides used to be. Each computer maker has their own connection for programs that want to talk to graphics, sound, keyboard and mouse, and so on.
Back in the old days we could hook up hardware from different manufacturers sometimes using adapter cables. In other cases, we had adapters that not only connected from one connector to another, but also translated the electronic signals.
For programmers that want to write programs that run on lots of different computer systems, the Java Virtual Machine (JVM) is like a bundle of adapter cables between your program and the computer system it's running on. No matter what system you are on, the JVM makes it look the same to your program:
This is why it's called a "virtual" machine. Java provides a sort of make-believe computer that we can program for. Then the JVM makes other computer systems pretend to be that make-believe computer. So programs written for that make-believe computer will run on any computer that has the JVM on it.
In this way the JVM acts like a whole bunch of adapter cables. On a Windows system it takes the oddball connector from its graphics system and adapts it to your program so that you can use familiar graphics objects and their methods. Similarly, it adapts the sound from OS X to your program, so that you can play music or sound effects. It adapts the filesystem from Unix so that you can read and write files using the same objects and methods as you would use on Windows or OS X. And so on. The JVM adapts all the major parts of a computer to your program, so that you can wrote one program and have it run on all major computer systems, rather than having to spend your time writing it over and over for different systems.
The system isn't perfect. The biggest problem has to do with how programs are "packaged" on each of the different systems. Your program will be the same, but the way you get it to act like a native program on each system for the user varies. The program itself will be the same, but it may need a "helper" file or some other item on each host system to make it look just like a program written directly for that system.
This will typically not be a concern for you as a programmer when you're starting out. And packaging your programs for each operating systems is a lot less work than learning all the ins and outs of how to program each system (or even just one of the systems.)
The JVM is such a useful tool that languages other than Java are being written to take advantage of it. Jython, for example, is a version of the python language that's written to use the JVM. It lets you write python programs that will run on any system with a JVM on it. Groovy is another such language. There's a long list of languages that run on the JVM in addition to Java.
Subscribe to:
Posts (Atom)
Subjects:
- Android (3)
- angle brackets (1)
- API (15)
- applet (2)
- application (15)
- arguments (2)
- array (3)
- array initializer (1)
- assignment (3)
- asterisk (2)
- beginner (8)
- book review (4)
- C (1)
- C# (1)
- C++ (1)
- calculations (4)
- classes (8)
- code blocks (3)
- collection (6)
- collision detection (3)
- command line (7)
- Comments (1)
- comparison (3)
- constants (1)
- constructor (2)
- cross-platform (1)
- curly braces (3)
- dates (1)
- declaration (4)
- documentation (3)
- dot notation (1)
- embedded (1)
- environment (11)
- equals (2)
- events (3)
- example (2)
- expressions (2)
- file (3)
- file names (1)
- framework (3)
- generics (2)
- graphics (22)
- graphics Swing CSS (1)
- heavyweight component (1)
- humor (1)
- i/o (3)
- IDE (9)
- import (2)
- inheritance (2)
- initializer (1)
- inner class (5)
- input (5)
- interface (3)
- Java (27)
- Java version (7)
- Javascript (1)
- JDK (5)
- JFrame (6)
- JPanel (7)
- JVM (10)
- lightweight component (2)
- List (3)
- listeners (3)
- literal (1)
- local (1)
- loop (2)
- main() (4)
- Math (3)
- method (4)
- methods (2)
- modulo (1)
- mouse (1)
- name (2)
- numeric (2)
- object code (1)
- objects (3)
- operators (4)
- output (3)
- packages (5)
- paint() (3)
- paintComponent() (4)
- parentheses (1)
- percent sign (2)
- PHP (1)
- public (2)
- read (2)
- reference (8)
- regular expressions (1)
- Resources (5)
- restore (1)
- save (1)
- Scanner (1)
- semicolons (1)
- signature (4)
- source code (4)
- square brackets (1)
- star (1)
- static (2)
- Swift (1)
- System.out.println() (2)
- threads (2)
- trigonometry (1)
- type (8)
- variables (9)
- video game (8)
- virtual machine (2)
- void (2)
- web (2)
- why java (9)