Java Programming Language

Written by Larry Gray on . Posted in Java

Java Programming Language Explained

Computer Programming

What do you think of when you think of programming languages? Software right? Software is a set of instructions which the computer executes in, hopefully, logical sequences. Programming languages define and provide those instructions.
public class HelloWorld{
    public static void main(String args[]){
        System.out.println("Hello World");
    }
}

Cryptic

The base software on any machine is the Machine's own Language known as ML(Machine Language) or Assembly. I won't go into details here except to say that this is very cryptic to say the least. Each machine has its unique instruction set. Registers and Ram store data. There are very basic binary math functions. Memory functions. Different types of memory addressing etc. On windows DOS DEBUG command can give you some examples of ML by displaying it from ram directly.
     6897:026E 8D167802      LEA     DX,[0278]
     6897:0272 B409          MOV     AH,09
     6897:0274 CD21          INT     21
     6897:0276 EB05          JMP     027D
     6897:0278 1B5B32        SBB     BX,[BP+DI+32]
     6897:027B 4A            DEC     DX
     6897:027C 24B4          AND     AL,B4
     6897:027E 30CD          XOR     CH,CL
     6897:0280 213C          AND     [SI],DI
     6897:0282 027D0A        ADD     BH,[DI+0A]
     6897:0285 8D167C01      LEA     DX,[017C]
     6897:0289 B409          MOV     AH,09
     6897:028B CD21          INT     21
     6897:028D CD20          INT     20

Somewhat Human Readable Generic Code

In the 1960's programmers saw a need to come up with a more generic language which would make programs more portable across machines. They came up with a language called C. Yes. C was meant to be a cross hardware portable language so that you only had to make minor adjustments to the source code to get the same program to run on one machine or another. C is cryptic but not nearly as cryptic as machine language. C is one of what is called a Von Neumann language. I won't go into details but other Von Neumann languages might be BASIC, Pascal etc. Statements, branching, loops, subroutines and functions is what I think of when I think of a Von Neumann language . I'm assuming the reader knows enough about programming that I don't have to explain statements, branching, loops etc.
/* Hello World program */
#include<stdio.h>
main()
{
    printf("Hello World");
}

Software Execution Options

Software execution may appear to the user in different ways on different levels. Software does not have to interface with a user at all for example. It can run silently in the "background". However the user may experience some good indirect benefit hopefully (other than malware, spyware and viruses). This type is called Daemon software. Can also be called TSR, Drivers or background processes.

Text Based Consoles and Printers

The first software was most noticeable on what was called a text console. Text meaning alphabet and symbols were displayed in one color with a different background color. White, amber and green were the first text colors with black background. Text was arranged in perfectly spaced rows and columns. And then we had the printer whereby text was spaced in a very similar fashion with black text on white paper or green/white paper. The graphics screen was another mode where the screen was divided into rows and columns of pixels. Later we added color to the scene, first 4 colors, then 16, then 256, then 1000's and then Millions and so on. So to get to the point software first interfaced with humans as "output". And a program basically performed this sequence. "Input", "Process", "Output". We called these programs "console applications" or "terminal applications"

Graphical User Interface

As computers have developed or advanced over the years the types of manifestations of computer software have increased significantly. I doubt I can possibly cover all of them. I will talk about some of the types related to Java programming. From the Console we added a pointing device(mouse) and the Graphical user interface, along with multitasking. We call this kind of software GUI Applications or Desk Top Applications.

Web Applications

A very exciting new type of software has been the Web Application. Web sites, and web development. This is software which runs on the web server. The user experiences this software in the form of web pages and files sent to the web browser. And some software runs on the web page or in the web browser as well.

Object Oriented Programming vs (prior Functional or Procedural using structures called Records)

I have been progressing towards telling you about the C++ programming language. This is another Von Neumann language and it is an extension of the C language. This language most notably adds what is called OOP(Object oriented programming) to the C language. OOP most notably combines data and subroutines into a package called an object. It can be thought of as a way to group and reference data and logic which pertain to one another. Its literally a program within a program or software within software.

Where Java steps in "Write once Run anywhere"

This finally brings us to the Java Programming language which was meant like C to be portable, unlike C it is meant to be 100% cross platform(machine) portable. This means you do not have to change the source code at all or recompile and Java will run on any machine. Though there is a catch. The machine must have what is called a Virtual Machine and in this case a Java Virtual Machine. A Java virtual machine executes a generic machine code called "bytecode". By execute I mean it "interprets bytecode". So Java is first compiled to bytecode. Java like C++ is also an OOP language. In Java however everything is an Object and all things begin with Objects. All things are built upon Objects.

Compiled vs Interpreted execution

For those of you who don't know what compiled means I will explain a bit. The first languages other than assembly were not compiled. They were what is called "interpreted". Meaning the program steps are read as text commands each and every time the program was run. This text is known as source code or scripts. Software can be made to run more efficiently if it is converted from this source or scripts into straight binary machine code. I've heard this referred to as "running the application on the metal". I can't possibly go into why this is more efficient except to say that it removes a lot of decision making and branching from the execution process. Is this excess execution speed necessary? Maybe and maybe not. Faster is always better right? Maybe its always better but its not always necessary.

Hybrid Pros Cons

