39582369-Java

109
Java Fundamentals

Transcript of 39582369-Java

Java Fundamentals

IntroductionJava is an Object Orientated programming language that is very popular amongst commercial organizations to develop a wide range of applications from small utilities to enterprise wide, mission critical systems. In this module we will start at the beginning and help you through getting going and developing your first applications. If there is anything you need some extra assistance with just post a question on the message board. Dont forget to have a look though to see if you can help anyone else.

ObjectivesThis module will give you a solid introduction to Java. You will install the Java Software Development Kit. And then set up your development environment. Once everything is ready to go you will write your first Java program. We will then take you through the core features of the Java programming language. Of course we will keep you busy with exercises and tests as you go through the module.

Module NavigationJava Fundamentals Introduction Objectives What is Java History of Java Versions of Java Getting Started Installing Java Your Enviroment Alternative Enviroments Your First Application What Just Happened? Java Basics Class Libraries JavaDocs Third Party Libraries Primitive Types Input and Output Printing Output Reading Input Exercise Summary Operators Arithmetic Operators Comparison Operators Bitwise Operators Making Decisions Arrays Looping Execise One Exercise Two Summary Objects Java Objects Syntax Using Constructors Using Objects

Packages & Imports Casting Exercise Summary Grouping Objects Collections Sets Lists Maps Looping Summary Advanced Objects Encapsulation Inheritance Polymorphism Interfaces Abstraction Summary Exercise Error Handling Exceptions Syntax Exercise Summary GUI Files Configuration Files Recursion Exercise Exercise Summary Logging Configuration Using Loggers Testing Threads Test Summary

IntroductionOne of the most important skills you will need to have as a good computer programmer is a good background knowledge of everything that is involved in software development. Whether you are conversing with somebody who will be using the finished solution or the architect who produced the specification you are following, you will come across generic terms that are used everyday in the world of software development. "Review this Use Case and produce a Sequence Diagram that implements the Factory Pattern." Obviously that will not be the entire conversation and asking questions is fine but in order to operate effectively on a project you need to know a lot more than a single programming language. This module will give you some of that essential knowledge. You will build on the concepts introduced here in later modules and you may even be confronted with exercises click here to add comments

The History of JavaJava evolved from a language called Oak and has actually been around for about twenty years. Knowing its history is unlikely to change your career but you might find it interesting to know a little about how we got to where we are today.

1. History of the World Wide Web1.4. History of JavaAt first glance, it may appear that Java was developed specifically for the world wide web. However, interestingly enough, Java was developed independently of the web, and went through several stages of metamorphosis before reaching its current status of de facto programming language for the world wide web. Below is a brief history of Java since its infancy to its current state.

1.4.1 OakAccording the Java FAQ, [Harold] Bill Joy, currently a vice president at Sun Microsystems, is widely believed to have been the person to conceive of the idea of a programming language that later became Java. In late 1970's, Joy wanted to design a language that combined the best features of MESA and C. In an attempt to re-write the UNIX operating system in 1980's, Joy decided that C++ was inadequate for the job. A better tool was needed to write short and effective programs. It was this desire to invent a better programming tool that swayed Joy, in 1991, in the direction of Sun's "Stealth Project" - as named by Scott McNealy, Sun's president. [Harold] In January of 1991, Bill Joy, James Gosling, Mike Sheradin, Patrick Naughton (formerly the project leader of Sun's OpenWindows user environment), and several other individuals met in Aspen, Colorado for the first time to discuss the ideas for the Stealth Project. The goal of the Stealth Project was to do research in the area of application of computers in the consumer electronics market. The vision of the project was to develop "smart" consumer electronic devices that could all be centrally controlled and programmed from a handheld-remote-control-like device. According to Gosling, "the goal was ... to build a system that would let us do a large, distributed, heterogeneous network of consumer electronic devices all talking to each other." With this goal in mind, the stealth group began work. [O'Connell] Members of the Stealth Project, which later became known as the Green Project, divided the tasks amongst themselves. Mike Sheradin was to focus on business development, Patrick Naughton was to begin work on the graphics system, and James Gosling was to identify the proper programming language for the project. Gosling who had joined Sun in

