Sophomore Scholars Java
Download
Report
Transcript Sophomore Scholars Java
A Review of the Basics
Java is an object oriented programming language
developed by Sun Microsystems.
An object programming language allows for massive
versatility in code – objects can inherit characteristics
of other objects and even redefine them.
Java is a cross-platform development programming
language – Java programs can compile and run on
Windows machines, Macs (ugh), and even Linux
boxes.
class Sample {
public static void main(String[] args) {
System.out.println(“Hello world!”);
}
}
class Sample {
public static void main(String[] args) {
System.out.println(“Hello world!”);
}
}
Every object in Java is a class, even this simple program.
Classes must be named in the same fashion as the file it is
saved in (the above would be in a file named Sample.java).
Classes can be named with any combination of letters,
numbers, and special symbols ($ and _).
However, they must begin with a letter, an underscore, or a
valid Unicode currency character (like the Euro symbol).
The first letter of a class name must be capitalized, and any
subsequent word in the class name should be capitalized.
E.g. ThisIsAClassNameWithMoreThanOneWord
JAVA IS CASE SENSITIVE!!!!! A class that is named
SnookieIsGross and SnookieIsGROSS are TWO TOTALLY
DIFFERENT CLASSES!!!
YOU CANNOT USE A SPACE IN A CLASS NAME!
class Sample {
public static void main(String[] args) {
System.out.println(“Hello world!”);
}
}
Curly brackets are used in Java to surround code. Every
class definition must be surrounded by curly brackets, as
well as method code (see later), and blocks of code (after if
statements, in loops, etc.)
Most errors occur because people forget to close their
brackets!!
class Sample {
public static void main(String[] args) {
System.out.println(“Hello world!”);
}
}
The main method (more on methods later in the year) is
the code that runs when a class is executed. A class does
NOT need to have a main method; if it does not have a
main method, you can compile it but NOT run it (you will
receive a noSuchMethodError: main exception).
It must be defined exactly as it is above.
class Sample {
public static void main(String[] args) {
System.out.println(“Hello world!”);
}
}
public = This method is accessible by everyone. It is possible to make a
method private – then it can only be seen by this class alone.
static = takes all variables as parameters – cannot see non static variables in the
rest of the class
void = does not return a value (This is weird in Java)
main = the name of the method
String[] = a data type (an array of Strings)
args = the name of the array that holds the Strings (THIS IS NOT A
KEYWORD)
class Sample {
public static void main(String[] args) {
System.out.println(“Hello world!”);
}
}
System.out.println(“…”) is a call to a method that prints
something out to the screen, where that something is …
surrounded by quotation marks, if it is a String.
You can also print out the value of a variable without using
quotes.
The dots are there because the println method is a method in the
out class which is defined in the System class.
class Sample {
public static void main(String[] args) {
System.out.println(“Hello world!”);
}
}
The end of every line in Java that executes some kind of
command MUST end with a semi-colon.
This is the second most common error in this course.
Please be very wary of your semi-colons! It’s like adding
punctuation at the end of a sentence.
In Java, one can output to the command prompt
(usually), to a file, or even to special GUI designs.
System.out deals with standard output, which is the
command prompt.
System.out.print(“…”) will print … to the command
prompt and WILL NOT GO ON TO THE NEXT LINE!
The cursor will remain on the same line awaiting to
print to the screen.
System.out.println(“…”) will print … to the screen and
move on to the next line. (Hence, the ln at the end of
the method).
public class PrintLineExample {
public static void main(String[] args) {
System.out.print(“Here is one line.”);
System.out.print(“And this will print on the same
line.”);
}
}
The output will be:
Here is one line. And this will print on the same line.
public class PrintLineExample {
public static void main(String[] args) {
System.out.println(“Here is one line.”);
System.out.println(“And this will print on the
next line.”);
}
}
The output will be:
Here is one line.
And this will print on the next line.
System.out.println(“The sum is ” + sum);
There’s a + sign there, but it does NOT mean addition!
The data type that goes into System.out.print/ln
statements is String.
The + there means string concatenation.
You can “add” Strings together to get one bigger String.
So, if I were to “add” the Strings “Mister” and “Weir” I
would get one String whose value is “Mister Weir”
So, in a print/ln statement, you must surround your Strings
(the parts you want literally printed to the screen) in “ “,
and variables must be ADDED to the string for their values
to be printed.
Let’s assume we have two variables, num1 and num2,
whose values are 10 and 5, respectively.
System.out.println(“The values are “ + num1 + “and” +
num2);
Will print “The values are 10 and 5”
System.out.println(“The values are num1 and num2”);
Will print “The values are num1 and num2”
This depends on the context of the code.
If you are writing a prompt to a user (asking for an
action and awaiting input), it might be cleaner to use
print() instead of println().
However, there is no wrong answer – it’s all a matter of
preference.
Comments are like notations that a programmer
makes in code, either to himself/herself or to another
person looking at the code.
Comments have absolutely no effect on the
compilation of the program.
There are two ways to put comments into your
programs.
Single line comments are comments for…a single line.
They must be preceded by two forward slashes.
//This is a single line comment
Multiple line comments are used when you want you
comments to span more than one line.
This is usually used in preconditions/postconditions of
a method, where much more detailed explanation is
required.
In this case, the comment must begin with /* and end
with a */ (a comment sandwich).
/*This is a multiline comment because it can go on and
on and on and on but it will eventually end. */
You can do pretty much any math you want in Java
(that is consistent with real world mathematics).
There is even a Math class in Java with special
functions (such as sqrt() - square root, abs() – absolute
value, etc.)
The math you will be doing in this course will be basic
math - addition, subtraction, multiplication and
division.
However, things are not as easy as they appear.
Java is a typed (though not strongly) language.
This means that variables must be the same type in
order for them to interact in any way.
Huh!?
Well, a variable is must like it is in math – something
which represents a specific value in a formula.
Variables must be DECLARED before they can be
ASSIGNED a value.
Naming variables must also follow some rules.
Variables must be named using similar rules as those
for classes.
Valid variable (or identifier) names can consist of any
combination of letters, capital and lowercase,
numbers, and special characters ($, _, Unicode
currency symbols).
They must also begin with a letter, underscore, or
currency character, like classes.
However, unlike classes, the convention is to have the
first letter be lowercase, and all subsequent words
begin with a capital letter.
Identifiers also cannot have the same name as reserved
words in Java.
Reserved words are those which mean something
special to the compiler (TextPad makes them blue
when you type them).
You have already seen some reserved words, such as
String, public, static, etc.
Your program will not compile if you do his.
abstract
continue
for
new
switch
assert***
default
goto*
package
synchronized
boolean
do
if
private
this
break
double
implements
protected
throw
byte
else
import
public
throws
case
enum****
instanceof
return
transient
catch
extends
int
short
try
char
final
interface
static
void
Class
finally
long
strictfp**
volatile
const*
float
native
super
while
Valid identifier names:
foo
bar
myScanner
myCookie
this_is_a_good_name
Invalid identifier names
!woo
2ForMe
public
This is a bad name
Here is a declaration for an identifier
int num2;
All declarations must first begin with a data type, and then
a valid identifier name, followed by semicolon.
You can also ASSIGN a value while declaring a variable.
int num2 = 10;
You MUST declare a variable before you can use it in your
program! This is how you are telling the compiler of this
identifier’s existence! When you declare a variable, the
compiler will set aside memory for later use.
But…let’s talk more about the specific data types…
Every variable must have a type associated with it.
You will be working with mostly primitive data types, but a
data type can even be a class (since all classes are of type
Object)!
The following is a list of primitive data types.
char
byte
short
int
long
float
double
boolean
void (useless)
Char stands for character. It is one single symbol.
Any symbol from the keyboard is a valid character.
When you assign a char a value, you must surround
the symble apostrophes (single quotes).
char c = ‘a’;
You will be working with characters in this course,
although the Scanner input we will be using cannot
deal with characters.
Byte is a number which ranges from -128 to 127.
We will rarely use this.
This is used primarily to save memory in programs
(due to its restrictive range).
byte b = 100;
Shorts are numbers that range from -32, 768 to 32,767.
Also used to save memory space.
short shortNumber = 4565;
The following will NOT work:
short outOfRange = 60,000;
This number is TOO LARGE for a short, and will produce an
error.
int stands for integer. These are signed numbers in the
range of -2,147,483,648 through 2,147,483,647.
These are the most common ones you will be using in
class.
int num1 = 0;
int num2 = 100;
long is for a…long number. The range of numbers is
-9,223,372,036,854,775,808 though
9,223,372,036,854,775,807.
Use these if you need to use a number that is greater
than the range of int.
You will never be using these.
All of the previous data types do not have decimal
values. If you try to assign a value with a decimal to
any of those, you will get a compilation error.
int num1 = 10.2 //THIS IS BAD
float is a data type which can have a decimal value.
However, the values have a short range (much like
short compared to int).
You won’t be using this.
float myFloat = 10.2;
doubles also deal with decimal numbers.
They have a wider range than floats.
You will be using these.
double grade1 = 98.2;
boolean variables have only two values: true or false.
These are used in conditional statements (will be
discussed later).
You will be using these all of the time in future
programs.
The following are example of setting the values:
boolean doesPatHaveDetention = true;
boolean willTheMetsWin = false;
Please notice that all of the primitive data types have
only lowercase letters. You cannot declare a primitive
data type using a capital letter as the first letter.
For example:
Integer int1 = 0;
There IS an Integer class in Java, with methods for
converting between int and other primitive data types.
So when you type Integer int1 = 0, the compiler will be
expecting something of type Integer to the right of the
=, not a number.
SO – please use only lowercase letters!
So now that you know all of the data types, let’s talk
about math.
We’ll do addition, subtraction, multiplication and
division (which is special).
Addition is done using the + operator.
Here’s an example:
int num1 = 5;
int num2 = 9;
int sum;
sum = num1 + num2;
System.out.println(“The sum is ” + sum);
This snippet of code will print out 14 to the screen.
Subtraction is done using the – operator.
int num1 = 100;
int num2 = 45;
int difference;
difference = num1 - num2;
System.out.println(“The difference is ” + difference);
Will print: “The difference is 55”
Multiplication is done using the * operator.
int num1 = 5;
int num2 = 9;
int product;
product = num1 * num2;
System.out.println(“The product is ” + product);
Will print “The product is 45”
Here is where things get complicated.
There are many types of division in Java (and generally
all of computer science) – integer division , “regular”
division and modular division.
Based on your data types, and situation, you will want
to use different ones.
I will highlight all three.
Regular division ONLY works with floats or doubles.
“Regular” division is division which gives you a whole
number answer (with decimal values).
double num1 = 101;
double num2 = 25.25;
double quotient;
quotient = num1 / num2;
System.out.println(“The quotient is “ + quotient);
Will print “The quotient is 4.0”
This only works with ints.
Since ints do not have any decimal values, this type of
division will just return the result of the division
WITHOUT a decimal value.
It does not even round. It ignores the decimal value
totally.
This does have its uses, which we will discuss later.
int num1 = 100;
int num2 = 6;
int quotient;
quotient = num1 / num2;
System.out.println(“The quotient is ” + quotient);
Will print “The quotient is 16”
The actual answer is 16.6667, but integer division
ignores the decimal values!
What if you wanted to use the remainder of a number
for some purpose?
You would use modular division.
Modular division returns the remainder of an integer
division.
You achieve this by using the % operator.
int num1 = 100;
int num2 = 6;
int remainder;
remainder = num1 % num2;
System.out.println(“The remainder is ” + remainder);
Will print “The remainder is 4”
Order of operations works the same in Java as it does
in real math.
PEMDAS!
You can use parenthesis in java math operations.
So…KNOW YOUR ORDER OF OPERATIONS!
Conditional statements are “checks,” which are very
much like boolean variables.
You should have done some simple conditional logic in
your geometry class.
In real world terms, the key words for logic are AND,
OR, NOT, IF, IF AND ONLY IF
The blue ones are what you will be using in Java.
AND = &&
OR = ||
NOT = !
IF = if
Assume we have three boolean variables, defined as
follows:
statementOne = true
statementTwo = false
statementThree = true
statementOne && statementTwo = false
AND statements are true only if each condition is true
statementTwo || statementThree = true
OR statements are true if any of the conditions are true
You can also have compound statements! Separate each
check with parentheses!
(statementOne && !(statementTwo)) && statementThree =
true!
If statements are the most prevalent conditional
checks in all of computer science. Mostly any program
will have if statements somewhere in the code.
They have the following syntax:
if (any number of conditional checks) {
…some code
}
The code inside of if statements is not guaranteed to
run!
The most common mistakes in these types of checks is
forgetting parenthesis!
int num1 = 10;
int num2 = 15;
if ( (num1 > 5) && (num2 < 100) ) {
System.out.println(“This will print!”);
}
In the above code, the condition is met, so the text is
printed.
What if you wanted something else to happen if the
condition is not met?
You would use an else statement after the if.
It has the following syntax:
if (condition) {
…some code
}
else {
…some more code
}
In this case, ONE block of code is guaranteed to run,
based on the condition.
boolean condition1 = (11>10); //can do condition here!
if (condition1) {
System.out.println("It worked!");
}
else {
System.out.println("Something is wrong!");
}
The above will print “It worked!” to the screen.
Note that you can set a boolean value to a check, and the
true/false value will be saved into the variable.
If you change the condition above to 10>11, the second
println statement will be printed!
Other than the standard logic symbols, there are other symbols that
can be used for comparisons.
They are:
>
<
>=
<=
==
The strange one is the == symbol. Please remember that a SINGLE =
means “assign the following value to the preceding identifier” in Java.
If you try this:
if (num1 = 10) {
Java will try to assign a 10 to num1, but it also knows that it CANNOT do that!
You will receive a compile error!
For this reason, you MUST use a double equal sign to do an equal
check!