Java therefore can be thought of as being a hybrid between interpreted and compiled languages. By the way compilers have been written for many interpreted languages. And in fact there is an attempt to write a Java Interpreter. Java can also be completely compiled to the native platform but this defeats the purpose of Java and system independence. I guess the advantage of the interpreted langauge is that you don't have this compilation step. An advantage of fully compiled to the metal software is that it doesn't need the interpreter to be installed to run. So what we see here is pros and cons for each type of software execution. Java must be compiled and it must have an interpreter. So we loose both of those typical advantages. However we gain the advantage of 100% Cross Platform portability. Yes I can write a Java program and without change it will run on a Macintosh, a IBM PC or clone. It will run on different operating systems without change as well, OS X, Linux, Unix, Windows etc. It will run without change on any machine and operating system which has had a Java Virtual Machine created specifically for that machine and operating system. It should run on all cell phones for example but thats another story. A special version of Java and VM runs on the Android phones and tablets. Java can still run machine code via Java Native Interface and it can run scripts now via Nashorn. Like I say, Pros and Cons.

Platform or Foundation

Since Java is a generic Machine it is what is known as a "Platform" for software. An operating system for example is a Platform. Hardware set is a platform. Another word for this I would think would be foundation. One good note is that Java is not the only language which is being developed for the Java Virtual Machine. Scala is another and there are more. This means that the JVM will be getting plenty of support as time goes by. Hopefully changes to the JVM will always be favorable for Java.

Popularity, Long live Java!

Computer languages can be thought of as being more or less popular. I've heard some languages being said to be "dead" or "alive". Long live Java! Things are changing fast in computer programming. Java has its competition. J++ was one such and is in fact dead because of a Sun and Microsoft lawsuit. J++ became what is now C# (C-Sharp). J++ and C# is very similar to Java but not identical in many ways. The saga continues. Java has been purchased from Oracle, the database folks. However Java's continued development and growth is managed by the Java community (those that use and love it). So there is plenty of hope for Java. Also many books and a huge source(code) base have been developed. Java will continue to be used for many years to come. Will it loose popularity? Yes at times and it will regain popularity as well. Sometime after 2000 and the coming of virtual machines such as VMware, a new hope and era for Java was the VPS(Virtual Private Server) which promises to make Java web services more affordable. VPS means you can install any operating system on a virtual server and any web services you like. Like Quest Host ,you may therefore have Debian linux installed andTomcat 5.5 web server. You are therefore paying a competitive price for the virtual server not for expensive "Java" web services.

Use the right tool for the right Job

What types of software is Java good for? Ah you want my opinion? Sure, I'll list a few types and next to it show poor, fair, good, great and excellent.
  • TSR hardware drivers(impossible)
  • daemons(great)
  • console applications(poor) with a 3rd party api JCurses (fair)
  • GUI applications(good to great)
  • Games general(poor to great) depends on the type of game
  • Games 3D(poor) except for using what is called OpenGL or JOGL addon's in which case via the use of these 3rd party graphics api's or libraries great 3d graphics can be achieved
  • Servers(excellent)
  • Client software(great to excellent)
  • Web Applications(good to great) depending on who you ask. Java works as well as it ever did but may not be like the newest fads. We are talking here about Java Server Pages, Serlvets, Java Server Faces.
  • Applets[mini applications](poor as of lately) Webstart applications are favored now over applets.
  • Web Start[mini applications](great)
  • Networking apps(excellent)
  • Database (good to great)
Next I will list some uses for Java the same way.
  • Educational software.(sure)
  • Scientific software.(for many types)
  • Accounting software.(why not?)
  • Introductory Programming (excellent, the best)

Conclusion

So in conclusion I say that Java is a great programming language to use and learn. And Java software is very valuable software. Loosing some popularity? Yes. But dead? No by no means dead. Some say, "Use the right tool for the right job." I say, "Use the tool you enjoy using. Use the tool that you know how to use well." Much in the computer world and programming is fad. Java has been a fad. But more than a fad as well. Much in the computer world is experimental. The more things change the more they remain the same right? Reinvention of the wheel is all around us. The basics of programming remain the same. "Statements", "Iteration", "Decisions", "Subroutine". "Input","Process","Output". But things are added over time such as GUI, Networking, Mobile, Virtual Machine. Hardware is improved or added on to for backward compatibility sake. What you learn when using and learning Java will be a foundation for more to come in the future. Even a foundation for learning other programming languages and technologies. I hope I have convinced you to at least learn a little more about Java, to experiment with Java and to test and try it out. Maybe even from a Java application end users viewpoint aye?

Interesting Discussion and Links

Newest latest language features include.
  • Generics, Enumerations, Variable Argument list for methods.
  • Invoke compiler from Java code
  • Run javascript interpreter from Java code using something called Nashhorn. It also may be possible to use other scripting languages but I'm not totally sure right now.
  • Lambda Expresssions(closures) or simplified A REFERENCE OR LINK TO A FUNCTION (called a Method in Java) Previously in Java all methods could only be referenced using a reference to an object that contained the method. In some circles this was a step backward not forward unless used properly. Though just about everyone outside the Java world might call it a step forward.
  • Java Web Sockets (Ajax the proper way using Java)
Jet, an example of platform dependent Java Bean Shell, an example of fully interpreted Java Scala, an example of another JVM Language

Java Phone Apps on Android

Written by Larry Gray on . Posted in Android Apps

Java Phone Apps on Android

Java was designed so that it should run on all phones. The founder of Apple computers who invented the IPhone rejected Java and said it was a slow and dead technology. He provided no support for Java on the IPhone. No phones would support Java if it were not for Google. Google has made a version of Linux which is Android OS and made up api's that support Java. By the way Google makes heavy use of Java technology within its systems. Google even hired one of the main Java guru's away from Sun.