1984, had previously developed the commercially unsuccessful NeWS windowing system as well as GOSMACS - a C language implementation of GNU EMACS. He began with C++, but soon after was convinced that C++ was inadequate for this particular project. His extensions and modifications to C++ (also know as C++ ++ --), were the first steps towards the development of an independent language that would fit the project objectives. He named the language "Oak" while staring at an oak tree outside his office window! The name "Oak" was later dismissed due to a patent search which determined that the name was copyrighted and used for another programming language. According to Gosling, "the Java development team discovered that Oak was the name of a programming language that predated Sun's language, so another name had to be chosen." [O'Connell] [Harold] "It's surprisingly difficult to find a good name for a programming language, as the team discovered after many hours of brainstorming. Finally, inspiration struck one day during a trip to the local coffee shop" Gosling recalls. Others have speculated that the name Java came from several individuals involved in the project: James gosling, Arthur Van hoff, Andy bechtolsheim. [McCarthy] There were several criteria that Oak had to meet in order to satisfy the project objective given the consumer electronics target market. Given the wide array of manufacturers in the market, Oak would have to be completely platform independent, and function seamlessly regardless of the type of CPU in the device. For this reason, Oak was designed to be an interpreted language, since it would be practically impossible for a complied version to run on all available platforms. To facilitate the job of the interpreter, Oak was to be converted to an intermediate "byte-code" format which is then passed around across the network, and executed/interpreted dynamically. [O'Connell] [Harold] [McCarthy] Additionally, reliability was of great concern. A consumer electronics device that would have to be "rebooted" periodically was not acceptable. Another important design objective for Oak would then have to be high reliability by allowing the least amount of programmer-introduced errors. This was the motivation for several important modification to C++. The concepts of multiple-inheritance and operator overloading were identified as sources of potential errors, and eliminated in Oak. Furthermore, in contrast to C++, Oak included implicit garbage collection thereby providing efficient memory utilization and higher reliability. Finally, Oak attempted to eliminate all unsafe constructs used in C and C++ by only providing data structures within objects. [O'Connell] [McCarthy] Another essential design criterion was security. By design, Oak-based devices were to function in a network and often exchange code and information. Inherently, security is of great concern in a networked environment, especially in an environment as network dependent as the conceived Oak-based systems. For this reason, pointers were excluded in the design of Oak. This would theoretically eliminate the possibility of malicious programs accessing arbitrary addresses in memory. [O'Connell] [McCarthy]

If Oak were to be widely accepted and used within the consumer electronics industry, it would have to be simple and compact, so that the language could be mastered relatively easily, and development would not be excessively complex. Some would argue that Oak/Java is C++ done right, but the jury is still out on that... In April of 1991, Ed Frank, a SPARCstation 10 architect, joined the green project. He led the project's hardware development effort. In two months, they developed the first hardware prototype known as star-seven (*7). The name *7 was somewhat demonstrative of the project's objective. *7 was the key combination to press on any telephone to answer any other ringing telephone on their network. In the meantime, Gosling was beginning work on the Oak interpreter. By August of 1991, the team had a working prototype of the user interface and graphical system which was demonstrated to Sun's cofounders Scott McNealy and Bill Joy. [O'Connell] Development of Oak, the green OS, the user interface, and the hardware continued through the summer of 1992. In September of that year, the *7 prototype was complete and demonstrated to McNealy and Joy. The prototype was a PDA-like (personal digital assistant) device that Gosling described as a "handheld remote control." Patrick Naughton proclaimed that "in 18 months, we did the equivalent of what 75-people organizations at Sun took three years to do -- an operating system, a language, a toolkit, an interface, a new hardware platform, ..." [O'Connell] While impressive, the market was not conducive to this type of technology, as later demonstrated by Apple's Newton PDA. The Green project's business planner, Mike Sheradin, and hardware designer, Ed Frank had envisioned a technology similar to that of Dolby Labs which would become the standard for the consumer electronics products. [O'Connell]

