CompSci-61B Lecture Topic 1
Introduction To Java

Instructor: Prof. Robert Burns

Ref: Carrano ch.1, 2, 3, and App. A

Java SE
released in 1995 by Sun Corporation
suitable for cross-platform, networked apps
C/C++ - like syntax
uses a "virtual machine" execution layer
  compile once, run anywhere

Java Logistics
programmer edits ".java" files
store files in organized subdirectories
compile from command line (or IDE)
compiler creates ".class" file(s)
apps typically involve multiple ".class" file(s)
  archived into ".jar" file for convenience

Demo: Hello, World
edit HelloWorld.java:

public class HelloWorld
{
  public static void main(String[] argv)
  {
    System.out.print("Hello!");
    System.out.print(" ");
    System.out.print("My name is ");
    System.out.println("Robert Burns");
  }
}
main is the container for statements
  to be executed by the program
System.out.print sends output to console
System.out.println also skips to next line

implementing packaging:
add first statement in the file:
  package compsci61b.intro;
  ...so save file to subfolder:
  compsci61b/intro;

compile command:
  javac compsci61b/intro/HelloWorld.java
run command:
  java -ea compsci61b.intro.HelloWorld

implementing jarring:
archival command:
  jar cf lab1a.jar compsci61b/*
run-from-jar command:
  java -ea -cp lab1a.jar compsci61b.intro.HelloWorld

Values And Variables
values: differentiated as numeric or text
numeric values: differentiated as:
  whole number (e.g. 0, 100, -99)
  floating point (e.g. 3.14159, 0.0, 0.000001, -40.0)
text values: differentiated as:
  single-character (e.g. 'A', 'a', '7', '@')
  any-length (e.g. "Hello", "UC Berkeley")

variables: addressable memory locations for storing values
must be declared with "data type" and unique identifier (e.g.:)
int age; | double gpa; | char grade; | String name;
not defaulted: must assign values (e.g.:)
age = 21; | gpa = 4.0; | grade = 'A'; | name = "RB";
variables can be output, manipulated, and replaced

Statements and Expressions
output statement: System.out.println("age is " + age)
declaration statement: int age;
assignment statement: age = 21;
assignment upon declaration: int age = 21;

numeric expressions: arithmetic and function calls (e.g.:)
  + - * / Math.sqrt(...) ++ --
text expressions: concatenation (e.g.: +)
shorthand statements: age -= 3;
  hello += ", World";

Comments
using // as statement or append to statement
using /* */ for comment block & debugging

Boolean Variables
declaration statement: boolean found;
assignment statement: found = true;
assignment upon declaration: boolean found = false;

Logic Blocks

if (age >= 21)
{
  System.out.println("old enough to vote"); 
} // end if  <- just a comment
else, and else if clauses
logical expressions (not for String variables)
  operators == != < > <= >= !

Arrays And Repetition Blocks

int[] age = new int[100];
for (int i = 0; i < age.length; i++)
{
  if (age[i] >= 21)
  {
    System.out.print("person #" + i)
    System.out.println(" is old enough to vote"); 
  } // end if  <- just a comment
} // end for  <- just a comment
while, do-while, and for-each structures
processing, counting, and boolean search loops

Assertions
assert name != null;
requires -ea flag in run command

Objects And Reference Variables
"Hello" is an object
String s; : "s" is a reference to an object
s = "Hello"; refers "s" to the object "Hello"
unlike int, double, char, and boolean
  any-length text requires two memory locations:
    one for the text itself
    another to store the memory location of the first

Consistency alternatives:
Integer, Double, Character, and Boolean

null references:
  for ref vars that refer to nothing (yet)
    e.g.: s = null;
  memory leaks and "garbage collection"

creating objects: e.g.: new String("Hello") -- an expression
  with assignment: s = new String("Hello");
  assignment upon declaration: String s = new String("Hello");

arrays of reference variables
.equals(...) and.compareTo(...)
  e.g., s.equals(t) or answer.equals("YES")

Programmer-defined Objects
"object-oriented programming" and "encapsulation"
a "class" file: blueprint for building an object
object contents: private data &: public interface
private data: observable/measurable attributes of an object (e.g.:)
  private String name;
public interface: actions that observe or modify attributes
  mutators: actions that modify
  accessors: actions that observe
examples: Animal and Student classes (lab 1c)
  new Animal() -- expressions that...
  new Student() ...create objects
  Animal a; -- reference variables...
  Student b; ...to track objects
package access and the import statement

Object Construction
default values for private data:
  object references are null
  numeric values are zero
  "constructors" override defaults

Object Actions
appear as "methods" in class: code containers (e.g.:)

public void setName(String name) // a mutator
{
  assert name != null; // always expected to be true
  this.name = name; // transfer reference to private data
}

public boolean isValid() // an accessor
{
  boolean result = false; // assume this as default
  if (name != null)
  {
    result = true; // changed my mind!
  }
  return result;
}
the special toString accessor

Constants
value shared by all objects of a class (e.g.:)
private static final int INITIAL_ARRAY_SIZE = 10;
  uppercase by convention

Testing Programmer-defined Classes
validating public interface with test.java
include main method in the class:
  create objects of the class
  exercise all methods in public interface
  output results to console

Using Programmer-defined Objects
put ".class" files into a "jar" (".java" too, for doc)
attach jar to compile command: -classpath mystuff.jar (e.g.:)
  javac -classpath mystuff.jar cs61b/anApp.java
  for more than one jar, use ";" delimiter
attach jar to run command: -cp mystuff.jar (e.g.:)
  java -ea -cp .;mystuff.jar cs61b.anApp
    XP uses -cp .; and UNIX uses -cp .:
or if main class is also in a jar:
  java -cp anApp.jar;mystuff.jar cs61b.anApp
  it's time to drop the -ea

Applying Java To Data Structures
object is a "data structure" -- a collection of values
private data is the values, plus overhead (e.g., track #of values)
public interface: mutators
  public boolean add(...)
  public ... remove(...)
  public void clear()
  public boolean replace(...)
public interface: accessors
  public ... getEntry(...)
  public boolean contains(...)
  public int size()
  public boolean isEmpty()
  public boolean isFull()
  public String toString()

Why Not Be Happy With Arrays?
arrays do it all -- why go beyond?
here's why:
  speed (how long operations take)
  size (memory requirements)
  ease of programming (array management can get messy!)

The Array Alternative: Linked Structures
can be better choice than arrays because:
  size: no wasted space
  insert: easy and fast


Checklist for compiling and running in Java on Windows XP
  1. Install Java Compiler: Go to http://java.sun.com/, under "Popular Downloads:" click "Java SE". In the box labeled "JDK 6u1" click the "Download" button. On the "Java(TM) SE Development Kit 6 Update 1" page, click "Accept License Agreement". In the box labeled "Windows Platform - Java(TM) SE Development Kit 6 Update 1" click "Windows Offline Installation, Multi-language" to download and run "jdk-6u1-windows-i586-p.exe", accepting all defaults. Delete "jdk-6u1-windows-i586-p.exe" when you are finished with the installation.

  2. Prepare Java Compiler For Command-line Compiling: Open Windows Explorer (under Start->All Programs->Accessories) and navigate to "C:\Program Files\Java\jdk1.6.0_01\bin". You should see these files: java.exe, javac.exe, jar.exe, and others. In the "Tools" menu choose "Folder Options...", click the "View" tab, and deselect "Hide extensions for known file types". Close Windows Explorer.

    Open Notepad (under Start->All Programs->Accessories) and enter 3 lines of text:

    @echo off
    path=C:\Program Files\Java\jdk1.6.0_01\bin;%path%
    set classpath=

    Save the file in your "c:\windows" folder as "java6.bat". Use quote marks around the filename in the "Filename:" box when saving the file.

  3. Get the JNotePad2 Editor: Go to the class website and download the "JNotePad 2 Code Editor" as JNotePad.jar onto your desktop or quick launch bar. No futher installation is required -- just double-click the file's icon to run JNotePad.

  4. Get the Hesky Pad Editor (for use with an SSH client): Go to the class website and download the Pad Editor's installation file. Run it to install Pad, and delete it after installation is completed. The first time you run Pad, deselect the checkmark that causes user tips to show every time Pad starts. In the "View" menu, deselect "Clipboard" -- all you need are "Toolbar" and "Status Bar". In the "Options" menu select "Options". Click the "Editor" icon, and select "Display tabulators as spaces, replacing tabs with 2 spaces. Click the "Associations" icon, and add JAVA as an association. Now, when you double-click a .java file, it will load in Pad. So to load it in JNotePad instead, open JNotePad first, and drag/drop the .java file into JNotePad's window. Click the "Ok" button to close the popup window, and close Pad.

  5. Compile and Run: Open Command Prompt (under Start->All Programs->Accessories) and navigate to the folder that contains your "compsci61b" folder, where your files for this class will be stored. Enter the command "java6" to prepare the command-line compiler. (Use the command "cd.." to navigate to the root of a drive, and "cd xxx", e.g., to navigate into a folder named "xxx". Continue to use "cd {subfoldername}" to drill-down through the folder structure. To change to another drive, use the command, e.g., "d:".) Now you can enter compile and run commands.

    To avoid retyping any commands, use the up and down arrows to cycle through previously-entered commands, or press the F7 key for a menu of previously-entered commands.


Checklist for using SSH in Windows XP
  1. Install SSH Secure Shell: Go to the class website, and click "SSH Secure Shell". Then download and install the "SSH Secure Shell 2.4 for Windows" (SSHSecureShellClient-3.2.9b283.exe), accepting all defaults. Delete "SSHSecureShellClient-3.2.9b283.exe" after installation is completed.

  2. Firewall Issues: SSH Secure Shell uses port 22. If your firewall is blocking port 22, make an exception for it for TCP/IP access. Or just turn off your outgoing firewall.

  3. Setup a Profile: Start SSH Secure Shell with the "SSH Secure Shell Client" icon. Click the "Profiles" icon, and select "Add profile...", and type a label to identifly your connection -- e.g., "cs61b". Click the "Profiles" icon, and select "Edit profile...", and choose your new connection. For "Host name", use "solar.eecs.berkeley.edu" (or whatever URL was provided to you by the TA in lab). For "User name", use "cs61b", and click the "Ok" button to save the profile.

  4. Connect to the UNIX Server: Click the "Profiles" icon, and select your profile. At the password prompt, enter the password given to you for your student account. You should see a window and a prompt. If you can enter the command "javac" and see some output about possible options, you are doing it right!

  5. Share files with the UNIX Server: With the "SSH Secure Shell" running, use the "Window" menu's "New File Transfer" option for a window that will let you drag and drop files between the UNIX server and your local computer.

  6. Editing and Compiling: It's easier to edit files directly on the server, rather than to edit them locally and transfer them before every compile statement. Right-click over any remote file and choose "open" from the popup menu to open the file for editing. This downloads a copy of the file to your temporary file folder -- you actually edit this copy, and when you save, the saved copy gets copied back to the server over your old copy.

    Enter your compile and run commands on the UNIX comand line in the SSH window. To avoid retyping any commands, use the up and down arrows to cycle through previously-entered commands.

  7. Logging Off: Don't just close the "SSH Secure Shell" window -- enter the command "exit" first, so that the server does not keep your session open. This will save server resources for others to share after you are done.


Checklist for compiling and running in Java on Apple Mac OS X
  1. Verify Java Compiler Installation: OS X should already have Java SE installed. Start the "Terminal" application -- use Spotlight to find it, if you have to. Enter the cammand "javac" to verify that the compiler is available, and the command "java -version" to see the version number. If the version is 1.5 or higher, it's Java SE.

  2. Get the JNotePad2 Editor: Go to the class website and download the "JNotePad 2 Code Editor" as JNotePad.jar onto your desktop or quick launch bar. No futher installation is required -- just double-click the file's icon to run JNotePad.

  3. Get the TextEdit Editor (for use with an SSH client): Start the "TextEdit" application -- use Spotlight to find it, if you have to. In the "Format" menu, make sure that the "Make Rich Text" option is showing -- if it is the "Make Plain Text" option, select it. Unfortunately, TextEdit wraps text -- so use shorter lines and wider windows when editing.

  4. Compile and Run: Enter compile and run commands in the Terminal window. To avoid retyping any commands, use the up and down arrows to cycle through previously-entered commands.


Checklist for using SSH in Apple Mac OS X
  1. Install SSH Secure Shell: Go to the class website, and click "SSH Secure Shell". Then download and do a full install of "XonX" (XFree66_4.3.0.dmg) from SourceForge.net, accepting all defaults. Delete "XFree66_4.3.0.dmg" after installation is completed.

  2. Setup a Profile: Start SSH Secure Shell. Click the "Profiles" icon, and select "Add profile...", and type a label to identifly your connection -- e.g., "cs61b". Click the "Profiles" icon, and select "Edit profile...", and choose your new connection. For "Host name", use "solar.eecs.berkeley.edu" (or whatever URL was provided to you by the TA in lab). For "User name", use "cs61b", and click the "Ok" button to save the profile.

  3. Connect to the UNIX Server: Click the "Profiles" icon, and select your profile. At the password prompt, enter the password given to you for your student account. You should see a window and a prompt. If you can enter the command "javac" and see some output about possible options, you are doing it right!

  4. Share files with the UNIX Server: With the "SSH Secure Shell" running, use the "Window" menu's "New File Transfer" option for a window that will let you drag and drop files between the UNIX server and your local computer.

  5. Editing and Compiling: It's easier to edit files directly on the server, rather than to edit them locally and transfer them before every compile statement. Right-click over any remote file and choose "open" from the popup menu to open the file for editing. This downloads a copy of the file to your temporary file folder -- you actually edit this copy, and when you save, the saved copy gets copied back to the server over your old copy.

    Enter your compile and run commands on the UNIX comand line in the SSH window. To avoid retyping any commands, use the up and down arrows to cycle through previously-entered commands.

  6. Logging Off: Don't just close the "SSH Secure Shell" window -- enter the command "exit" first, so that the server does not keep your session open. This will save server resources for others to share after you are done.


Checklist for compiling and running in Java on UNIX and Linux
  1. Verify Java Compiler Installation: Some installations of UNIX and Linux OSs already have Java SE installed. Enter the command "javac" to verify that the compiler is available, and the command "java -version" to see the version number. If the version is 1.5 or higher, it's Java SE.

  2. Get the JNotePad2 Editor (X-Windows only): If you have a GUI interface, you can use JNotePad. Go to the class website and download the "JNotePad 2 Code Editor" as JNotePad.jar onto your desktop or quick launch bar. No futher installation is required -- just double-click the file's icon to run JNotePad.

  3. Compile and Run: Enter compile and run commands. To avoid retyping any commands, most OSs let you use the up and down arrows to cycle through previously-entered commands.


[ Home | Contact Prof. Burns ]