Java will run on a few brands of phones other than the Android I assume with some setup required. Java apps will also run on some tablets and specifically Android tablets. Java had a micro edition at one time for just such ventures, but at the time was for Personal Data Assistants (PDA) such as Palm Pilot. Those have lost popularity and died as a result of tablets and smart phones. I'm not sure at this time if Java ME is used for phone and tablet development or not.

That's about all I know for now. Come back later and hopefully I will update this article with more information on this.

Java Web Sockets

Written by Larry Gray on . Posted in Java WebSockets

Java Web Sockets

Java web sockets is Java's alternative to Ajax. It is actually not specifically Java but an open standard called Web Sockets which is the HTTP alternative to Ajax. Java Web Sockets is Java's implementation of Web Sockets. Basically in HTTP and Common Gateway Interface (CGI) protocols there is much text based overhead in each server request and response messaging. Prior a hack was made to servers that was unofficial to get around this problem. They called it Ajax. It was made official with Web Sockets. The jest of it is that now once the web socket is made your web page and Javascript code can make very concise request with as few characters as possible of the server and get back a very concise response. This reduces bandwidth and speeds communications and reduces lag considerably. Which makes many things possible that otherwise would be impractical. Javascript using the HTML DOM can update pieces of a web page in the browser vs having to reload the entire web page from the server. Surely you can see the advantages for yourself.

Java Facelets and Java Server Faces

Written by Larry Gray on . Posted in Facelets / JavaServerFaces

Java Facelets and Java Server Faces

So Java JSP is awesome and we need no more right? Wrong, JSP is great, but it is a very cryptic way to describe things. Also routine work on web type applications developed into repetitive design and coding task. This was turned into what is called web frameworks. Jakarta Struts is a 3rd party api for such a framework. Sun felt it was time to create a framework for distribution with the standard and extended api's. Facelets and Java Server Faces was born.

Faclets and JSF is built on top of the existing servlet technology. A facelet page is based on specialized facelet codes which are "interpreted" by a Java Facelet servlet. Java Server Faces is the framework that uses this facelet language. This gives the developer quick and easy access to common task using good ole MVC design patterns. And as you might guess Facelet source is a whole lot nicer to read than JSP tag source. Why all this ease of reading? Difficult to read source creates bugs, and slows debugging activities.

Java Servlets, JSP, Facelets and JSF may all be used happily together though Facelets and JSF side step JSP. JSP is left out in the cold by JSF. Not a bad thing really. I believe here this skipped uglier JSP and the compilation process. I would still have no problems using JSP if I wanted, so go ahead and use it all. Matter of fact for now this entire web site is JSP based.

JavaFX

I'll mention JavaFX here. This is some api that uses I think cryptic code for doing things similar to Macromedia Flash effects. It is hardly used at all and gained no real support from the Java community. If I learn more i'll put up a special article about this when I get time.

Java Servlets and Java Server Pages

Written by Larry Gray on . Posted in Servlets / JavaServerPages

Java Servlets and Java Server Pages

Well first maybe I should explain a bit about the first actual web applications called CGI's. CGI(Common Gateway Interface) is a protocol or language for formatting request and responses from an http server to and http client. On this web site the server is the Java web server Apache Tomcat 5.5. A client would be any web browser typically. Initially a web server would send a request in CGI format to standard output on the server, at the same time calling a program on the server to startup. This program can be written in any programming language which can get standard input and output to standard output (practically any language, and even shell scripts). So the server sends the request to standard output which is read as standard input by the program. It then processes the request and prepares a response which is again posted to standard output, the server then reads this back in as standard input. The server then sends this information back to the client as a response.

This was a pretty good thing in the dawn of the internet. However staring up a system process for each request used a lot of system overhead, ram, processor and such. This was especially true when the request begin to come in in large numbers at a time. A server could easily be bogged down with request it couldn't answer. It could even crash. However we have a savior, you might recall from the article on Desktop Applications and GUI 'multi threading'. Developers were already writing these servers on machines that could handle this multi threading. So they worked on a way to send this client request to a thread within the same process(the server itself) to be handled. In Java we call this thread a Servlet. This is far more efficient on system resources than starting up a whole system process (multitasking) for each client request. And threads may be pooled, meaning reused without shutting them down and restarting them each time saving even more precious ram and processor time. Since a servlet runs within the server process it is a mini-application. It is to the server what an "applet" is to the desktop application. The server is made in such a way that you merely drop your servlets into, this is even easier than plugging something in. I mean you simply build your Java sources for your Servlet classes, compile them and then locate them in a given folder structure. The Server automatically knows where to look for them based on good ole standards.

Also the Java Servlet API has some nice classes which encapsulate all that CGI messaging complexity. This api handles request data with one object and response data with another. It handles your http request types such as POST, GET, DELETE, etc. with a single method call. The API simplifies the whole mess so that you the programmer are free to work on your web apps logic.

As an example of running servlets look at the comment submission form on the arksoft home page. This is a servlet I wrote which displays the last 10 comments submitted. It also logs the comments in a text file on the server. And it sends me an email notifying me that a reader has submitted a comment, with the comment content and reply email address. A second servlet processes the captcha image spammer filter. Also the comment submission servlet rejects any comment with image links, or urls or html. I may eventually get this form at the bottom of each article but for now its just one form for the entire site.