1.4.2 FirstPersonIn November of 1992, the Green Project is incorporated under the name FirstPerson. Given Java's lack of success in the consumer electronics industry, the company's direction was somewhat uncertain. Under Sun's influence, the company began reevaluating its mission. In early 1993, Time-Warner issued an RFP (request for proposal) for a set-top box operating system and interactive, video-on-demand technology. FirstPerson identified this area as a new target market, and began working in that direction. However, despite FirstPerson's great efforts, SGI was granted the contract by Time-Warner. By mid 1993 Sun began negotiating with 3DO to provide a Java-based OS for their set-top box. The negotiations were, however, unsuccessful and a deal was never made. FirstPerson was left on its own without any viable business prospects. Another attempt by the company to market its interactive TV technology fails when in February of 1994 a public launching of their products is canceled. [O'Connell]

A Sun higher level review of FirstPerson determines the interactive TV market to be immature in 1994. FirstPerson then shifts its focus yet again. Business plans are submitted to Sun's executives for developing Oak-based on-line and CD-ROM applications. Sun's response was not favorable, and FirstPerson was dissolved. Most of FirstPerson's employees moved to Sun Interactive to digital video data servers. However, a few individuals from FirstPerson still pursued the objective of finding a home for Java in a networked desktop market. [O'Connell]

1.4.3 Java and the World Wide WebIn June of 1994, Bill Joy started the "Liveoak" project with the stated objective of building a "big small operating" system. In July of 1994, the project "clicked" into place. Naughton gets the idea of putting "Liveoak" to work on the Internet while he was playing with writing a web browser over a long weekend. Just the kind of thing you'd want to do with your weekend! This was the turning point for Java. [O'Connell] The world wide web, by nature, had requirements such as reliability, security, and architecture independence which were fully compatible with Java's design parameters. A perfect match had been found. By September of 1994, Naughton and Jonathan Payne (a Sun engineer) start writing "WebRunner," a Java-based web browser which was later renamed "HotJava." By October 1994, HotJava is stable and demonstrated to Sun executives. This time, Java's potential, in the context of the world wide web, is recognized and the project is supported. Although designed with a different objective in mind, Java found a perfect match in the World Wide Web. Many of Java's original design criteria such as platform independence, security, and reliability were directly applicable to the World Wide Web as well. Introduction of Java marked a new era in the history of the web. Information provides were now given the capability to not only deliver raw data, but also the applications that would operate on the data. Sun formally announced Java and HotJava at SunWorld `95. Soon after, Netscape Inc. announced that it would incorporate Java support in their browser. This was a great triumph for Java since it was now supported by the most popular browser in the world. Later, Microsoft also announced that they would support Java in their Internet Explorer web browser, further solidifying Java's role in the World Wide Web.

Versions of JavaKnowing the history of Java may not change your career but it is important to know your stuff when it comes to the different versions of Java. You need to be aware of this because you might find yourself working on a project for a client that has elected to use a version other than the one you are used to or even one from a different manufacturer. When it comes to the version of there are three main variables, the manufacturer, the edition and the version number. Java was invented by Sun Microsystems but other manufactures, including IBM, also produce their own Java Virtual Machines, compilers and other tools. There are two editions of Java, the Standard Edition (J2SE) and the Enterprise Edition (J2EE). The Enterprise Edition is basically a set of technologies that extend the Standard Edition. These technologies include those used in larger system such as Enterprise Java Beans (EJBs). The [standard edition] version number is the most complicated bit. Some software vendors choose to name the versions of their products or use larger numbers like the current year but Java version numbers tend to increment very slowly. The first commonly available version of Java was 1.1 and was followed by 1.2 but 1.2 was considered such an improvement it became known as Java 2 or J2SE. The next major version was 1.4 (known as J2SE 1.4) and most recently came 1.5. This version introduced some new language features so the decision was made to call it J2SE version 5. To complicate things even further each of these versions has sub versions and sub-sub versions. These are used for interim and maintenance releases. It is always a good idea to check exactly which version you should be using when joining a project team. It is common for project managers to not use the very latest version, they will often use a version that has been around long enough for any bug to have been fixed. For this reason we will be using version J2SE 1.5 for this course but will be highlighting features that didn't exist in 1.4. If that is clear then you are doing well but there is one other variable, the enviroment. If you want to develop (or compile) Java applications you need the Java Development Kit (JDK), if all you want to do is run Java applications you only need the Java Runtime Enviroment (JRE).

