(syllabus and calendar)

Ch. 1 Java Fundamentals
pp. 7-31

examples1-spring2014.zip

Session 1

Java APIs, the class libraries - http://docs.oracle.com/javase/7/docs/api/

Concrete example of a Java program

Why Java?

Major Releases of Java

What is Java Programming?

Applications, Applets and Servlets

Java has nothing to do with JavaScript

Java compared to C and C++

Java and C#

Platform Architecture

New Features of J2E 5.0

An object is an instance of Class

Language tokens and parsing

Names for variables versus class names

Syntax and reserved words

Java class libraries - built-in core APIs

OOP = encapsulation + polymorphism + inheritence

Demonstration of a Java program

Compiling and running

PATH and CLASSPATH (often important for getting set up)

Links


Quiz

Homework Assignment Preparation and Link


Java APIs, the class libraries - http://docs.oracle.com/javase/8/docs/api/

This is the reference information about the functionality already available to you as you write your programs.


Concrete Example of a Java program

The modulus operator returns the remainder of the division of the left operand by the right operand.

Floating point representation often reveals measurable errors.

The rounding issue affects modulus as well.


Why Java?

1991: The original concept for the "Oak" project that became Java was to be embedded in devices, such as television controllers (cable set-top boxes), vending machines and parking meters, what GE Software calls the internet of things and what Cisco calls the internet of everything.

1995: "Write Once, Run Anywhere" mean that Java bytecode is cross-platform, able to run on Macs, Windows, and Solaris. "Applets" are graphic user interfaces for HTML browsers, but they ran too slowly to become popular. By 1996, Adobe Flash provided a faster way to display graphics and animations. With the advent of mobile devices (tablets and smart phones), the mobile vision of write once, run anywhere was crushed in 2007 when Steve Jobs banned Java from iPhone: "Java’s not worth building in. Nobody uses Java anymore. It’s this big heavyweight ball and chain."

If Java was useless for Steve Jobs focusing on the end-user, for whom is it useful?

http://www.lifesoft.in/GEP/Image_GEP/ana2000010601.gif

For three tier (or n-tier) applications running across a network or the internet, Java is most useful for the middle tier. Imagine a Java application using a JBDC connection to database to issue a SQL query. The Java application then passes the data to a client tier that displays items from a sales catalog. The client tier might have JavaScript to make sure the customer's credit card number has no letters in it.

Client Tier HTML, JavaScript
Middle Tier Java, AJAX (asynchronous JavaScript and XML)
Data Tier SQL

Traditionally, software programs have been written in source code and then compiled into machine code that talks directly to the operating system that drives the microprocessor in the computer. This means that traditional programs depend on, and are bound to, a particular type of hardware (the microprocessor), a particular platform. Porting from one platform, or operating system, to other, is traditionally time-consuming and prone to errors. The Java platform is a virtual platform that mitigates this dependency by providing a model in which software is written and compiled, and can then be transmitted over a network and run anywhere by a fully compliant virtual machine. Whereas it is not practical for end-users of, say, a Windows machine, to add a Macintosh chip and motherboard to their laptop, it is feasible for a Unix, Linux, Windows, Macintosh, or even a hand-held personal assistant to install the application that provides a Java virtual machine (JVM). Now the internet becomes a viable distribution medium for programs that are intended to run on multiple platforms.

This model provides the additional benefit of heightened security, both because programs can be verified by the client's virtual machine after they have been transmitted over a network, and because the client's virtual machine can run programs in a secure "sandbox" that prevents certain destructive behaviors.

Furthermore, Java is a strongly typed language and has features to prevent invalid values and invalid types. For example, the famous internet security flaw known as "Heartbleed" -  http://en.wikipedia.org/wiki/Heartbleed -  stems from a protocol written in C that failed to provide "bounds checking", that is, to only share a portion of the internet user's memory that is within the appropriate limits. Insofar as Java prevents direct memory management, the flaw would not exist in Java. However, Java is not a fast as native code written in C, so there might be trade-offs between security and performance.

Software programmers have embraced the Java platform because it reduces the cost and time required to write and support software code. They are no longer required to rewrite software to function on different computers with different operating systems and microprocessors. Companies and organizations deploying applications favor Java technology because it minimizes the cost of purchasing or modifying different versions of software applications for the various types of computers and servers within their networks.

The promise of Java: http://java.sun.com/docs/books/tutorial/getStarted/intro/changemylife.html

Major Releases of Java