JSP

Servlets are enough right? We can do anything we want with them now! Well yes but the ugliness of this was that source code becomes very ugly when its full of System.out.println(" ..........HTML.........HTML........"); We have mixed logic with content. It works. It works fairly well actually. Its just ugly. What is a JSP page? Its a text file named somename.jsp that contains (text only)(html)(text and or html and jsp tags)(jsp tags may contain Java source)

They came up with Java Server Pages to resolve this problem of ugliness and separate HTML from Java source. A jsp page is a text file that has a mix of HTML and JSP tags. This page is compiled by the server at runtime into you guested it, a Servlet and in this servlet the compiler builds all those System.out.println("...html..."); lines for you. When is it compiled? The first time a jsp page is accessed from a browser. This can take seconds to even a minute and may confound a visitor who thinks the page is not loading. Developers usually access the jsp pages themselves to compile them to save the visitor from having to wait. Speaking of the compiled servlet source, good news is that most of the time you never have to look at that ugliness. You can if you want too but there is usually no need unless a debugging problem arises. Java source code can also be included on the jsp page as well if needed though this is probably not best practice. Instead you try to focus on keeping your content in the jps pages and your application logic in supporting Servlets.

And can we somehow work JavaBeans into this scene? Yup, but I won't talk about it on this web site at this time except to say its called EJB Enterprise Java Beans and that requires an additional Server to run with Tomcat called JBoss. There are other 3rd party EJB containers as well. And in fact you could probably use the JavaBean design without an EJB container if you tried with some benefit.

That's not the end of the story with JSP, JSP has what is called Tag Libraries. To be honest I have yet to mess with them. JSP and Servlets and servers for that matter have one very important feature called 'Server Side Includes'. This means the output of one serlvet can be the input of another. It also means that multiple jsp pages and html pages can be combined into one html page for a single response. How is this helpful? Web page headers and footers are prime examples. Let say I have 100 web pages on a web site. Instead of editing 100 pages to update a header or footer I now only edit two files, one for the header and one for the footer. The index.jsp page for each one will look something like the following psuedo example.

JSP Include header.html tag Page content JSP Include footer.html tag

I use this technique on ever page on this web site for header, footer, bread crumb trail, horizontal menu, vertical menu, related links and recommended books. I sometimes use the same related links for sets of pages for example. Mastering the use of server side includes is a must for any web developer that will save countless hours of work or at least make work possible that otherwise would be put off or never done.

Java Applets and Webstart

Written by Larry Gray on . Posted in Applets / Webstart

Java Applets and Webstart

Java Applets

Java applets are mini-applications which run within another application. Applets actually could be run as a desktop application with Java's appletviewer.exe program. And actually, that may be the only way to make an applet run at the current day and time. Well, a better way to run an applet is to convert it to Web Start application which I talk about later on in this article.

Java applets were quit the rage when Java first appeared on the scene. Applets are primarily run on a web page. However over time they lost popularity. Reasons for this might include applets being to startup. Another was applets not starting up at all which usually had a fix but was frustrating enough from the end user point of view to cause a loss in popularity. Applets may have enjoyed their greatest success in the case of in house programming within corporations. One very well used applet to date might be the RPG game called Runescape. Other popular alternatives to the use of Applets were Javascript and Macromedia Flash. At any rate this gave rise to Java Web Start technology.

Applets are inserted into a web page with a single html applet tag. Later the standard changed on this and an html object tag was used instead. The tag gave the applet space on the page as a rectangular area of given dimensions in pixels. An applet might inhabit for example 400x400 on an 800x600 page.

Applet and Web start applications run in what is known as a Security Sandbox. This means that applets do not have access to ram, to hard drive space or any storage space. Well thy can store and read Java cookies. Cookies might be a whole other article. Javascript , Web Start, Java Servlets and JSP can also access cookies. Briefly a cook is 4096 byets of storage on your hard drive in text files where each cookies is a name=value pair. Don't worry, cookies can't have viruses or malware, though they can be read and written by any application on your computer that has not been controlled by security features, such as viruses and malware. This doesn't mean you should disable them however, it simply means you should be more careful about protecting your computer from viruses and malware.

Applets may also not make network connections to other computers. They can only connect back to the computer they were loaded from. These security restrictions can be relaxed in a number of ways. Applets can be signed and have security certificates. Or a user may install a Java security policy file which grants the applets permission to do potentially dangerous things. Or if the applet is loaded locally from the local hard drive it will have a different security policy and has access to the local system and networking. Applets do have usefulness which is why we now have the Java Web Start technology.

Java Web Start

Java Web Start technology is almost the same thing as the Java Applet technology except that it is a normal java application which runs in a Sandbox on your computer as a desktop GUI application with its own Frame. Security is the same for web start apps as it is for Applets. I do not have much to say about Java Web Start except to say that a special file type called .jnlp is needed to launch the web start app in a single mouse click on a web page link. It is then downloaded and started up in the sandbox. Applets and Web Start applications are both cached on the local hard drive in your browsers cache. Applets, Web Start Apps and cookies are all wiped off the hard drive with system cleanup task.

Java Daemons and Servers

Written by Larry Gray on . Posted in Daemons / Servers

Java Daemons and Servers