Before attempting this exercise make sure that you have copied the code in the preceding examples and got the servlets up and running.

Create a HTML file with a form in it. Ask some multiple choice questions in the form. Write a servlet that processes the answers and returns a web page with the results of the test. Show the correct solutions for all answers that were answered incorrectly. Use the GET method to send data to the servlet.

Note: Put the compiled class files in %Tomcat_Home%\webapps\jjolt\WEBINF\classes directory and HTML files in %Tomcat_Home%\webapps\jjolt\html directory. In order to run the servlet, you need to add servlet entry in web.xml file. The web.xml file is %Tomcat_Home%\webapps\jjolt\WEB-INF. Once you have completed the exercise, zip all the files and submit them for review.

Installing JavaThe first step towards your first application is downloading Java, we are going to use the Sun Microsystems J2SE 5.0 JDK Visit the following page click on 'Download JDK 5.0 Update X' where X is the latest version. http://java.sun.com/javase/downloads/index_jdk5.jsp You will need to agree to the license terms and select your platform.

It will also be a good idea to download the documentation from the same page and install it locally because you are likely to be using it a lot!!!

Don't worry about downloading NetBeans, J2EE or the source code.

Once you have downloaded it, run the executable to install the JDK.

Your EnviromentThe next step is to ensure that you can use Java from your command prompt. You need to make sure that the folder containing the Java executables is in your 'PATH' enviroment variable. To test whether it is there already do the following: 1. Open a Command Prompt Window by clicking Start, going to All Programs the Accessories then clicking Command Prompt. 2. type java -version 3. if you see java version "1.5.0_04" or similar then everything is fine, if not continue with the following steps. 4. right-click on My Computer on your desktop and choose Properties. 5. click on the Advanced tab then click Enviroment Variables. 6. check in the list of variables (user and system) for a variable called 'JAVA_HOME', if it doesn't exist add it to the system variables. 7. ensure that the value of the JAVA_HOME variable is the path to the directory where the you installed the JDK e.g. C:\Program Files\Java\jdk1.5.0_04 8. check in the list of variables (user and system) for a variable called 'PATH', if it doesn't exist add it to the system variables. 9. add ';%JAVA_HOME%\bin' to the end of the value of the PATH variable. 10. now close the command prompt and try again and you should see java version "1.5.0_04" or similar. The next step is ensure that the Java executables can find your classes. We will use another enviroment variable to hold this information. 1. using windows explorer create a new directory where you will store your code e.g. c:\java_code 2. right-click on My Computer on your desktop and choose Properties. 3. click on the Advanced tab then click Enviroment Variables. 4. check in the list of variables (user and system) for a variable called 'CLASSPATH', if it doesn't exist add it to the system variables. 5. ensure that the value of the 'CLASSPATH' variable is the path to the directory you just created You should now be ready to write your first application. You may need to refer back to this section if everything doesn't go to plan.

Your First ApplicationThere a tradition amongst courses, books etc. that teach programming that the first program you write simply prints out "Hello World" to the screen. We will stick with that tradition. Follow the steps below to write, compile and execute your first Java Application and then we come back and review what we did. 1. Open Notepad 2. Copy and paste the following code into Notepad: package firstapplication; public class HelloWorld{ public static void main(String[] args){ System.out.println("Hello World"); } } 3. Save the code in a file call HelloWorld.java in the directory c:\java_code\firstapplication 4. Open a Command Prompt window and change to the directory c:\java_code 5. Type javac firstapplication\HelloWorld.java and press enter (you should just get a blank line - no errors). 6. Type java firstapplication.HelloWorld and press enter. You should see Hello World. Congatulations, you have just written your first Java application. We'll review what we did in the next section.

