Lec7 CodeMusic
Lec7 CodeMusic
PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.
DOWNLOAD AND INSTALL SOFTWARE
3
STEPS FOR CREATING & RUNNING A PROGRAM
4
SOURCE CODE IS WRITTEN IN A .JAVA FILE
Step1. When a programmer writes Java code, it is stored in a source code file that
has a .java extension like SampleCode.java.
The source code file is what the programmer compiles and runs to see the output of
a program. We will write our Java progams in the IDE software called Eclipse. IDE
stands for Integrated Development Environment. An IDE lets you write, compile,
and execute programs.
Source code can be typed in any simple text editor, but we will use Eclipse, which is
both a text editor and a compiler.
Eclipse is a nice Java editor and compiler because it will point out syntax errors when
java code is typed incorrectly. A program will not run until all syntax errors are
removed. 5
SOURCE CODE IS COMPILED TO BYTE CODE
When source code is compiled into byte code, the byte code is stored in a file that
has the same name as the source code file but with a .class extension. It is not
a text file and you cannot open it! For example, the source code file
RobotMan.java will be compiled into a byte code file named RobotMan.class.
The file is created during the compiling process, however, Eclipse sometimes
translates .java files into .class files behind the scenes before you ever compile
them. You can see these files in your package folders if you open your workspace
folder on your hard drive. 6
BYTE CODE IS INTERPRETED TO MACHINE CODE
Step 3. The JVM (Java Virtual Machine) must interpret the byte code into
machine language. Interpret basically means to translate. The JVM is
software that acts like hardware. That is why it is called a virtual
machine. Java bytecodes are translated on the fly to 1s and 0s instead of
being stored in an executable file, which some languages do. The main
advantage of an interpreter is that it will run on any computer and there
are JVMs for Apple and Windows machines. This makes the code portable
from one platform to another.
Every kind of computer, whether it is an Apple, Windows, or Unix machine,
has an operating system that contains a JVM software component. The
JVM was automatically installed when your computer’s system software
was installed and updates to the JVM may be contained in any system
software updates you install now or in the future. 7
WHAT ARE APPLETS?
Applets are small Java programs that are embedded in web pages. When you
load a web page that has a game in it, the game is an applet.
More specifically, the applet is usually a jar file that contains the byte code for all
the .java files that are needed for the game. A jar file is like a zip file, where a
number of files are compressed into one file.
An HTML web page can contain a special kind of tag called an Applet tag. That
tag tells the web page that the byte code is stored in a jar file with a specific
name.
The browser software, like FireFox, Chrome, Camino, or Safari will then use its
built-in JVM interpreter to translate the byte code into machine language 1s and
0s.
8
JUST-IN-TIME COMPILATION BY THE JVM
9
MACHINE LANGUAGE CODE IS
EXECUTED
Step 4. Finally, the machine
language code (patterns of 1s
and 0s), those instructions
that the computer
understands at the lowest
level, are executed. This
allows the program to appear
in its runnable form, either in
a console window, an applet
window, or a GUI (Graphical
User Interface) window.
Again the overall process is
….
10
SECTION 2
1. PACKAGE DECLARATION
2. IMPORT STATEMENTS
3. CLASS DECLARATION LINE
4. MAIN METHOD
11
FRAMEWORK OF A SIMPLE JAVA PROGRAM
The Framework (in order) of a simple console or standalone program:
1. package declaration for the file listed first (where it is stored)
2. followed by import statements (if any)
3. class declaration line
4. main method Sample
Skeleto
import java.util.Scanner;
n
public class DistanceCalculator Program Note:
{ // opening curly brace for the DistanceCalculator class • Curly braces always appear in
public static void main(String args[ ]) pairs.
{ // opening curly brace for main method • All comments start with two
// code for program goes inside these curly braces slashes //
} // ending curly brace for main method
12
All Java console and JFrame (standalone) programs have this framework. The framework for applets is different and
you will become familiar with it later.
CLASSES IN JAVA
A Java program can use more than one class file (a .java file). In fact, it may be made up of
many .java files.
And most of the time, every .java source code file in a Java program contains only one class.
However, it is possible to have more than one class in a .java file, but this is usually done in
more advanced programming projects where the code is more complicated and there is a
reason for doing it.
So assume that every .java file contains only one class, but a java program can use one or
more .java files.
A class is a module of code that can stand alone by itself and if made “public” other files can
“see it” and “access parts of it”. Eclipse is a nice IDE for organizing Java files so that
classes are accessible to each other if they are in the same package folder or if an
appropriate import statement is used to direct Eclipse to where a package is located.
Eclipse manages this behind the scenes automatically and lets you know if something is
“unorganized”, so you can fix it.
13
DECLARING CLASSES IN A FILE
A class is declared with a line like:
public class RobotMan
and has a set of curly braces that go with it { and }.
In Java, a class like RobotMan must be stored in a file named RobotMan.java. If they
don’t match, then Eclipse or any other IDE will flag it with an error and it must
be corrected before the file is used in a program. Eclipse has short cuts to
renaming the file (compilation unit) or the class if necessary. You’ll learn about
that soon.
Simple Java programs can be designed so that they contain just one class. We will
now look at some examples. 14
SECTION 3
THREE TYPES OF
JAVA PROGRAMS
15
THREE TYPES OF JAVA PROGRAMS
web page.
16
CONSOLE TEXT OUTPUT PROGRAMS
17
GRAPHICS & GUI PROGRAMS
Besides console text programs, you can have applet or standalone programs that contain graphics or
GUI components:
1. GUI components are elements in a program like text fields, buttons, labels, text areas, or menus.
2. Graphics are lines, and curves, and pretty much anything that can be drawn.
18
APPLET GUI OUTPUT PROGRAMS
Java applets are small Java programs downloaded from web pages
that run in a Web browser. A JVM is incorporated into every
browser, so the applet can be interpreted, executed and displayed
inside the browser. Both applet and standalone programs can
have GUI components.
20
JAVA IS HOT SOURCE CODE
public class JavaIsHot
{
public static void main(String args[ ])
{
System.out.println( " d ");
System.out.println( " o l ");
System.out.println( " l r ");
System.out.println( " l o ");
System.out.println( " e w ");
System.out.println( " H ");
System.out.println( " xxxxxxxxxxxxxxxxx ");
System.out.println( " x x x ");
System.out.println( " x Java x x ");
System.out.println( " x xxxx ");
System.out.println( " x is Hot! x ");
System.out.println( " x x ");
System.out.println( " xxxxxxxxxxxxxx ");
} // end of main method
} // end of JavaIsHot class
22
PRINT AND PRINTLN STATEMENTS
Here are lines of code that call the two methods print and println:
1. System.out.print(“Hello World”);
2. System.out.println(“Hello World”);
I am doing fine. 25
PRINT STATEMENTS AND SYNTAX ERRORS
System.out.println(“Hello World!”);
num1 = reader.nextInt();
Some Java lines do not end in a semicolon. You will learn which ones don’t as you are
27
USING VARIABLES TO STORE VALUES
A variable names a memory address (location) in RAM memory where a value can be stored.
In Java, we have different kinds of data types. Here you will learn three of them. We can store
each of the three types of data values in different kinds of variables.
We can have …
1. int variables that can hold integers (type int)
2. double variables that can hold real numbers or what we refer to also as floating-point
numbers (type double)
3. String variables that refer to an object that can hold a string of characters, in other words,
a bunch of characters that make up a word (type String)
The data types int and double are simple numeric data types and we store those kind of values
in simple variables that are not considered object variables.
However, Strings are objects and a String value must be stored in an object variable. Let’s
29
look at how we do that with the assignment operator.
THE ASSIGNMENT OPERATOR
The assignment operator is the = character and you can initialize variables to literal numeric or string
values in one line of code.
So to store a value in a variable, we use the assignment operator.
Here is how to declare the different kinds of variables and store values in them or as we like to say
initialize them:
In the last line of code, name is the String variable and the word “Java” is being stored. Notice the
double quotes around Java since we are storing a literal String value Don’t place double quotes
when you store numbers. 30
NUMERIC VARIABLES
double celsius;
32
JAVA’S MATHEMATICAL OPERATORS
Mod is represented by the % sign. Mod gives the remainder of int division. (You’ll be amazed at how
much you will use mod)
We also use the assignment operator when creating objects (constructing objects) so an
object variable can refer to them.
If we want to receive input from the keyboard during a program, then we need to
construct a Scanner object first. This allows the user to enter numbers or string values
into a program.
To do this we need to import Java’s Scanner class with the line:
import java.util.Scanner; // goes above the class declaration line
Next, inside the main method, we need to construct the Scanner object with the line:
Scanner reader = new Scanner(System.in);
We need to use System.in as the parameter because this indicates the keyboard, which
is the default input device for Java. Note: Scanner is a class so the S is capitalized.
34
GENERAL FORM FOR CONSTRUCTING
OBJECTS
You can see that the line of code below follows this form:
You can think of reader as something that is “scanning the keyboard waiting
for input”. 35
CONSTRUCTING A SCANNER OBJECT WITH
NEW
System.out.print(“Enter your age and press return: ”); Note: the print statements “prompt” the user to
int age = reader.nextInt();
enter data, otherwise he or she wouldn’t know
the computer is waiting for input!
System.out.print(“Enter your gpa and press return: ”);
We can now “echo the input” (print the information back to the screen that was
entered) by using some println statements. In each line, we will print a literal
string (something in double quotes) and the value contained in a variable. We
use a plus sign to concatenate the literal string value and the value stored in the
variable together to make a larger string that is then printed.
Notice that there are no double quotes around the variables name, age, and
38gpa.
SAMPLE CODE : NOTE TWO COLUMNS
public class ScanIn press return: ”);
{
int age = reader.nextInt();
public static void main(String args[ ])
System.out.print(“Enter your gpa and
{
press return: ”);
//Consider these three lines of
code: double gpa = reader.nextDouble();
If we wanted to write the code for a program that would convert Fahrenheit
temperatures to Celsius, it would be good to stop and develop an algorithm.
An algorithm is a step by step procedure for solving a problem. This helps
our code to be more efficient and we save a lot of time, because we
consider all that needs to be done … NOT just the mathematical formula
needed to convert the temperature.
40
ALGORITHM FOR CONVERTING
TEMPERATURES
41
import java.util.Scanner;
double fahrenheit;
double celsius;
// prompt the user to enter a value from the keyboard when the program runs.
System.out.print("Enter degrees Fahrenheit and press return: ");
// read the value from the keybaord and store it in the variable fahrenheit.
fahrenheit = reader.nextDouble();
// calculate the equivalent celsius value and store it in the variable celsius
celsius = (fahrenheit - 32.0) * 5.0 / 9.0;
// print out the value stored in the variable celsius to the terminal window.
System.out.println(celsius);
}
}
Note the key Scanner lines identified by the red arrows.
42
MORE ABOUT IMPORT STATEMENTS
In the Convert.java code you saw that the first line after the package declaration was an
import statement:
import java.util.Scanner;
This tells the compiler where to find a class that will be used during the program. The
class may be either in a Java library file or another file you have in a folder. The
import statement contains the path name of where to find the class.
The import statement tells us that the Scanner class is found in a sub-package folder
named util that is in the java package folder.
Now you know enough that you can finish the second half of the Convert.java program!
43
SECTION 5
CALLING METHODS
44
METHOD CALLS WITH PARAMETERS
A message may require zero, one, or multiple parameters. Here are some
examples:
• To print a blank line, we can use System.out.println(); without any parameters in
the ( ).
• To print “Hello World”, we need only one parameter the literal string value “Hello
World” in the parenthesis … System.out.println(“Hello World!”);
• To print “Hello World. Java Rules”, we still need only one parameter but the
parameter may be the concatenation of two literal string values as in …
System.out.println(“Hello World!” + “Java Rules!”); Notice that we concatenate two literal strings together using a + symbol.
• To call a method named calculateArea with two parameters length and width, we
use the code ...
calculateArea(length, width);
Notice the two parameters are separated by a comma. 46
THE METHOD SELECTOR IS THE PERIOD
The Method selector operator is the period . and is always placed between the object’s name
and the method’s name. It is also placed between the name of a class and the name of an object
when needed as in System.out.
Scanner reader = new Scanner(System.in);
Above, reader has been declared to be a Scanner class variable that represents a new Scanner object.
That Scanner object can read data from the input of the keyboard. Reader can call either of the
methods nextInt() or nextDouble() to read integers or floating-point numbers from the47
keyboard.
DECLARING INT AND DOUBLE VARIABLES
In the last output line, we concatenate 6 things together to be written to output. Three of the items are
literal strings and three are variables of type int that hold integers. Notice there are NO double
quotes around the variables. You never place double quotes around any variable … only literal
string values. Also, notice the blank spaces at the beginning and end of some literal string values.
49
This keeps the numbers from being jammed up against the words.
REVIEW OF SIMPLE AND OBJECT VARIABLES
In the Convert.java program, simple variables like fahrenheit and celsius each hold a
single floating-point number.
reader.nextDouble() sends the message “get me the next floating point number” from
the keyboard.
In summary, to write effective Java programs, a programmer does not need to have
detailed knowledge of the inner workings of any object, he or she just needs to know
how to construct objects and how to send messages to the object by calling methods.
50
THE READABILITY OF CODE
It is important for your code to be readable by others. In the real world, programmers are on
software teams as they develop and maintain software. So everyone must be able to read your
code! Programmers have developed a standard for how code should be formatted.
• The main factors that determine whether code is readable or not are
Spacing (referring to extra blank lines that space things out)
Indentation (referring to tabs or indentions on a specific line)
• Spacing and Indentation are just for programmer readability. The compiler ignores any kind of
spacing and indentation. It just checks to make sure that everything is syntactically correct
(spelled correctly)!
• Eclipse assists you with indenting segments of code as you type by automatically properly
indenting your next line depending on the kind of Java code you are writing. But if you mess up
the indenting then all you have to do is select all code by typing Control “a” on a Windows
machine or Apple “a” on a Mac, then type either Control “i” for Windows or Apple “i” for a Mac
and everything will get indented properly. 51
COMMENTS ARE USED TO …
52
THE THREE TYPES OF PROGRAM COMMENTS
Program comments come in three varieties:
public class HelloWorld
{
public static void main(String args[ ])
End of line or Single comments: All
{
text following a double forward slash //Consider these three lines of code:
(//) on a single line may explain a line System.out.println(“Hello World!”);
of code and are ignored by the
compiler. } // end of main method
} // end of HelloWorld
Notice the //. Everything after the // are programmer comments about t
Multi-line comments: All text code.
occurring between a /* and a */ is It is does not perform any task when the code is executed.
ignored by the compiler. Multi-line
comments are used where lengthy
explanations are needed or you want
to deactivate a large segment of code
temporarily.
53
USEFUL READING AND YOUTUBE VIDEO