A server is a daemon but a daemon is not necessarily a server? I think so. I think all a daemon is, is a process that runs in the background, meaning no user interface. You start it up, it hides, runs and does it thing. A server does the same thing but accepts connections from clients which request it to do things for them. The server then does as requested if it can and responds to the client with details, data or files. A server's user interface is the client itself though actually they can have admin user interfaces that are web or GUI based. They usually do not have user interfaces but are simply configured, started and stopped.

If a java daemon(server) is started then in a process list you will see the java VM instead of the actual Java class name. If more than one is started you will only see multiple java VM's listed in the process list on the System. It might be difficult to know which process to kill if for example you wanted to kill a certain Java server. Below I list common types of servers.

  • Web Servers(files and webpages)
  • EMail Servers
  • Game Servers
  • Chat Servers
  • Messenger Servers
  • Time Servers
  • News Servers
  • Database (SQL)
  • Name Servers(DNS)

How do clients and servers communicate? TCP/IP protocol or (Transmission Control Protocol/Internet Protocol). In Java we use the sockets API. A socket connects to ports. TCP/IP defines just over 65,000 logical ports on a computer. This is really only a way of routing incoming and outgoing messages to and from clients and servers, computers and computers. The first few 1000 ports are the most used. Some ports have been standardized. For example HTTP is on port 80. You may run a web server on other ports. For example "http:80//www.somedomain.com/myfolder" is exactly the same as "http://www.somedomain.com/myfolder". But you may run a 2nd server on another port such as 8000. "http:8000//www.somedomain.com/myfolder". "http://" and"http:8000//" are two completely different web sites hosted on the same computer. The thing to remember here is that web browsers default to the standard port 80 unless you tell them the port explicitly.

 IPv4 Address. . . . . . . . . . . : 192.168.1.10
Use ipconfig to find your IP address like above. Then edit the Client source using your IP address.

Java Server

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    
    public static void main(String[] args) throws IOException {
        ServerSocket listener = new ServerSocket(10100);
        try {
            while (true) {
                Socket socket = listener.accept();
                try {
                    PrintWriter out =
                        new PrintWriter(socket.getOutputStream(), true);
                    out.println("Hello World from the Server!");
                } finally {
                    socket.close();
                }
            }
        }
        finally {
            listener.close();
        }
    }
}
Java client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class Client{
    public static void main(String[] args) throws IOException {
        String serverAddress = "192.168.1.10";
        Socket s = new Socket(serverAddress, 10100);
        BufferedReader input =
            new BufferedReader(new InputStreamReader(s.getInputStream()));
        String answer = input.readLine();
        System.out.println(answer);
        System.exit(0);
    }
}
Run the server using javaw.exe instead of java.exe to run it in the background. Then run the client.

c:\dev\java>javac Server.java

c:\dev\java>javaw Server

c:\dev\java>javac Client.java

c:\dev\java>java Client
Hello World from the Server!

c:\dev\java>

So can a mail server and web page server run on the same port? Absolutely not! At least not at the same time. This is what makes TCP/IP so nice. Its like a traffic cop for messaging between computers. TCP/IP and Client/Server design is what the Internet is. And can your desktop computer be a server? Sure, any computer can be a server or client. What do you think malware and spyware is? Someone has maliciously installed a server or (Trojan horse) on your computer which gives them complete access(and slows your computer at the same time).

Java Console Applications

Written by Larry Gray on . Posted in Console Applications

Java Console Applications

I gave a very small introduction to Java console application execution in the Java Desktop applications article. Java console applications are started in the same manner. I talked about path and classpath which are both very important. If the path and classpath are not set properly then your console application will fail to execute. I explain how to set the classpath on windows in the Desktop Applications article. There is much help on the internet for telling you how to set the system path to add java bin folder. If you do not add the JDK bin folder to the path then when you type 'java' at the command line or any other java tools you will get a not found error.

(DOS OR Windows Shell example)

set path=%path%;c:\dev\java\jdk8\bin;
set classpath=%classpath%;.;c:\dev\java\myproject\bin;
echo %path%    shows you the current path setting
echo %classpath%   shows you the current classpath setting

Java was not designed from the ground up for operation at the console(text screen) as a user interface. The standard Java API's and installation provide only very basic access to the system console. Java was made more for the windows GUI and is used more as background processes like servers. Many server applications are started from the console or from scripts which are run by the system. Some popular java utility applications operate from the command line. For more advanced console programming 3rd party API's are needed such as JCurses. JCurses might allow more complete control of the screen as in plotting characters to exact x,y positions. JCurses may let you alter background colors and foreground colors. Another 3rd party API is Java Native Access which I have not tried. This lib will allow you to output text in color to the console from what I understand. Another option for someone wanting to step back in time and have a terminal would be to make your own GUI component which emulates a text screen(JPanel), system input(KeyListener) and system output (plotting ASCII characters(drawImage()) in cells).

Below is an example of where I used JCurses with my Java Ledger project.

This slideshow requires JavaScript.

Java console or GUI applications may be given arguments when started from the command line in the console. This is merely a list of words which were separated by spaces in the command. i.e. 'java MyJavaApp Hello World' might return Hello (new line) then World (new line). Most command line commands have options. With Java arguments given to the main method (which is the starting point in any java application) the programmer may code options into the startup of the application using whatever syntax he likes such as '/s /q' or '-sq' or whatever seems appropriate.