What just Happened?That wasn't too hard was it! The first thing you need to know is that every line of java code ends in a semicolon. This means that you can make your code more readable by breaking it over several lines without effecting the way it works or causing errors.

You will have probably already noticed that there are exceptions to the semicolon rule. Most Java code is devided into blocks. A block is one or more lines of code surrounded by braces (or curley brackets). The only lines of code that don't end with semicolon are lines that begin or end a block. Our Hello World application contains two blocks, the first one is a class identified by the code public class HelloWorld. This block contains a second block identified by the code public static void main(String[] args). This second block is a method (also known as a function). The function contains a single line of code: System.out.println("Hello World"); As we known, Java is an Object Oriented language, that means that every line of code you write will either define part of, or interact with at least one, object. System is an object that is provided as part of the JDK. Out is actually another object that is itself a property of the System object and finally println is a method within the out object. This method expects one argument - a piece of text (a String object). You will notice that both our class and our method are prefixed by the word public. This is how you can control whether or not other objects can access your objects and methods, you will learn more about this later. Before we go any further it is important to understand a couple of definitions. Class - A model, template or blueprint for an object. Object - An instance of a class. To understand this imagine you have a class called Car. The Car class is only a blueprint but if you create an instance then you would have an object representing a car, you could then set the make, model and colour properties to make a red BMW 3 series. You could then create other instances of the Car class and set the make model and colour of each one without affecting the others. Java also provides a means to manipulate the template itself rather than each instance. These properties and methods are identified by the key word static. Our main method is static, this means that the Java Virtual Machine does not need to create an instance of our class before it calls our methods.

The key word void simply means that our method does not return anything to the code that called it. You will notice that our main method can actually be an argument (or parameter). Arguments are defined by two words, the first word specifies what type of object the argument must be and the second word is the name that will be assigned to argument, we would then be able to use the name to reference the argument from within our code. The square brackets [ ] after the type indicates that our method actually expects an array of String objects rather than just one. We'll discuss arrays later. The only line we haven't discussed is the first one! package firstapplication;. When developing applications you may well end up with hundreds or even thousands of classes. To keep them organised we can organise our classes into packages and sub packages these packages relate directly to (and must be the same as) folders within your operating system. The name of the class must also match the name of the file it is in. For example a class called SecondApplication in a the package com.jjpeople.training must be declared the the file com\jjpeople\training\SecondApplication.java The naming of files, folders, classes and packages is important. if they don't match your code will not compile. We used the javac executable to compile the class, you may have noticed that a file with the extension .class was created in the same folder as your java file. We then used the java executable to run the application. Here's a tip for you. There are a lot of things that can go wrong even with the smallest of applications. Whilst this application is working we now change some things (one at a time) like the package, class or method names and try compiling your modified code. Obviously it is going to fail but make a note of the errors you get and what caused, that way if you have problems in the future you may recognise the error and know where to start with fixing it. One last thing before we move on. how did the java executable know which method to call? We specified the class from the command prompt but at no point did we specify which method to call. Well every java application always starts with the same method, only the class you use to start your application need have it but every application starts with the method public static void main(String[] args).

Java BasicsSo you have written your first application but there is a long way to go. The next few sections will guide you through the basic building blocks of most applications. There is a lot to take in and you may find it easier to piece it all together by reading the ahead a few sections and coming back to re-enforce your understanding

Class LibrariesAs you know Java is an object orientated language and that means you are going to need objects for more or less everything you do. We used three objects in our one line hello world application. Imagine you want to write some text into a file and save it, you will need an ojbect to hold the text but you also need an object that represents the file. Java would be pretty hard work if you had to write the classes that these objects are instances of. Obviously you don't need to write all these classes they and many more are provided as part of the JDK. The J2SE 1.5.0 JDK comes with 3279 public classes that you can use within your applications, obviously you can't hope to learn the names and features of all of them but one of the biggest parts of learning Java is getting to know more or less what is available to you otherwise you will spend your life re-inventing the wheel. Of course Sun provides extensive documentation on these classes. If you didn't download and install it, you can find it at: Java 2 Platform Standard Edition 5.0 API Specification http://java.sun.com/j2se/1.5.0/docs/api/index.html