Types of languages
Object-oriented programming (OOP) Procedural Web scripting Page description Data description Database
Java, C++, SmallTalk, Objective-C (Apple), C#.NET (Microsoft)

Java-like languages:

C, Basic, Fortran, Cobol, Lisp*, Perl scripting, Python scripting, Tcl (prototyping), PL/SQL, Natural

* Lisp introduced automatic garbage collection in 1959

** Perl and Python have OOP extensions

JavaScript,
VBScript, PHP (server-side)
HTML XML, XHTML SQL

The Runtime

The Jave Runtime Environment (JRE) is for users who only need to run existing Java bytecode and do not write the code. http://java.sun.com/j2se/1.4/  The Java Runtime Environment consists of the Java virtual machine, the Java platform core classes, and supporting files. It is the runtime part of the Java 2 SDK, but without the development tools such as compilers and debuggers. (The JRE download is only 8 MB, compared to 38 MB for the SKD download.) The installer for certain programs might install the runtime environment so that end users can run the application.


What is Java Programming?

Java programming is the process of creating:

The Java platform is a target for software development, much as traditionally software developers targeted an operating-system or processor-based platform such as MacOS/Motorola, Windows/Intel, or Sun/Sparc.

To develop code for the Java platform, the software developer uses: 

Some people say JDK (Java Development Kit), and this is the same as the Java SDK (Software Development Kit).
However, the JRE (Java Runtime Environment) is a subset of the SDK for running Java programs that does NOT include development tools.

To run your code, you and whoever uses your code will need:


Applications, applets, servlets, and middleware

An application is software that runs on top of the operating system, has a specific purpose, and usually allows an end-user to interact. An example of an application is Microsoft Word. On the other hand, the software that runs your printer (a "driver") is something for the operating system or an application, rather than for the human user.

Applets ran in a browser, but are superceded by technologies like Flash

Java introduced the concept of applets, which were applications that ran inside of a web browser on the client computer. A web browser is an application. 

An applet was  a "safe" quasi-application that can only run inside of another, very specific application. Some of the key restrictions on an applet 

These restrictions are meant to give web surfers confidence to download applets from the web, even if the user does not know the company that created the applet.



Signed applets

If an applet provider registers a specific applet with a registration company, the "signed applet", if you accept it, can have access to your file system and the native operating system. This is called a "signed applet".   http://mindprod.com/jgloss/signedapplets.html#SIGNEDAPPLETS

Note: A Java application, like any application, does have access to your file system.

Java Plug-in

http://java.sun.com/products/plugin/index-1.4.html
The Java Plug-in allows you to run applets using Sun's Java 2 Runtime Environment, Standard Edition (JRE) instead of the web browser's default virtual machine. Sun's JRE provides a Java CompatibleTM environment for today's widely adopted web browsers. That means consistency and reliability when running applets.

The Plug-in can give the browser support for Swing. Swing is part of the Java 2 Foundation Class library that extends the Java 1 Advanced Windowing Toolkit (AWT) to provide new GUI components and features, better event handling, and selectable look and feel]

Unless Internet Explorer is used in conjunction with the Java 1.4 plug in, your users are limited to the functionality of Java 1.1  http://mindprod.com/jgloss/ie.html

Applets are no longer important because they were replaced by faster client-based technologies, such as Flash.

Servlets run on the server

http://java.sun.com/products/servlet/index.html
JavaTM Servlet technology provides web developers with a simple, consistent mechanism for extending the functionality of a web server and for accessing existing business systems to give them a web interface. A servlet can almost be thought of as an applet that runs on the server side -- without a face. Java servlets have made many web applications possible.

Middleware

Presentation Tier:
JavaScript for the end-user with a web-browser
(applet or signed applet also possible)
-------------------------
Middle Tier:
Java for the middleware,
controlling business logic and optimizing web services
-------------------------
Data tier:
SQL for the database (MySQL, Oracle, MS SQL Server)
[or, a no-SQL datastore, such as Apache Hadoop]

Java is ideal for middleware. An example of middleware is layer that controls how any kind of client browser can access data stored on any kind of data platform, such as Oracle on Solaris, MySQL on Linux, and SQLServer on Windows Server. Another example would be a layer that provides a uniform application programming interface for MIDI-based musical instruments to use sound cards, regardless of the sound card vendor.

Another example would be a database web service, written in Java, that allows an application written in .NET to submit a query that the web service then passes along to a database.

Java's platform independence allows organization to avoid the cost of porting when scaling up the middleware from a developer's laptop running, say, Mac OS, to a small server running, say, Windows Server, to a large cluster of robust servers running, say, Linux or Solaris.

JNI and OSGi

The following graphic shows the Java Native Interface (JNI) that allows native code (C or C++) to interact with bytecode. The OSGi Framework is a dynamic module system that provides a way to deploy a new version of a software module without having to reboot the container of the modules. One use case is to automate updates for the industrial internet, such as:

A popular integrated development environment (IDE) for Java, Eclipse, supports OSGi, as do Atlassian Confluence and Jira.


Java has nothing to do with JavaScript

JavaScript is a marketing misnomer because the weakly-typed JavaScript scripting language has nothing to do with the strongly-typed Java programming language. In 1995, Netscape wanted to capitalize on the name of Java so as to appear technologically advanced. Sun wanted support for Java to be built in to Netscape Navigator, which was the most popular browser at the time.

In 1996, Microsoft copied JavaScript, changed the name to JScript to avoid a lawsuit, and gave Microsoft Internet Explorer built-in support of JScript.

JavaScript is a limited tool to enhance a subset of the capabilities of an HTML browser. JavaScript can be used to open a new HTML browser window, to validate the data types of entries in an HTML form (credit card numbers should have no letters), and to cause a browser image to change when the mouse hovers over an existing image.

For performance, JavaScript runs on the web client, but web client computers suffer from vulnerability to security weaknesses inherent in JavaScript, including internet banking theft. http://en.wikipedia.org/wiki/JavaScript#Security

JavaScript can also be used in PDF documents.


Note: Google Android cell phones use a proprietary version of the Java Virtual Machine (JVM) named Dalvik, which is optimized for minimal use of memory and the battery -  http://en.wikipedia.org/wiki/Dalvik_virtual_machine


Java compared to C, C++

A computer platform is the combination of the operating system and the central processing unit (CPU). 

Examples of operating systems include 

Examples of CPUs include 

A standard, compiled application runs machine code that is specific for a platform. Machine code is the raw zeros and ones that a computer "chip" understands. If you want your UNIX application to run on Windows, for example, you must "port" the code and recompile it using a compiler that produces machine code that is "native" to the target CPU. Porting costs developer time and some platforms have different kinds of data types or a different number of bytes for the same data type.

Platform independence

Java code is different from standard, compiled code. You compile your Java source code into a special language, "bytecode", that a special application, the Java virtual machine (JVM), interprets. With one binary code (bytecode) for one virtual machine for all the operating systems, there is no need for porting. Each hardware platform, however, still needs an interpreter to convert the bytecode into native machine code.

The Java interpreter (java) is different from the "HotSpot" just-in-time (JIT) compiler. The interpreter interprets bytecode and makes application programming interface (API) calls into the native operating system, for example, calls to Win32API. The JIT compiler can improve performance with optimization capabilities that allow it to compile into native machine code parts that are most heavily used. 

The JVM is an application that emulates a computer. It translates Java bytecode into native machine code.

There is a JVM for Mac OS, UNIX, Linux, and Windows. This means that the same source code should be valid for multiple platforms. You do not need to "port" the application to another platform. It should be "write once, run anywhere", assuming there is a JVM for that platform.

There are even JVMs for smaller platforms, such as the PalmOS that runs on the PalmPilot.

Advantages and disadvantages of the Java platform compared to C++

Pro Con
Less likely to create careless bugs (memory leaks, pointer errors) performance is slow because of CPU-intensive interpretation or compilation of byte code into machine code
Relatively platform independent: "write once, run anywhere", which is particularly valuable if the server could be Unix, Linux, or Windows, and you don't which it will be vision is not fully realized
write once, debug everywhere
strict object-oriented model; cannot mix with procedural code, so coding is more straightforward  can use more CPU and memory (C++ can be optimized with lower-level code)
Dynamic linking: supports introducing new objects at runtime without recompiling everything [RMI (remote method invocation)] slower because of look up; mitigate with JIT compilation

For more on static versus dynamic linking: http://www.cpp.atfreeweb.com/StaticVersusDynamic.html


Java and Microsoft C#

From Sun's point of view, Java 1.4.1 is part of Sun's J2EE platform. C# is a Microsoft programming language that closely resembles Java. C# is for use in Microsoft's .NET platform, which relies on libraries of the Microsoft Windows operating system. Insofar as .NET has an intermediate language (IL) and a common language runtime, there is a something analogous to a JVM-like portability, but only within the Microsoft family of programming languages, such as Visual Basic, J# (Microsoft's version of Java), and C#, and only for use on Microsoft operating systems. Whereas the Java platform offers portability across operating systems, the .NET platform is an integration within Microsoft's "family" of languages. From Microsoft's point of view, .NET frees you from being confined to any one language, such as Java, and allows you to use whatever Microsoft language you freely choose. For example, VB.NET syntax might be most convenient for a developer of end-user applications and C# syntax might be a bit more familiar for the C++ developer working with pointers. However, all of the .NET languages actually have the same capabilities.

.NET source code in any .NET language >> IL (analogous to bytecode)  >> runtime interpretation to native code

For details, see http://genamics.com/developer/csharp_comparative.htm.

The virtues of Java (as in theory of C#): http://java.sun.com/docs/overviews/java/java-overview-1.html :
Simple


"Platform" Architecture

Sun defines three (3) Java platforms at http://java.sun.com/java2/whatis/:

http://java.sun.com/j2se/1.3/
The JavaTM 2 Platform, Standard Edition (J2SETM) has revolutionized computing with the introduction of a stable, secure and feature-complete development and deployment environment designed from the ground up for the Web. It provides cross-platform compatibility, safe network delivery, and smartcard to supercomputer scalability. It provides software developers with a platform for rapid application development, making it possible to deliver products to market in Internet time. It defies traditional software development and deployment models by delivering on the promise of cross-platform compatibility.

The Software Development Kit (SDK) is much more than a language. There are many convenient implementations you can use and customize in your applications.
The code provided for your applications is the application programming interface.
(You can think of APIs as "hooks" you can grab and use, without having to know the deepest level of Java, which is actually C++.)
The core APIs save you the work of "reinventing the wheel" and allow you to program at a higher level.
For example,

 

In the 1.4 J2SE, the JRE and the SDK include new core application programming interfaces (APIs), such as XML and Logging:
 http://java.sun.com/j2se/1.4/docs/relnotes/features.html

 

http://java.sun.com/j2se/1.5.0/docs/index.html is for the 1.5 version.


New Features in J2SE 5.0

http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html
The set of new features in the latest release of Java provide some conveniences. Perhaps they are an attempt to make Java easier to use for people who write code for Microsoft's .NET platform. 

Generics

An alterative to casting various objects to type Object. This alterative provides type safety. To enable this feature, the concept of a Collection has been expanded to support type checking.

"for-each style" loop

A convention way to iterate over all the items in a collection, such as an array. [pp. 172-178]
for(int x: nums) sum += x;

Enumerations

A convention way to work with a collection of constant values that require identifiers. This is an alternative to final variables such the set of constants are their own data type. The java.lang package now contains the Enum class.

Autoboxing

A convenience that automates the process of wrapping a primitive into its corresponding object type.
Integer myValue = 100; // wraps the primitive into its corresponding object type
int myInt = myValue; // automatically unboxes the object to its primitive

Static import
An expansion of the import statement that allows you to use the short name, rather than the full-qualified name, for a method or property that is static.
import static java.lang.System.out;
// now you can say
// out.println();
// instead of
// System.out.println();

varargs

variable length arguments to a method

metadata

Allows you to provide annotations for use in build management, such as marking a particular method as deprecated. Deprecated means outdated, and might be removed from a future release.


An object is an instance of a Class

Have you eaten Food today? No. No one has ever eaten Food. Go to McDonalds and tell the attendant, "I have Money and want to eat Food." You must specify a particular instance of Food, such as thisLukewarmMcHeartAttack, and pay a specific amount of Money, such as 99 cents.

A class is a recipe for making food objects.


The recipe does not define the shape or the material of the pie plate, so both of the following are valid instances.

class Food{}
class FastFood extends Food{}
class MacHeartAttackFastFood extends FastFood{}
// now, let's instantiate
MacHeartAttackFastFood myLukewarmMcHeartAttack = new MacHeartAttackFastFood();

Here is an instance of CookieMonster with an instance of Cookie.
CookieMonster sid = new CookieMonster(myChocolateChipCookie);

Similarly, have you ever heard the national anthem of the United States? No, no one has, not even the composer. Instead, various instances of HumanBeing have heard various instantiations of the class StarSpangledBanner performed on various instances of MusicalInstrumentOrHumanVoice.

It is the same song, regardless of who sings it and which key the performer uses. Therefore, even if the song were originally written to begin with the note "F" (or "fa"), any musician could play this wong without ever using that note. The song does not depend on any particular note, but rather a set of relationships between a set of notes. The composer merely creates a blueprint, but not the implementations.

The following blueprint is NOT an instance of the Golden Gate Bridge:

The following is an instance of Golden Gate Bridge insofar as it follows the blueprint:

If you were a sailor with a navy, you would already be familiar with the concept of classes of ships and submarines.
http://en.wikipedia.org/wiki/List_of_submarine_classes_of_the_United_States_Navy

Submarines of the United States Navy are built in classes, using a single design for a number of boats. Minor variations occur as improvements are incorporated into the design, so later boats of a class may be more capable than earlier. Also, boats are modified, sometimes extensively, while in service, creating departures from the class standard. However, in general, all boats of a class are noticeably similar.

Similarly, the Nimitz class of aircraft carriers share the following properties:

http://en.wikipedia.org/wiki/Nimitz_class_aircraft_carrier

The Soviet November class of Cold War submarines all had eight torpedoes that could be launched from a depth of 300 feet.

The following objects are instances of the class BettyCrocker, whose age fluctuates ordering to fashion:

Let us instantiate Betty Crocker, so she can greet us:

We only instantiated one Betty Crocker object, but any number can be created from the recipe or class:

By the way, the collection of objects pictured above might also be called an array of objects of type BettyCrocker.

I am an instance of the class HumanBeing.

Consider Santa Claus. Have you ever seen Santa Claus? No, you have only seen one or more particular instances or impersonations of Santa Claus.

Here, we create an instance of Santa Claus on Line 9. An "object" is an "instance" of a class.

An instance of a class inherits properties from that class. All objects of type Pizza have a crust and a topping:

A class is a type. NeapolitanPizza is a type of Pizza. Historically, it might be the original pizza. Properties of the class NeapolitanPizza are: roundishShape, bakedInWoodChipOvenForOnlyFiveMinutes, hasTomatoSauce, hasBasilLeaves, doesNotHavePepperoniOrPineapple, soldInNaplesItaly, isInexpensiveComparedToNewYorkPizza.

Remember, you cannot eat the class PumpkinPecanPie, only a physical instance of that class.

In this sense, a class is a recipe or template for creating an object, like this blueprint for a house:
http://www.varietybackyard.net/wp-content/uploads/2011/10/House-Blueprints-2.jpg

Do not confuse the plan with its implementation. A blueprint for a house or castle might be implemented in various materials. It would still be an instance based on that blueprint, that is, it would still be an object of that class, unless the class specified the material of which it was made.

 


Language tokens and Parsing

Tokens

A token is a "word" or "punctuation mark" in a language.

http://en.wikipedia.org/wiki/Token_%28parser%29#Token

Parsing

What is a parser? The part of javac that prepares your source code for compilation into bytecode, and that allows the debugger to alert you of possible problems.

v. parsed, pars·ing, pars·es
v. tr.
  1. To break (a sentence) down into its component parts of speech with an explanation of the form, function, and syntactical relationship of each part.
  2. To describe (a word) by stating its part of speech, form, and syntactical relationships in a sentence.
  3.  
    1. To examine closely or subject to detailed analysis, especially by breaking up into components: “What are we missing by parsing the behavior of chimpanzees into the conventional categories recognized largely from our own behavior?” (Stephen Jay Gould).
    2. To make sense of; comprehend: I simply couldn't parse what you just said.
  4. Computer Science. To analyze or separate (input, for example) into more easily processed components.

v. intr.

To admit of being parsed: sentences that do not parse easily.

When you invoke the javac compiler, it parses the tokens in your source code. The parser ignores the contents of comments as well as white space. Therefore, the following are the same:

When you name identifiers (variables, methods, classes), the characters must be contiguous (no spaces), cannot start with a numeral, and cannot include operators.

Convention for names

Make sure that you follow these conventions!

Let us identify the tokens that represent a class, a variable, and a constant.

 

Separators

CHARACTER NAME USE
;
semicolon to end a statement
.
dot operator to separate an object from one of its members (methods and properties) for the syntax object.member
( )
parenthesis to contain a list of parameters (or arguments) for a method;
to contain the condition in a control statement
{ }
curly braces to define a block of code
[ ]
brackets to declare an array and to contain assignments to an array

Key words and reserved words

You cannot use the following as identifiers in your code.

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html

true false null  
abstract double int strictfp **
boolean else interface super
break extends long switch
byte final native synchronized
case finally new this
catch float package throw
char for private throws
class goto * protected transient
const * if public try
continue implements return void
default import short volatile
do instanceof static while

One of the keywords is class. Here are four objects of type Beatle:

// construct Beatle objects by calling the Beatle constructor
Beatle ringo = new Beatle(drums);
Beatle john = new Beatle(leader);
Beatle george = new Beatle(leadGuitar);
Beatle ringo = new Beatle(bassGuitar);

Syntax and reserved words

When you use any language, whether it is a computer language or a human language, you have to follow the rules. The term "syntax" refers to the rules of word order and word combination. Some languages, like French, have a flexible syntax that lets you say "the chocolate good" as well as "the good chocolate". Other language are more rigid about word order. Java syntax is more rigid than, say, Perl syntax. 

For example, Java has certain "reserved words" that you use according to Java's syntax and semantics. The Hello World application consists almost exclusively of reserved words or predefined words (in bold):

public class HelloWorld 
{
  public static void main (String[] args)
  {
    System.out.println("Hello World");
  }
}

The only words that are not reserved words or predefined words are the three variables: 

Just as human languages have punctuation in addition to words, so Java has special symbols, such as the curly braces { }, parentheses ( ), the brackets [], the comma separator , the wildcard asterisk *, quotation marks " ", the forward slash /, the backslash \, the dot . and the semicolon ; that completes a statement.


Built-in libraries are called core APIs

The Java software development kit comes with many built-in methods. This Java environment includes these methods to support major types of functionality, such as security, XML, networking, and input and output. Having a rich set of pre-built methods and properties saves you time. Here's an example.

/* This program uses API introduced in 1.1.
   It tells you the language version of your Java.
   In my case, in United States English: en_US */

public class CurrentLanguage {
   public static void main(String[] args) {
   System.out.println(java.util.Locale.getDefault());
   }
}

Earlier, we saw that the String object has a method, length(),  for getting the length (number of characters) in the string.
An array has a property, length, that represents the numbers of elements in the array.

The Java platform offers predefined formatting for numbers: http://java.sun.com/docs/books/tutorial/java/data/numberFormat.htm

One student used the parseInt method of the Integer class to convert the strings of args[] into integers.

l

This is called conversion or type conversion. See Type Conversion.

Let's now take a tour of the API documentation: http://java.sun.com/javase/6/docs/api/

The Java platform specification lists the functionality that is available to a programmer out-of-the-box, without having to design, write, and compile low-level code.

Do not confuse the general concept of "interface" (a kind of abstract class) with the specific application programming interfaces (APIs) that are packaged with the SDK.

Core APIs are class and interfaces that are an integral part of (hence "core") the Java platform. We will look at the API documentation, and you will use some of the core APIs  in your code so that you do not have to write everything from scratch.


Object-Oriented Programming (OOP): encapsulation, polymorphism, inheritence

In Week 4, we will see how creating a class allows us to encapsulate logic where it belongs.

In Week 6, how a method or constructor can be overloaded to perform its task differently in different situations. Each version of the method or constructor is a form, and Java supports many forms, which in Greek is polymorphism.

In Week 7, we will take advantage of features of inheritence to make specialized objects and maximize the reuse of existing code.


Demonstrations of Java programs

We could follow along this set of demonstration programs, which introduces concepts from Chapter 2 (data types) and Chapter 3 (Program Control Statements):

http://www.herbschildt.com/getting_started_with_Java.htm

Hello World Code

public class HelloWorld 
{
  public static void main(String[] args)
  {
    System.out.println("Hello World");
  }
}

The following example shows that args in an array of type String.

Here, we use command line args with a for-each loop.

Explanation of each token for the parser to parse in this application:

This program illustrates all the tokens, including static, in the most concrete manner possible:

This program uses the Scanner class to make input and output relatively straightforward:

This program involves the standard input and output, also known as IO, which is less straightfoward than the Scanner class.

Note that the output can reveal lack of precision in an obvious way, which is probably a good thing.

A more complete program with fields, a constructor, a methods that return a value using the return keyword.

See also Lecture 2 on language tokens and parsing.

Sample Program

If there is no class that matches your classfile name, you get an exception.
D:\java\teachjava\spring2003\session1>java BadName
Exception in thread "main" java.lang.NoClassDefFoundError: BadName

/*
This is a simple Java program.
Call this file "Example.java".
*/
class Example {
   // Your program begins with a call to main().
   public static void main(String args[]) {
      System.out.println("This is a simple Java program.");
      }
}

Enclose multi-line comments inside /*      */
Put single-line comments after //

//This is a wordy Java program.
//Call this file "Wordy.java".
class Wordy {
// Your program begins with a call to main().
public static void main(String args[]) {
   int year = 2003;
   System.out.println("This is a wordy Java program.");
   System.out.println("This program uses the following:");
   System.out.println("public static void main(String args[]) {");
   System.out.println("The keyword public means this class is available for calls from outside the class.");
   System.out.println("The keyword static means no class is initiated,"
      + "\nwhich is good because I do not have a class to initiate.");
   System.out.println("The keyword void means this class does not return a value.");
   System.out.println("The keyword String means that args[] is of type String.");
   System.out.println("The variable name args[] refers to an array"
      + "\nbecause some programs take command line arguments.");
   System.out.println("The print method prints to the screen without a new line.");
   System.out.print("So the year value will appear on THIS line: ");
   System.out.print(year);
   }
}
To assign a value to a variable, use the assignment (=) operator, which looks an equals sign.
class Assignment {
   public static void main(String args[]) {
      int x, y; // variable declarations

      x = 100; // this assigns x the value 100
      y = 10;

      System.out.println("The value of x is: " + x);
      System.out.println("The value of y is: " + y);
      System.out.println("The product of x and y is: " + x*y);
      System.out.println("The dividend of x / y is: " + x/y);
      }
}
TIP: Do not confuse assignment 
  x = 4;
with testing for true
  if x == 4;
Can you find the bug?
class HelloWorldApp2 {
   public static void main(String[] args) {
   System.out.println("Hello World!); //Display the string.
   }
}
D:\java\124115\sessions\demos\2\HelloWorldApp2.java:3: unclosed string literal

Looping is fast


Formatting with character sequences \n and \t

Method call (preview)

We will explore methods more in Week 4 of the course. This is just a preview.


Let's see a different application that puts the array of command-line strings into action:

Command-line args

The output is:

args[0]: sky
args[1]: is
args[2]: blue
args[3]: 4
args[4]: you

In this application, whatever the user types after invoking java with the application identifier is stored into
the array of command line arguments. The for loop processes the array of command-line arguments.

String[] args

To make clear why the main method takes a parameter of type String array, let us make use of the string array.

It is best to write String[] args, but String args also works.

For consistency and simplicity, the string array is usually named args, but it is not a keyword or a reserved word, so its name (or identifier) can be something different.

Here's the same thing, but with a for loop to process multiple command-line arguments.

This source code must be in a file named CommandLine.java because the compiler expects the class identifier to indicate the class with the main method, that is, with the point of entry for execution.

Now, let's try to compile and run the program.

At the command line, I types a list of strings that the program stored in an array named applesauce.

What is an array? An ordered collection in which each item can be referred to by an index.

For example, an array of freeway lanes begins with the #1 lane. Here is a northbound array and a southbound array. We might think of the number of these lanes as the width of the freeway, and say it is 5-lanes wide, but in Java, we consider the number of elements as the length.

In a redundant array of independent disks, a RAID array of hard disks, we have a 1-based array, with the lowest index value being 1.
Each item in the array is of the same type (hard disk) and each item can store a different value (different data).


Should it be possible to "populate" this array of hard disks in various manners?
For example, can I have an array of hard disks in which Bay 5 is empty?
Can an entire array be empty of hard disks (or an array of freeway lanes be empty of automobiles) and yet still exist an array?

In Java, arrays are 0-based, that is, they begin with zero instead of one because binary counting begins with 0.
What is the capacity (or length) of the command-line String array?

A String is implemented as an array of characters (chars). An empty String is a String without any chars.
In CommandLine.java, can I have an empty string for one of my elements?

Now, let's run a program that does some arithmetic.

Finally, let's do arithmetic with input from the command line:

Note that this requires converting the command-line Strings into numbers.


Compiling and Running

Like other programming languages, you compile your Java source code (in a text file) by invoking a compiler that outputs compiled code.
In this case, the compiled code is called "bytecode", which is in a .class file. You can install the same .class file on multiple operating systems.

To enable platform independence, the Java platform inserts "interpretation" between the compiled code (.class file of bytecode) and the operating system's native machine code.
The Java interpreter, named java, converts compiled "bytecode" into machine code.

The Java interpreter executes bytecode within the Java virtual machine, a sort of virtual computer inside the computer.

Or, if you prefer to visualize the sequence as numbered steps:

STEP DESCRIPTION OUTPUT  NOTES
1 Write and save the source code file, which is a text file named after the class, such as MyClass.java .java  
2 Invoke the Java compiler, javac, and specify the .java file to compile:
javac MyClass.java
   
3 The compiler outputs a .class file of bytecode, such as MyClass.class .class Look in your directory for this
4 Invoke the Java bytecode  interpreter, java, and specify the .class file to interpret:
java MyClass
   
5 Java Virtual Machine interprets the bytecode and outputs native code for the platform (Windows, UNIX, or Macintosh)    
6 Operating system runs the native code    
7 runtime memory management: The JVM periodically checks for unreferenced code (garbage collection) to free memory for reuse   In C/C++, this logic must be built into the code

Case-sensitivity: homework1.java is not a valid name for a file that contains the Homework1 class. The Windows OS is not case-sensitive and does not know that it can overwrite the case dimension of a file name. But Java is case-sensitive.

Exception in thread "main" java.lang.NoClassDefFoundError: homework1 (wrong name
: Homework1)


PATH and CLASSPATH

When you download the Java development kit at
     http://www.oracle.com/technetwork/java/javase/downloads/index.html
write down the drive and path in which the installer installs the Java development kit (JDK), so that you can verify the installation and, if necessary, configure Java so that the following are available from the command line of a console window:

COMPILER set by PATH

The PATH system environment variable should point to the directory that has the java compiler (javac.exe), which is located in the the "bin" subdirectory of the installation directory for the JDK version.

For example, before the latest update became available, I went to my Windows Control Panel > System > Advanced > Environment Variables
and edited the path by adding a new entry:

;D:\java5\jdk1.5_01\bin

You will probably have a slightly different version number.

INTERPRETER uses CLASSPATH

The CLASSPATH variable is what the Java interpreter looks for to run a Java program, the bytecode in a .class file.
I want Java to be able to run whatever .class file I have in my current directory.
Therefore, I also created a new user variable, CLASSPATH, and included:

.;D:\java5\jdk1.5.0_01;D:\java5\jdk1.5.0_01\lib\tools.jar

Then I logged out (or rebooted), so the changes would take effect.


Setting the PATH and CLASSPATH on Windows XP

For VERSION 1.5.0 of Java

These directions also appear in your book
in the section "Before you Begin"

NOTE: If a command is given in quotes for you to type, DO NOT TYPE THE QUOTES

1.      Click on START (lower left)

2.      Under "Settings" click on "Control Panel"

3.      Switch to "classic view" (upper left) -- not "category view"

4.      Click on the "System" icon.

5.      Click on the "Advanced" tab.

6.      Click on the "Environment Variables" button (bottom).

7.      Highlight "PATH" (in the top window "User" not "System") and click the "edit" button.  

(Do not edit the "SYSTEM VARIABLES" because of the risk for the operating system.)

8.      Edit the "PATH" so it begins C:\Program Files\Java\jdk1.5.0\bin; (note: if you install Java into a different directory, you may need to change the directory from that listed above)

9.      For example, the full "PATH" on my computer is:
C:\Program Files\Java\jdk1.5.0\bin;C:\Program Files\SSH Communications Security\SSH Secure Shell

10.  After you have finished editing the PATH, click "OK".  You are done setting your PATH.  Now you have to create a new variable, called your CLASSPATH.

11.  Click on the "NEW" button below the top window.

12.  Under 'variable name' type CLASSPATH

13.  Under 'variable value' type  .  (yes, type a single period).

14.  Click OK.

15.  EXIT the control panel.

16.  Restart your computer.

17.  Test your installation by opening up a DOS window and verifying that both the commands "java" and "javac" are recognized.

Troubleshooting tips at http://java.sun.com/docs/books/tutorial/getStarted/problems/index.html


Links


Quiz: Session 1

  1. What is the file extension for source code?

  2. Source code is the output of the Java __p________ and the input to the Java __c______________.

  3. What is the file extension for byte code?

  4. Byte code is the output from the Java ____________ and the input to the Java __i_____________.

  5. True or false: First, Java source code is interpreted, and then it is compiled.

  6. Is the compiler included in the JRE or the JDK? What does the acronym JRE stand for?

  7. What does the acronym JVM stand for?

  8. What is the point of entry for program execution?

  9. What does the command javac invoke?

  10. What does the command java invoke?

  11. How many methods named main should a program have?

  12. What is args in HelloWorld?

  13. Is the source code extension required when invoking the compiler?

  14. Is the byte code extension required when invoking the interpreter?

  15. What is the difference between System.out.print() and System.out.println()?

  16. What must you type at the command line to launch a Java application with two arguments in the array of Strings that is passed to the main method? For example, to make HelloWorld write your first name and last name to the screen.