Using the Java System object one may access the 'standard input', 'standard output' and ' standard error'. Standard input will allow the programmer to gather a line of text at the end(bottom) of the console from the user. System output allows the java programmer to output lines of text at will to the console. System execute command would allow the programmer to use a DOS command like CLS to clear the console. This isn't robust but it works and can get the job done. Also Java apps can handle redirection of input output in the same manner as any other system processes. I'm fairly sure you could direct the output of one Java application as input for another for example. You may certainly redirect the output from a Java application to a text file.

Pieces of example code.

// here we make a BufferedReader to get a line of text from the console.
br = new BufferedReader(new InputStreamReader(System.in)); // here we use System.in
//next in an infinite loop use
String input = br.readLine();
// then you can output the result back to the console
System.out.println("input:"+input);  // here we see the use of System.out
// if you throw exceptions in your code the output will go to System.err (error).

To be honest I have not seen many or any Java console apps that request key input from the console. I use the console mostly for quick and dirty debugging output. Though logging API's basically do the same thing better but with files or console. If a person wanted too, he could grab some input by using JOptionPane.showInputDialog() method. Using this in a console app means a GUI dialog will popup in front of the console and request input in a text field. When the user hits enter the dialog closes and text is returned as a String from the method call. You may do this without even using or displaying a JFrame.

In conclusion the console even with Java is useful and necessary at least for execution of applications and output from applications. I am even working on a text screen emulation component for the GUI as I described above for a retro text based adventure game using Java.

Widgets/Java Beans/Components

Written by Larry Gray on . Posted in Widgets / Javabeans / Components

Java Desktop Widgets, JavaBeans and Components

GUI applications are made up of Components in a modular manner. These components (parts) are plugged into one another more or less. Some contain others. Below I list some commonly known GUI widgets. Here is a link to a cool set of charts showing Java Swing Components And here A visual guide to Swing Components

  • Frame
  • Menu Bar
  • Button (Press and Toggle)
  • Button Bar
  • Text Label
  • Text Field
  • Text Box
  • Combo Box
  • List Box
  • Icon
  • Dialog Box (popup)
  • Tool Tip
  • Panel
  • Scroll Pane
  • Tabbed Pane
  • Scroll Bar (vertical or horizontal)
  • Progress Bar
  • Check Box (for selections)
  • Option Button (for selections)
  • Resize Bar
  • Tree Viewer
  • Table Viewer

I am sure there are more than listed above. And anyone may make custom widgets of any kind for any purpose for more robust or specialized GUI's. This brings me to the topic of JavaBeans next.

public class BushBean{
    private Color beanBushColor;
    private Name name;
    public setColor(Color aColor){
        this.beanBushColor=aColor;
    }
    public Color getColor(){
        return this.beanBushColor;
    }
    public setName(String aName){
        this.name = aName;
    }
    public String getName(){
        return this.name;
    }
}
A Java Bean can be a GUI component or even a business logic class which is not even related to the GUI graphically. Java Bean itself is a design pattern. In order for the GUI widgets to function properly a given popular and well known design must be followed. This is called the MVC or Model-View-Controller. By the way a good site for design patterns is Vince Huston Design Patterns. Though I didn't find MVC but it may be the Mediator Strategy Pattern. I couldn't find a JavaBean design patterns there either. Java Bean itself is a class which has public 'setter' and 'getter' methods for its private properties. Using this design JavaBeans are more or less pluggable. And these properties control how it looks and functions within the GUI. They also control how the widget(view) interacts with its (model) and maybe (controller). Most if not all Java widgets are also a form of a JavaBean in design.

So what is a component? Its something that can be plugged into something else. A frame contains for example a menu bar, a button bar, a main panel. A menu bar contains menu items, and sub menu items etc. A button bar contains buttons. A panel can contain anything, such as other panels and edit boxes and text. A dialog might contain edit boxes, selection boxes etc and text. Some things you click on like sliders and arrows and scroll buttons are controls which are part of the widgets.

And what makes all these parts work together flawlessly? Well this becomes more complicated and even difficult to explain. In a word its called 'multithreading'. Well no there is another word I'll talk about later on in this article 'events'. Related terms might be 'processes'. In java we are dealing with multithreading. This is all part of this new (for the past 20 years for most of us(though in reality its been around since the 60's on mini-computers and main-frames)) technology called 'multitasking' not to be confused with windows 3.1 'task swapping'. When I grew up in computers the processor could only do one thing at a time. What a wonderful world that was in computers. We did talk about how in the future a micro-computer processor could actually be executing different parts of a program at the same time. That future was not far away. This is multithreading. Running different programs at once is multitasking. You as a programmer generally do not have to deal with threads in your GUI directly. This has already been done behind the scenes. You need to become familiar with the concept to troubleshoot and identify possible thread related problems.

Simple thread example.

public class HelloRunnable implements Runnable {

    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new Thread(new HelloRunnable())).start();
        System.out.println("Hello from main thread.");
    }

}
c:\dev\java>notepad HelloRunnable.java

c:\dev\java>javac HelloRunnable.java

c:\dev\java>java HelloRunnable
Hello from main thread.
Hello from a thread!

c:\dev\java>
A major problem with all this is that if these processes and threads and such are not dealt with very carefully by the programmer then your GUI hangs up. Or certain parts of the GUI hang up. Or your system hangs up. I think we can all relate to this, especially those of us who have used the MS Windows systems. Though to be fair newer versions of windows seem to be better about not locking up as frequently. But the rule of thumb is that you do not use threads unless you have a good reason to and as few as possible.

Other notes on the widgets in the list above is that some of them are also seen on your web pages as HTML components. Also the last two widgets are very complex and have many specialized sub components. A widget itself can become as complex as any software with a learning curve of its own. Both for the programmer and the end user.