API is another term you will come across a lot. API stands for Application Programming Interface. The interface basically means 'what you can see', a mobile phone for example has a lot of compexities inside but the interface is quite simple. An API is the interface to a class or library of classes available for programming applications. With this many classes in one API you can see the benefit of packages. It is a good idea to read through the list of packages and their descriptions on the API Specification home page even if it doesn't all make perfect sense at the momment.

JavaDocsThe API documentation you reviewed is known as JavaDoc. This is the standard way of documenting Java code. Documenting your code is vital, the manager of every project you ever work on will tell you that too. If you develop an application for a bank for example and months after the project has finished and you have moved on the bank brings in another developer to add a new feature, if you have not documented your classes they could spent weeks trawling through you code trying to understand it. Many project manager use automated tools that inspect every class to ensure it is documented. For this reason we are going to insist that every class you write as part of this course is documented using JavaDoc. Any exercise solution that you submit with code that is not documented will be rejected as incomplete. Don't worry, it is not hard and will soon become second nature. To demonstrate this we will JavaDoc our first application. JavaDocs are actually generated from comments you add to you code as followspackage firstapplication; /** * Simple application that writes * Hello World to the * Standard Out * * @author Dave Finch */ public class HelloWorld{ /**

* This is the method that writes * Hello World to the * Standard Out * * @param args - An array of string arguments * supplied on the command line */ public static void main(String[] args){ System.out.println("Hello World"); } }

In Java you can add a comment on a single line by starting that line with two slashespublic static void main(String[] args){ //this is a comment on a single line System.out.println("Hello World"); }

Or over multiple lines by starting with slash star and ending with star slash, you can put anything you like in between.public static void main(String[] args){ /* this is a comment spread over two lines */ System.out.println("Hello World"); }

JavaDoc comments simply start with two stars instead of one and have a star begining each line. This should be placed before your class declaration and every method. To generate your documentation do the following: 1. open a command prompt window at the folder containing your firstapplication package (c:\java_code) 2. execute the command javadoc -d docs firstapplication The -d docs specifies where to generate the documentation and firstapplication specifies which package to generate the documentation for. You should now have a new folder containing your documentation. open index.html to view it. This is the most basic usage of the javadoc tool. It is actually very powerful, for full documentation on it visit

Javadoc 5.0 Tool http://java.sun.com/j2se/1.5.0/docs/guide/javadoc/index.html

Third Party LibrariesThe libraries that come with the JDK are extensive but by no means exhaustive. The great thing about the JDK is that it is free (unlike other development enviroments like Microsoft's Visual Basic .Net). Another good thing about Java is that is cross platform and very easy to package and distribute small libaries or entire applications. As a result a vast array of Java libraries or API's available for free. If you are developing an application then chances are you can use some of these libraries and save a lot of time and money. Making good use of the tools available to you is an important part of being a good Java developer and we will be introducing you to several different libaries throughout this course. It is important to remember that not everybody wants to give away their hard work and even if they do, the license terms will vary. Always respect the the license terms and never use a third party API without checking with your project manager first.

Primitive TypesAs we mentioned previously, you are going to need objects for more or less everything you do. But not absolutely everything. A fundamental part of the Java language are Primitive Types (or Primitives for short). Primitives are the eight basic data types that everything else is built from. They are not objects. Primitives do not have properties or methods can only be used to one value of their own type. When you use primitives they are automatically initialised to a default value and can't be empty (or null). The primitive types are boolean, byte char, short, int, long, float and double. A chart showing what can be store in each primitive type and how much memory they use can be found here:

Language Fundamentals - Primitive Types http://www.janeg.ca/scjp/lang/primitives.html

It is important to note that for each primitive there is class that allows you to create objects that can be used to store the same value as their associated primitive and also provide some useful utility methods but they are not the same. The classes have the same name as the associated primitive but with the fist letter capitalised, with the exception of int and char which are actually abbreviations of their full names Interger and Character. As a general rule, if a primitive meets your needs then you should use it, only if it doesn't should you use an object.

Input and OutputMost applications handle data in some way, shape or form and when you have data the needs to be way off passing the information into the application and getting it out again. Imagine a calculator that had no way to enter numbers or view the result. There are numerous different ways of getting data in and out including files, databases or over a network but the most basic way of getting information in and out of your application is using your keyboard and the command prompt on your monitor (known as the console). Transfering data between your application and any of these locations in known as input and output or I/O. Java has the concept of standard input and output device where it will send errors, for example. By default the standard input devices are your keyboard and your console. over the next few sections we will experiment with standard I/O.

Printing OutputIn our first application we printed 'Hello World' to standard out but we didn't explain what happened in any detail. Underpinning I/O in Java is the concept of streams. When watering your garden it is a lot less hard work if you use a hose pipe to transfer the water from one end of the garden to the other than if you were to use a watering can. Streams follow the same basic principle to move data from one place to another.

To better understand this, read the following article. The Standard I/O Streams http://scv.bu.edu/Doc/Java/tutorial/java/system/iostreams.html We'll consolidate what you have just read with an example after you have had an intro to reading input.

Reading InputReading input is a little more complicated because there is no such thing as System.in.readln(). we need to make use of a couple of classes from the java.io package to achieve the desired result. Read the following article Reading input from console in Java http://www.ericsson.com/mobilityworld/sub/open/technologies/open_development _tips/docs/odt_reading_input_console_java If you tried to run the example in this article you will know that it simply prompts for input from the console and echos it back to you (unless you typed 'ok' or just pressed enter). The article is actually from Ericsson and targets people writing mobile phone software but because Java is cross platform it applies equally well to us. Although we will be covering all the features used in the code later, it is worth talking you through what is actually going on. 1. The first line of code - import java.io.*;- lets the compiler know what classes it needs to import and make available to our code. This statement imports all the classes in the java.io package. 2. The code block beginning while(true) is actually an infinite loop. It is only the break statement that causes the loop to end. 3. String objects can be created implicitly. For example System.out.print("ECHO< "); actually creates a new String object containing the value 'ECHO>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension. The bitwise & operator performs a bitwise AND operation. The bitwise ^ operator performs a bitwise exclusive OR operation. The bitwise | operator performs a bitwise inclusive OR operation.

The following program, BitDemo, uses the bitwise AND operator to print the number "2" to standard output.class BitDemo { public static void main(String[] args) { int bitmask = 0x000F; int val = 0x2222; System.out.println(val & bitmask); // prints "2" } }

Making DecisionsWe have already exposed you to the if statement but to expand on what you have figured out we'll go through the decision making options.

The TestThe most important part of any decision is the actual test. The test is a comparison that evaluates to either true our false.

if()...elseif and else are both statements that begin blocks of code so are usually followed by an open brace but as you will remember, the braces are only required around a block if it contains more than one statement. if(a = b){ System.out.println("a equals b"); }else{ System.out.println("a doesn't equal b"); } The code above will function exactly the same as the code below. if(a = b) System.out.println("a equals b"); else System.out.println("a doesn't equal b");

Some project managers prefer the braces to be left in your code even if there is only one statement because it is considered more readable.

If statements can be chained together at infinitum as follows. if(a > b){ System.out.println("a is greater than b"); }else if(a > c){ System.out.println("a is greater than c"); }else if(a > d){ System.out.println("a is greater than d"); } But the code above is not the same as the code below because in the code above only one condition can apply but in the code below all the conditions to be true. if(a > b){ System.out.println("a is greater than b"); } if(a > c){ System.out.println("a is greater than c"); } if(a > d){ System.out.println("a is greater than d"); }

Conditional ExpressionsJava provides support for you to combine a logical test and an assignment into a single statement as follows. System.out.println("a is " + (a