Mr. Monroe s Guide to Mastering Java Syntax
Getting Started with Java 1. Download and install the official JDK (Java Development Kit). 2. Download an IDE (Integrated Development Environment), like BlueJ. 3. Create a new project and a new class file. a. Name projects and classes appropriately. b. Spaces are not allowed in class names. 4. Double click on the orange class box to open the code window. 5. Delete the starting code and type the following to get started.
BlueJ Compiling and Executing 1. Before executing any code, it must be compiled into 0 s and 1 s. 2. Hit the compile button and look at the bottom of the screen for errors. This image shows a class that has not been compiled. This image shows a class that has been compiled successfully. 3. Execute a compiled class by right clicking, selecting main, then Ok. 4. If the output terminal window does not show up upon execution, click View on the top bar, and select Show Terminal. (Ctrl+T) a. If the terminal won t close, hit Options, Close. (Ctrl+W) b. Another useful option is checking Clear Screen at Method Call. 5. If the program gets stuck running, click View on the top bar, select Show Debugger, and hit terminate to stop the program. (Ctrl+D) 6. Another way to stop the program is to right click on the red and white active bar and hit Reset Java Virtual Machine. (Ctrl+Shift+R)
Common Java Compilation Errors 1. REACHED END OF FILE WHILE PARSING This means that you are missing an ending curly brace somewhere in your code. Check to make sure all of your braces are paired correctly! 2. IDENTIFIER EXPECTED Check the highlighted line. You may have code that is outside of a method or a method that is outside of a class or some other typo. 3. CANNOT FIND SYMBOL Check the highlighted line. You may have a variable that you did not declare, are trying to access a variable out of scope, or another typo. 4. ; EXPECTED Check the highlighted line. You may have a statement that has not been terminated with a semi-colon. Most statements must end with one. 5. UNCLOSED STRING LITERAL Check the highlighted line. You may have a String declaration or assignment or print statement that is missing a quotation mark. 6. NOT A STATEMENT Check the highlighted line. You may have a statement that contains a typo such that Java cannot resolve the statement properly. 7. NOTE: COMMENTS ARE NOT READ BY THE COMPILER Comments in Java are written after //. They are not ignored by the compiler and will not cause errors, but they will also not do anything.
Java Variables 1. Integers (whole numbers) are stored using int 2. Decimal numbers are stored using double 3. Letters and words are stored using String 4. True and false values are stored using boolean A variable may only be DECLARED once! Variables must first be DECLARED before they are used. To declare a variable, type the storage type and then a variable name. int x; // variable declaration Variables may be INITIZALIZED when they are DECLARED. To initialize a variable, assign it an appropriate value when declaring it. int x = 5; // variable initialization Variables may be ASSIGNED a new value after they ve been DECLARED. To assign a variable a value, set it equal to an appropriate value. x = 7; // variable assignment
Java Arithmetic Operators 1. = assignment 2. + addition 3. - subtraction 4. * multiplication 5. / division 6. % modulus (remainder)
Incrementing/Decrementing Variables To change the value of a variable that we have made, we must reassign it a new value. This applies to any variable type: int, double, String, or Boolean. int x = 5; x + 1; x = x + 1; x += 1; x++; // initialize value // doesn t assign // reassigns value // shorthand v1 // shorthand v2 double y = 5.5; y - 2.0; y = y - 2; y -= 1; y--; // initialize value // doesn t assign // reassigns value // shorthand v1 // shorthand v2
Java Print Statements The Java commands to print something to the terminal are: System.out.print( Text ); System.out.println( Text ); If the print has ln after it, the program will do a return after printing what is inside of the quotes. ln is short for line. Note the capitalization, quotes, parenthesis, and semicolon. Examples:
Java Printing Variables Use System.out.print or System.out.println, but place the variable name inside of the parenthesis without quotes. To print out text and a variable in the same print statement, use plus signs to separate each string of text and each variable.
Java Boolean Expressions A conditional statement is a line of code that only activates if the relationship inside of the parenthesis evaluates to true. You must have parenthesis after an if statement. You must have parenthesis after an else if statement. You must NOT place parenthesis after an else statement. You must have a set of curly braces after a conditional statement. Relational Operators: (x == y) // equal to (x!= y) // not equal to (x > y) // greater than (x >= y) // greater than or equal to (x < y) // less than (x <= y) // less than or equal to
Java Compound Boolean Expressions Conditional statements may be extended for additional conditions rather than using a sequence of multiple if statements. The code above can be shortened using logical operators. Logical Operators: ( ( x == 5 ) && ( y == 10 ) ) // Logical AND If BOTH are true, then the condition is met. ( ( x == 5 ) ( y == 10 ) ) // Logical OR If EITHER is true, then the condition is met. (!myboolean ) // Logical NOT The value is switched from T->F or F->T.
Truth Tables for && and In an AND (&&) expression, BOTH variables must be true for a true result. && T F T true false F false false A B R T T T T F F F T F F F F In an OR ( ) expression, EITHER variable can be true for a true result. T F T true true F true false A B R T T T T F T F T T F F F
Java While Loops A loop statement allows us to execute a group of statements repeatedly as long as the expression in parenthesis remains true. While loops parenthesis hold the same conditional operators as if and else if statements. Here is an example using a boolean value: The above code would create an infinite loop if executed. The compiler would not show any errors, but execution would never end. This is because the condition in the parenthesis never changes.
Java For Loops Another kind of loop statement is a for loop. For loops provide a compact way to execute a group of statements a set number of times. for (initial value; termination; increment) { } // statements to execute The code example below starts with an initial value of 1. The loop will stop executing the code when that value not less than or equal to 10. After each execution of the statements inside the loop, the value is incremented by 1. This means that, eventually, the value with be > 10.
Java Random Number Generation To generate a new random integer, Java needs the Random utility to be imported. Call this at the top of your code, outside of any class. import java.util.random; Now that the utility has been imported, inside your class you can create a new random number generator and name it something like rand. Random rand = new Random(); To get a random integer from it, call rand.nextint(#). The next line of code will generate a random integer from 0 to 999. int myrandnum = rand.nextint(1000); By default, the random number generator will give you an integer from zero to the number in the parenthesis minus one. If you want a random number within a certain range, use this:
Java Scanner for User Input To get input from the user, Java needs the Scanner utility to be imported. Call this at the top of your code, outside of any class. import java.util.scanner; Now that the utility has been imported, inside your class you can create a new scanner and name it something like scan. Scanner scan = new Scanner(System.in); To store an integer from the user, call scan.nextint(). When the program is executed and reaches this line, it will wait for the user to input an integer. int mynum = scan.nextint(); To store a String from the user, call scan.nextline(). When the program is executed and reaches this line, it will wait for the user to input a String. String mystring = scan.nextline(); If you want to safely check for integers only, use this: Also, you should close the scanner if you don t need it anymore: scan.close();
Type Casting in Java Casting is a way of taking an object of one particular type and temporarily changing it to another type. Java in some cases will actually do this for you automatically! Examples: int x = 5; int y = 2; System.out.println( x / y ); // Prints 2 System.out.println( (double) x / y ); // Prints 2.5 double z = x; // Automatically casts x as double System.out.println( z ); // Prints 5.0 double a = 12.7; int b = a; int b = (int) a; // Error Incompatible Types! // Downcasts a to type int System.out.println( b ); // Prints 12 Note: Casting doubles to ints always rounds down!
Final Variables in Java Final variables are user-defined constants. After you have assigned a final variable a value, you may no longer assign it again! This is useful to keep us from accidentally changing a value later in our code, as well as having direct access to a parameter at the top of our code rather than having to scroll through it all and change it in every case below. Declare final variables by using the keyword final before declaration. Also, convention is that variables that are declared final are written in all capital letters. Examples: final double TAX_RATE = 0.8; final int MAX_STUDENTS = 30; If you later try to reassign one of these values TAX_RATE = 0.6; // Error: Cannot assign a value! Though, if you don t initialize a final variable, you may assign it later. final double TAX_RATE; if (state== California ) { TAX_RATE = 7.5; } else if (state== Texas ) { TAX_RATE = 6.25; } No errors because it never reassigned the final variable!
Arrays Arrays are a data structure that stores a sequential collection of elements of the same type. Each item in an array is called an element, and each element is accessed by its numerical index. To declare an array, write the data type and then square brackets, followed by a name for the array. To assign data in an array, use the assignment operator =, and then place appropriate data inside of curly braces separated by commas. int[] arrayname; int[] myarray = {7,3,5}; myarray = {6,4,7}; myarray[2] = 7; // declares an array // initializes an array // reassigns an array // reassigns an element Note: Java starts the indices at zero!
Printing Arrays and their Elements int[] array = {6,9,7,4,5}; System.out.print(array[1]); // prints 9 System.out.print(array.length); // prints 5 How do we print the elements in the array? System.out.print(array); // prints a string representation of the array for (int i=0; i< array.length; i++) { System.out.print(array[i] + ); } // prints 6 9 7 4 5
ASCII/Unicode and Characters/Strings ASCII stands for American Standard Code for Information Interchange. It is the character encoding scheme that we developed in the 1960 s to convert all of the English letters and symbols into binary 0 s and 1 s. Unicode is a superset of ASCII that has the same encoding as ASCII, but also has encoding for all of the world s writing systems and all of their symbols. A character is any letter, number, or symbol. To store a single character in Java, use the primitive variable type char. Here s an example: char myfavletter = m ; // char initialization To store an array of characters, use the same array syntax. Example: char[] myfavletters = { d, c, m }; // char array initialization Remember to use SINGLE QUOTES around characters! String is a class in Java to help us store and use strings of characters. The following example shows the initialization of a String literal: String mylastname = Monroe ; // String literal initialization If you later write in your program another string that stores the same exact text as a previous string, Java will save memory via interning, where instead of storing all of those characters in memory somewhere else, it will just point to the same address in memory as the previous string. If you want to create a unique String with its own place in memory, use this: String lastname = new String( Monroe ); // String object initialization Remember to use DOUBLE QUOTES around Strings!
String Methods String myfirstname = David ; String mylastname = Monroe ;.equals(string) returns boolean, compares two strings! boolean match = myfirstname.equals(mylastname); // false.length() returns integer, counts letters in the string! int length = myfirstname.length(); // 5.toLowerCase() returns String, lowercase version of string! String low = myfirstname.tolowercase(); // david.touppercase() returns String, uppercase version of string! String cap = myfirstname.touppercase(); // DAVID.indexOf(string) returns integer, first occurance of input in string! int firstoccur = myfirstname.indexof( v ); // 2.substring(#,#) returns String, part of string from start to end! String sub = myfirstname.substring(2,4); // vi // Note: Starting number is inclusive, ending is exclusive!
Methods In Java, you must have a main method in at least one class in your program to be able to execute your program. This is the definition: public static void main(string[] args) { } The public and static keywords will be covered on the following page. The String[] args part can be used to send the program some parameters during initialization to change program execution. Other methods can be defined using a similar syntax to the main method: public static returntype methodname ( parameters ) { } The returntype must be a valid data type, like int, double, String, boolean. You can return multiple data types, just separate them using spaces. The methodname can be any name you want, other than a reserved word. The parameters must be a valid data type followed by a variable name. You can input multiple parameters, just separate them using commas. Example of method call and return below: