Starter code (in Java)
Welcome
Assumptions
Ability to run *NIX commands
In order to run Unix or Linux commands (collectively known as *NIX), you will need a UNIX terminal emulator:
- OS X users already have the Terminal app we will use for this purpose.
- Windows users must have Git for Windows installed.
Ability to execute Java programs
You will need to have the Java Development Kit (JDK) installed.
If you have any terminal emulators open (such as Terminal or Git Bash), close them and reopen them after installing the JDK.
Understanding of plain text
Plain text is a term frequently used to mean one data on a computer that is represented as codes in the ASCII encoding system or the Unicode encoding system, a successor to ASCII.
These coding systems map specific numeric codes to every text character. For example, the letter a
is 97, b
is 98, and so on and so forth.
Understanding of plain text
When you as a human see plain text on your screen or type text characters on your keyboard, chances are the computer behind the scenes will store that text’s numeric codes (in binary) according to one of these two encoding systems.
A plain text file is a file that has nothing but numeric codes that map out to characters in one of these systems. Unicode is today’s standard and includes all the Anglocentric characters ASCII did, plus characters of all other languages.
Ability to edit plain text
Computer programming code is plain text. In order to edit code, you will need a decent plain text editor program.
- Install Sublime Text, a free good quality plain text editor.
- Sublime Text is freeware, but periodically will ask for donations. You are not required to donate.
Just about any code editor or Integrated Development Environment, such as Visual Studio Code, is a good plain text editor.
Warnings about text editor quality
- Never use TextEdit on OS X to edit code.
- Never use Notepad on Windows to edit code.
- Do not use Microsoft Word or Google Docs to edit code
- Beware of Emacs, lest you find yourself forever dreaming of keyboard shortcuts.
Command line text editors
Emacs is a plain text editor that can be run from the command line. Vim is another.
If you want to have the most fun with the *NIX command line, use Emacs instead of Sublime Text or Visual Studio Code.
Emacs shortcuts
Emacs functionality depends upon a lot of keyboard shortcut combinations. The following will get you started:
Ctrl-x Ctrl-s
to save a fileCtrl-x Ctrl-c
to quit emacs
Learn more shortcuts with an emacs cheat sheet.
Starter code
Create a file
Use the command line to make a new plain text file with the .java
extension somewhere you know you can find it later.
foo@bar$ cd ~
foo@bar$ mkdir first_try
foo@bar$ cd first_try
foo@bar$ touch MyFirstJavaProgram.java
Add starter Java code to the file
Edit the text file you just created using a text editor of your choice, such as emacs
or nano
:
foo@bar$ emacs MyFirstJavaProgram.java
Add the following code:
public class MyFirstJavaProgram {
public static void main(String[] args) {
// put the main contents of your program below here
System.out.println("Welcome to Java from the command line!");
// put the main contents of your program above here
}
}
Save your file
If you are using the emacs
editor, press Ctrl-x Ctrl-S
to save, then Ctrl-x Ctrl-c
to quit.
If using any other graphical user interface editor, just save the ordinary way.
Compile the Java source code
Java code must be compiled to byte code before it can be run. Use the javac
command to do this.
foo@bar$ javac MyFirstJavaProgram.java
Note the full name of the .java
file to compile.
The compiler will now have automatically created a file named MyFirstJavaProgram.class in the same directory.
Execute the Java byte code
The Java byte code can now be executed by the JVM, Java’s interpreter, using the java
command.
foo@bar$ java MyFirstJavaProgram
Welcome to Java from the command line!
Note the command does not require the .java
or .class
file extension.
Better starter code
Add a package
Java code can be organized into “packages” of related files.
Add a similar package declaration to your source code file in an editor of your choice, but replace fb1258
with your own NYU Net ID.
package edu.nyu.cs.fb1258;
public class MyFirstJavaProgram {
public static void main(String[] args) {
// put the main contents of your program below here
System.out.println("Welcome to Java from the command line!");
// put the main contents of your program above here
}
}
Move the file to the proper location
Sadly, with a package identifier, the .java
and .class
files must now be located in a directory that matches the package or the JVM will not execute them.
Create an appropriate set of sub-directories, and move both files at once (replace fb1258
with yoru own NYU Net ID):
foo@bar$ mkdir edu
foo@bar$ mkdir edu/nyu
foo@bar$ mkdir edu/nyu/cs
foo@bar$ mkdir edu/nyu/cs/fb1258
foo@bar$ mv MyFirstJavaProgram.* edu/nyu/cs/fb1258
Of course there is a way to create all these sub-directories at once using the -p
flag to the mkdir
command:
foo@bar$ mkdir -p edu/nyu/cs/fb1258
foo@bar$ mv MyFirstJavaProgram.* edu/nyu/cs/fb1258
Recompile the Java source code.
Sadder still, the Java source code must now be re-compiled, since the byte code is no longer up to date.
foo@bar$ javac edu/nyu/cs/fb1258/MyFirstJavaProgram.java
This will overwrite the file named MyFirstJavaProgram.class
in the appropriate directory.
Re-execute the Java byte code
At this point, you have two files named MyFirstJavaProgram.java
(source code) and MyFirstJavaProgram.class
(byte code) in the directory edu/nyu/cs/fb1258
, where fb1258
is replaced with your own NYU Net ID.
Now try running it. Here we will tell the JVM that it should look in the current working directory (nicknamed .
in UNIX) and any sub-directories for the appropriate .class files within the indicated package.
foo@bar$ java -classpath . edu.nyu.cs.fb1258.MyFirstJavaProgram
Better welcome to Java from the command line!
Use package identifiers from now on in all work.
Even better starter code
How could it be any better?!
We can do even better than our better starter code by putting Java source code into a src/
directory and compiling our Java byte code into a separate bin/
directory.
project-directory/
|
|----------> src/ (Java source code)
|
|----------> lib/ (external dependencies)
|
|----------> bin/ (compiled byte code)
In which case, we’d need to modify our compile and execute commands. Assuming the source code files were in the new location:
foo@bar$ javac -d bin src/edu/nyu/cs/fb1258/MyFirstJavaProgram.java
foo@bar$ java -cp bin edu.nyu.cs.fb12358.MyFirstJavaProgram
Soliciting input
Scanner
In order to easily receive keyboard input from a user, a Java program must import java.util.Scanner
.
package edu.nyu.cs.fb1258;
import java.util.Scanner;
public class AgreeableBot {
public static void main(String[] args) {
System.out.println("What's on your mind? ");
Scanner scnr = new Scanner(System.in);
String response = scnr.nextLine();
System.out.println("I'm also thinking about " + response + "!");
scnr.close();
}
}
Scanner’s built-in functions
Scanner has a few different functions for fetching the user input as different data types, e.g.:
nextLine()
- returns aString
with the user’s input up to the newline (i.e.\n
) character they typenextInt()
- returns anint
with the user’s input, if they entered an integer; otherwise crashesnextDouble()
- returns adouble
with the user’s input, if they entered a number; otherwise crashes
Scanner weirdness
Using any of the functions besides nextLine()
creates complication. For example:
package edu.nyu.cs.fb1258;
import java.util.Scanner;
public class LookHowGreatJavaIs {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
// get user's age
System.out.println("Please enter your age: ");
int ageAsInt = scnr.nextInt(); // an int
// get user's name
System.out.println("Please enter your name: ");
String name = scnr.nextLine(); // a String
// print out a friendly welcome message
System.out.println("Welcome, " + name + "! You are " + ageAsInt/7 + " years old in dog years!");
scnr.close(); // close the Scanner to conserve resources
}
}
This program will always output, Welcome, !
no matter what you do… Scanner barely works.
Avoiding Scanner weirdness
One way to avoid Scanner’s weirdness, when asking the user for data types besides String, is to use nextLine()
for all input and then convert the String it returns to other data types.
public class StickToScanningStrings {
public static void main(String[] args) throws Exception {
Scanner scnr = new Scanner(System.in);
// get user's age
System.out.println("Please enter your age: ");
String ageAsString = scnr.nextLine(); // a String... avoid nextInt() and nextDouble!
int ageAsInt = Integer.parseInt(ageAsString); // and for doubles use Double.parseDouble(age)
// get user's name
System.out.println("Please enter your name: ");
String name = scnr.nextLine(); // a String
// print out a friendly welcome message
System.out.println("Welcome, " + name + "! You are " + ageAsInt/7 + " years old in dog years!");
scnr.close();
}
}
Conclusions
We can now use the command line to write and compile Java source code into Java byte code and then execute that byte code using the JVM interpreter.
- Thank you. Bye.