public class MouseEvents extends JPanel
        implements MouseListener, MouseMotionListener {
    .....
    // from MouseListner class
    public void mousePressed(MouseEvent e) {
        System.out.println(e);
    }
     
    public void mouseReleased(MouseEvent e) {
      System.out.println(e);
    }
     
    public void mouseEntered(MouseEvent e) {
        System.out.println(e);
    }
     
    public void mouseExited(MouseEvent e) {
      System.out.println(e);
    }
     
    public void mouseClicked(MouseEvent e) {
       System.out.println(e);
    }
    .....
    // of MouseMotionListener class
    public void mouseMoved(MouseEvent e) {
       System.out.println(e);
    }

    public void mouseDragged(MouseEvent e) {
      System.out.println(e);
    }
    .....
}
Another major piece of the GUI puzzle is this notion of System "Events". This leads us to another term in programming called 'Event driven programming'. The system monitors mouse and keyboard events and relays them to your GUI application(if it has focus). Focus means its on top and in view of other applications. A component may also need to have focus. Usually you tab through components to give one or another focus. I list a few common GUI events below.
  • Mouse press
  • Mouse release
  • Mouse enter
  • Mouse exit
  • Mouse clicked
  • Mouse moved
  • Mouse drag
// this key listener class can be added to a component such as JTextField or JTextArea or even JPanel or any component.
public class KeyEvents implements KeyListener{
    public void keyTyped(KeyEvent e) {
        System.out.println(e);
    }
    public void keyPressed(KeyEvent e) {
       System.out.println(e);
    }
    public void keyReleased(KeyEvent e) {
        System.out.println(e);
    }
}
  • Key typed
  • Key pressed
  • Key released
This is all part of controller coding. Basically in Java a class called a Listener is installed in a component. Java has KeyListener and MouseListener, MouseMotionListener and MouseWheelListener and MouseInputListener. On each event type special commands are added and executed if the event occurs to the component. This is event driven programming. Your GUI and Components patiently sit there waiting on you to do something so that they may do something for you. Components have focus as well as the entire application. The last component you clicked on has focus and is paying more attention to you than the rest of them. Focus can also be gained with the keyboard with accessibility keys added to each function or component. For example you can cycle through the components in the GUI with the enter key or tab key. Or the key "H" assigned for the help menu.

A programmers job is to create the view by plugging in all the components. Then he/she alters the model with adjustments to component properties. And then wires it all together with controller code in listeners and such. If I didn't explain all this GUI stuff properly then I am sorry, come back later and maybe I will have made things clearer. I am merely trying to introduce the reader to these concepts. Finally components/widgets/javabeans are fairly big business items because they are to programmers what parts in the auto parts store are to shade tree mechanics.

Desktop Applications

Written by Larry Gray on . Posted in Applications

Java Desktop Applications

Let me explain a few things that will prepare you to run a Java Desktop Application, and other Java Applications as well. If you do not get this right the application won't run.

Bytecode example that looks very similar to assembly language.

  iconst_2
  istore_1
  iload_1
  sipush  1000
  if_icmpge       44
  iconst_2
  istore_2
  iload_2
  iload_1
  if_icmpge       31
  iload_1
  iload_2
  irem
  ifne    25
  goto    38
  iinc    2, 1
  goto    11
  getstatic       #84; // Field java/lang/System.out:Ljava/io/PrintStream;
  iload_1
  invokevirtual   #85; // Method java/io/PrintStream.println:(I)V
  iinc    1, 1
  goto    2
  return
  Java runs in a virtual machine, meaning this VM (java.exe or javaw.exe) interprets Java bytecode. For the VM to be able to interpret the bytecode it needs to be started up and given the name of an executable Java class. An executable Java class is one with a "public static void main(String args[])" method. Also any supporting classes must be on the classpath. The Java VM first loads the class with the main method and then begins loading all other classes needed for the application to run.

Objects, Classes and the classpath variable.

This is Java's world. Its a world with a classpath full of Java classes. Classes are in programming terms types of Objects. You may have heard of OOP (Object Oriented Programming). Java is based on languages such as SmallTalk and C++ when it comes to OOP with some variants of its own. Prior to objects or OOP program code was grouped into files called libraries. Data was grouped into records. OOP combines this and logically groups program logic and data into units called objects.

This slideshow requires JavaScript.

So what is a classpath? Its extremely similar to the DOS or Unix system PATH variable in function. The path variable reduces the number of locations that your operating system will have to search to find commands that you enter at the command line. If you didn't have this it might take many minutes just to find the command to run because its looking over the entire hard drive for the command. The classpath is a system variable. There are other system variables related to Java as well such as JAVA_HOME and CATALINA_HOME and others. I won't talk about those in this article however. The classpath provides a set of locations on the hard drive where the Java VM should look for classes when loading them (loading up and running your java application). This is very handy for the VM because it doesn't have to search the entire hard drive for classes but only say 5 to 10 percent of it or much less. Also this eliminates situations where you have multiple versions of classes in different locations causing class version conflicts. The classpath may be set at the DOS command line or Unix command line. It may be set on Windows in the System Properties Advanced Settings as a permanent setting. On Unix it may be set in .bashrc file for the user. And when executing the VM, a command called 'java' on linux and 'java.exe' on windows, you may specify classpath options as well. This classpath is very important because if you do not get it right your application will fail to startup. There is more to learn about the classpath that I tell you about here, such as inclusion of current folder '.' for example.
import java.awt.*;  
import javax.swing.*;  

