Download presentation
Presentation is loading. Please wait.
1
Sophomore Scholars Java
A Review of the Basics
2
What is Java? 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.
3
A Sample Program class Sample { public static void main(String[] args) { System.out.println(“Hello world!”); }
4
Classes and Nomenclature
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).
5
Classes and Nomenclature
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!
6
Brackets 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!!
7
Methods?! 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.
8
More Methods - Keywords
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)
9
The Code 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.
10
SEMICOLONS 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.
11
Output 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).
12
More Output – Print() Example
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.
13
Output – Println() Example
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.
14
Variables and Print 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.
15
Examples 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”
16
Which One Should I Use?! 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.
17
Comments 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.
18
Single Line Comments Single line comments are comments for…a single line. They must be preceded by two forward slashes. //This is a single line comment
19
Multiple Line Comments
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. */
20
Math 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.
21
Variables (Identifiers) and Types
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.
22
Variables – Naming Conventions
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.
23
Reserved Words 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.
24
List of Reserved Words abstract private enum**** void continue this
instanceof Class for break return finally new double transient long switch implements catch strictfp** assert*** protected extends volatile default throw int const* goto* byte short float package else try native synchronized import char super boolean public final while do throws interface if case static
25
Variable Names - Examples
Valid identifier names: foo bar myScanner myCookie this_is_a_good_name Invalid identifier names !woo 2ForMe public This is a bad name
26
Declaring and Assigning Values
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…
27
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) Of these, only int, boolean and double are tested on the AP Exam.
28
Int int stands for integer. These are signed numbers in the range of -2,147,483,648 through 2,147,483,647. -231 through You must remember these values!! They are stored in static variables called Integer.MAX_VALUE and Integer.MIN_VALUE In other words, you can type in those variable names in any Java program and they will be usable: //The following stores in someInt int someInt = Integer.MAX_VALUE;
29
Floating Point Numbers (double)
Floating point numbers allow for the storage of numbers with a decimal. Floating point numbers are stored in two parts: a mantissa, which specifies the digits of the number, and an exponent , in the following manner - sign * mantissa * 2exponent For type double, eleven bits are allocated for the exponent, and typically 52 bits for the mantissa. One bit is allocated for the sign. …this leads to problems!!!
30
Floating Point Mathematical Errors
When floating point numbers are converted to binary in order for your computer to do calculations, there is sometimes an error of conversion of the number. This is known as round-off error! For example: 0.1*26 ≠ … (26 terms) The first evaluates to 2.6. The second evalutes to This is why so many of you had math errors in your AddCoins program last year and I told you not to worry about it! You need to know about round-off errors for the AP Exam – just the definition will suffice.
31
NaN and Infinity There are two other possibilities for results of any arithmetic expression in Java: NaN = not a number. This is used for when there can be no REAL result, such as taking the square root of a negative number or dividing 0.0 by 0.0. Inf or –Inf = Infinity or –Infinity. This is used when an answer is too vast or too small (like the limits of expressions – calculus stuff). Dividing a nonzero number by zero yields this result.
32
Hexadecimal Numbers Hexadecimal numbers (known as Hex or base-16) are represented by the numbers 0-9 and the letters A-F. 0-9 represent 0-9 A represents 10, B represents 11, C represents 12, and so on. For example, A34 represents the number 2612. How!? Before you can convert to hex, you need to investigate how binary numbers work. This will be covered slightly later in another set of slides.
33
Boolean 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;
34
Primitive Data Type Declarations
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!
35
Back to Math 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).
36
Addition 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.
37
Subtraction 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”
38
Multiplication 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”
39
Division 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.
40
Regular Division 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”
41
Integer Division 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.
42
Integer Division Example
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 , but integer division ignores the decimal values!
43
Modular Division 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.
44
Modular Division Example
int num1 = 100; int num2 = 6; int remainder; remainder = num1 % num2; System.out.println(“The remainder is ” + remainder); Will print “The remainder is 4”
45
Order of Operations 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!
46
Conditional Statements
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.
47
Symbols for Logic Keywords
AND = && OR = || NOT = !
48
Some Logic Examples 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!
49
If Statements 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!
50
If Statement Examples 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?
51
If…Else 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.
52
If…Else Example 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!
53
Valid Comparison Symbols
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!
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.