public class DisplayGraphics extends JPanel{  
      
    public void paint(Graphics g) {  
        g.drawString("Hello",40,40);  
        setBackground(Color.WHITE);  
        g.fillRect(130, 30,100, 80);  
        g.drawOval(30,130,50, 60);  
        setForeground(Color.RED);  
        g.fillOval(130,130,50, 60);  
        g.drawArc(30, 200, 40,50,90,60);  
        g.fillArc(30, 130, 40,50,180,40);  
          
    }  
        public static void main(String[] args) {  
        DisplayGraphics displayGraphics =new DisplayGraphics();  
        JFrame f=new JFrame();  
        f.add(displayGraphics);  
        f.setSize(400,400);  
        //f.setLayout(null);  
        f.setVisible(true);  
    }  
} 

Once the classpath issues are resolved all that one need do to start a Java application is something like 'java AClassName' or 'java.exe AClassName'. If this does not work for you then you have a classpath problem or have not used the proper class name which may need to be the fully qualified name. For example 'java apackage.AClassName' Java classes are categorized in packages most of the time, which have names. These names correspond to folder names on the system. If indeed there were a package named apackage then it would be in a folder '\apackage' or '/apackage' depending on your system. Remember "\" on windows and "/" on Unix in file paths.

You may also start up Java Applications from within an IDE such as Eclipse by merely clicking on the class and selecting Run from a menu. Another method would be to run a Java application that has been packaged in an executable Jar file. These files are named with '.jar' at the end. On a properly installed Java Runtime Environment or JRE or Java Development Kit JDK or SDK, one can place the jar on his desktop and merely click it to run it as he would any GUI app by clicking an Icon. At the command line you may use a command like 'java -jar somejavaapplication.jar' or java.exe on windows. On linux follow this with the & symbol to run it in the background so that the console is freed up for other things. On windows you may use 'javaw.exe' to do the same thing.

I talk in the Java console applications article more about anything to do with Java from the console or command line. I wanted to mention it here to give the reader a good foundation for the understanding on how to startup Java GUI applications. The easiest way to run a java application is from the jar file by clicking it from the desktop or by adding the jar file to the start menu so that it may be started as any normal GUI application. You may need to add a shortcut on the desktop to the jar file instead of copying the jar file. In more complex applications the jar has to be executed from the installation folder, or using a windows shortcut or unix symbolic link. You may also alternatively navigate in the system folder explorer and click on the executable jar file to run it.

A note to programmers about how this executable jar file works. First you must make up a manifest file that has one entry which describes which class should be the 'main class'. When building this jar file you need to specify the manifest file name in the command. Just unpack 'unjar' any executable jar file to see how this is setup. Simply edit the manifest file to view the syntax. On my java projects there may be many class files with main methods. I do this for several reasons. Many of the main methods are for "boot strap" testing. Meaning I am simply using it to run and test and debug the class itself without starting up and loading the rest of the project. In other cases I have multiple apps within one project. It would be a simple thing to make a menu app for starting up any of them. In those cases the only main method that is needed is the one in the MenuApp and it would be the main class in the jar.

Once you learn to run Java GUI Application the fun begins. You will find them to be as nice as any GUI application if they are properly designed and made. Java GUI's can be made from several libraries and each give them a slightly different look and feel. The standard libraries that come with Sun's and now (Oracle's) Java is made with AWT(Abstract Windowing Toolkit) or Swing which is based on AWT. AWT came first, then Swing. Usually in today's Java world any application from Sun's Java would be a Swing application. Swing itself comes with 4 main 'look and feels'. First there is the Java default Swing Look and Feel. Next the Windows Look and Feel. Then there is the Metal Look and Feel which resembles Unix like GUI's. And there is Motif which resembles Mac GUI's. And custom Look and Feel's can be made as well. So don't be surprised if you start up different Java apps and they look slightly different. This was done so that users on different system could set a look and feel that more closely resembles their own native system's GUI.

IBM has a GUI library (libraries are also know as API or application programmer interface) called SWT (Standard Widget Toolkit). If you are familiar with Eclipse IDE I believe that it is made using SWT and not Sun's Swing. And finally there is OpenGL which is for high end graphics mostly in Game, Simulator or CAD type applications. OpenGL may have its own widgets and look and feel I assume.

If you have installed Sun's Java SDK (JDK) Development Kit (IBM has a development kit and now there is Open JDK yet another one.), you will find demonstration applications for probably both AWT and Swing GUI. These are fairly impressive so have a look. Find and download some Java apps and try running them. A good place to look would be www.sourceforge.net.  Source Forge is a web site which is dedicated to helping assist and coordinate the collaborative efforts of programmers from around the world on creating free software. (This opens up a whole other can of worms as in "why would anyone want to work for free on software", which I will not go into here.) Just know that the software is free, so download and enjoy. Many of the tools I use as a programmer are projects that are hosted at sourceforge. Sourceforge is not the only open source host on the internet. When I get time later in another article I'll be glad to list some others, and they host Java Projects as well. In conclusion I say "search and enjoy".

Well one last note. To run Java apps from the command line you may need to add the Java distribution binaries to the System path variable. This is slightly different on each system and I won't explain this here. Simply search the web and you find many examples and explanations. If I explain more it will be in the article about Java console applications.