Introduction to Java Java Programs Classes, Methods, and Statements Comments Strings Escape Sequences Identifiers Keywords Program Errors Syntax Runtime Logic Procedural Decomposition Methods Flow of Control
Review source code (ClassName.java) code written by programmer (text) Class name defined in source code: public class ClassName {.. byte code (ClassName.class) result of compiling source code platform independence Java Virtual Machine (JVM) translates byte code to executable code for native machine
Review Compile To compile our code, we use the javac command followed by the name of the Java file we want to compile > javac HelloWorld.java Execute After you compile your code, you will notice a.class file has been created in your directory. We execute the class by telling the Java Virtual Machine to run it. The command to run the Virtual Machine is java and the name of the class > java HelloWorld
Structure of Java Programs Class Method(s) Statement(s)
Classes Class A unit of code that is the basic building block of Java programs. All code in a Java file is written in a class. Each Java file starts with the words public class and the name you wish to give your program. It is convention to start the class name with a capital letter The content of a class is enclosed in a set of open and closed curly { braces. public class ClassName {
Methods Method A program unit that represents a particular action or computation. Method header: public static void methodname () { A method is made up of statements contained within curly braces. Every executable program has a main method. Java begins execution of the program with the main method.
The main Method public class ClassName { public static void main(string[ ] args) { Whatever code we write inside the main method s curly braces is the first thing that is executed. Can be placed anywhere but the convention is to put it as either the first or last method in the class.
Statements Statement An executable snippet of code that represents a complete command. All statements end with a semicolon ; public class Program { public static void main(string[ ] args) { System.out.println("Hello World!"); For now, we will use print statements of the form: System.out.println("text"); An empty print statement will produce a blank line of text: System.out.println(); To print text without advancing to the next line: System.out.print("text");
Indent nested code Readability public class Example {...public static void main(string[] args) {...System.out.println("Please indent!");... Always use braces Avoid long lines See style guidelines
Comments When writing code, it is easy to forget what you have done after a week or two go by. Comments help you and others understand what your code does It is desirable to be able to write in our code what a particular section of the code accomplishes without it affecting the program Comments are sections of our source code that are ignored by the compiler
Single Line Comments If we want to write a comment on a single line, we begin the line with // // Print an empty line System.out.println(); We can also have a comment after code System.out.println(); // Print an empty line
Area Comments If we want to have consecutive lines in the source code be comments, we use /* and */ around our comment /* This entire area in our source code is ignored by the compiler */
Javadoc Comments A third style of commenting is called Javadoc. It is a special format of commenting that we will discuss in more detail later in the course. /** * Notice it starts with two stars, * and each line has its own star. * It also allows tags for things like the author. * @author Michelle Glatz */
String Literals String A sequence of characters enclosed in double-quotes. Can contain spaces, punctuation, and special characters Cannot span more than one line "I am a valid String literal" "I m an invalid String literal"
Practice Create a Lab2 folder (cd to your exercises folder and then mkdir Lab2, cd Lab2) and then create a file PrintTest.java in this folder that contains the following code: public class PrintTest { public static void main(string[] args) { Write statements in the main method that will print the following text to the console. Each line of text gets its own System.out.println(); A well-formed Java program has a main method with { and braces. A System.out.println statement has ( and ) and usually a String that starts and ends with a " character. (But we type \" instead!)
Code does not Compile Why? Errors: PrintTest.java:10: error: ')' expected System.out.println("with a " character."); ^ PrintTest.java:10: error: illegal start of expression System.out.println("with a " character."); ^ PrintTest.java:10: error: unclosed string literal System.out.println("with a " character."); ^ 3 errors The compiler doesn t think the " and \ characters are part of the String How can we make them part of the String?
Escape Sequences We use "escape sequences" to include characters like double-quotes, tabs, newlines, and backslashes in Strings. When writing a string, we need to mark double quotes that are part of the string So the compiler knows they are part of the string We mark them by putting a backslash in front We re making an escape sequence: \" We say we escape the " to show it s actually part of the string. System.out.println("with a \" character."); System.out.println("But we type \\\" instead!)");
Escape Sequences (cont.) Common Escape Sequences \" Double-quote \n New line \t Tab \\ Backslash
Escape Sequences (cont.) Tab \t Example System.out.println("This is a\ttab"); Newline \n Example System.out.println("This is a\nnewline"); Backslash \\ Example System.out.println("//\\\\");
Escape Sequence In-class Exercise /** * This program outputs text given in RS Exercises 1.5 on page 55 * * @author your name */ public class MuchBetter { public static void main(string[] args) { Write the text in Exercise 1.5 (pg. 55) within your MuchBetter main method. Each line of text gets its own System.out.println(); Use escape sequences so your output matches the listed output. Submit to moodle MuchBetter.java assignment.
MuchBetter program output A "quoted" String is 'much' better if you learn the rules of "escape sequences." Also, " " represents an empty String. Don't forget: use \" instead of "! '' is not the same as "
Identifiers Identifier A name given to an entity in a program. Class Method Must begin with a letter, underscore, or $. After the first letter, it must contain only letters, digits, underscores, or $ Can not be a Java keyword/reserved word
Java Keywords Keyword Word that is reserved for use by Java. Sometimes called reserved word. Don t use a keyword to name a class, method, variable, or constant! Java keywords in our HelloWorld program: public, class, static, void Complete list of keywords on page 20 of text.
Case-Sensitivity Java is a case-sensitive language. Upper-case letters are interpreted as completely different letters than lowercase letters Example is a completely different identifier in Java than example
Are These Valid Identifiers? abc 5abc $$$$$$$ class _abc ab_c$ hello! Public go4it
Naming Conventions Classes start with a capital letter; subsequent words are capitalized: HelloWorld, MyFirstProgram, LetterWriter Methods start with a lowercase letter; subsequent words are capitalized: main, calculatecost, myage, nameofstudent See Style Guidelines
Program Errors Syntax Errors Runtime Errors Logic Errors
Syntax Errors (Compile-time errors) Caught by the compiler Examples: Missing semicolon ; at the end of a statement Missing curly brace { or Missing keyword Misspelling a keyword or identifier Common Error Messages: Exercise1.java:10: error: ; expected System.out.println("String that starts and ends ") Exercise1.java:10: error: cannot find symbol System.out.pruntln("String that starts and ends"); ^ symbol: method pruntln(string) location: variable out of type PrintStream ^ Strategy: Fix first compiler error and recompile
More Example Syntax error messages When too many s: TestingErrors.java:8: error: class, interface, or enum expected Missing : TestingErrors.java:7: error: reached end of file while parsing ^ Missing keyword on method header: TestingErrors.java:2: error: invalid method declaration; return type required public static main(string[] args) { ^
Common Error Messages Class name and filename don t match: HelloWorld.java:1: error: class Hello is public, should be declared in a file named Hello.java public class Hello { ^ Execute javac classname without the.java extension: Error: Class names, HelloWorld', are only accepted if annotation processing is explicitly requested Execute java classname.java: Error: Could not find or load main class HelloWorld.java
Runtime Errors Discovered at Runtime: We are able to compile the program, but we are not able to run the program. Example: Missing (or misspelled) main method Error: main method not found in class HelloWorld, please define the main method as: public static void main(string[] args)
Logic Errors Program runs, but output/result is not correct Examples: Error in a calculation Incorrect output (ex. Words misspelled in printed String) Strategy: Test programs thoroughly! Think about special cases that could occur during execution Try to make general and special cases occur during execution Make sure the program handles all of them
Errors In-class Exercise Go to our moodle page and complete the LotsOfErrors.java inclass lab. Download the given LotsOfErrors.java file to your Lab2 folder. Fix the program so that it will compile and run without errors. Put a single line comment on each line that you modified describing the change that you made. Submit your corrected LotsOfErrors.java file. Note: Before you fix any of the errors, compile the program to see the error messages that java generates. This will help you recognize what error messages are generated for each type of error, which will hopefully be beneficial when trying to decipher error messages generated when compiling your code for future assignments. Fix the errors that java finds and recompile. Once the initial errors are corrected, java will find the remaining errors that you need to correct.
Procedural Decomposition Two types of programming Procedural - a set of tasks to be executed sequentially to accomplish a goal (like a recipe) Object-oriented a set of objects that can perform tasks on themselves and interact with each other (what Java was designed for) Dividing a larger action into smaller actions Example: Baking Cookies, Doing Laundry
Static Methods A block of Java statements that is given a name Methods allow us to decompose programs into smaller pieces. Methods allow us to reuse the same piece of code thus eliminating redundancy. Procedural style (not object oriented) method
Static Method Syntax Template public static void <name>() { <statement>; <statement>;... <statement>;
Method Header Keywords public static void <name>() public indicates that the method is available to be used by all parts of your program static this is a procedural (not-object oriented) method void this method does not return a value
Calling a Method We want to move our functionality out of main Use procedural decomposition to identify methods Put common functionality in identified methods Method Call: a command to execute another method, which causes all of the statements inside the called method to be executed methodname();
Flow of Control The order in which the statements of a Java program are executed Calling a method Control is transferred to the called method When the called method is complete, the control returns to the calling method method1() { stmta; stmtb; method2(); stmtc; method2() { stmtd; stmte; stmtf;
Flow of Control Example public class Tricky { public static void main(string[] args) { first(); second(); second(); first(); public static void first() { System.out.println("Inside first method"); public static void second() { System.out.println("Inside second method"); first();
Static Methods Example Write a program to print these figures using static methods to provide structure and eliminate redundancy. / \ / \ \ / \ / - - - - - - / \ / \ \ / \ / - - - - - - \ / \ / / \ / \ - - - - - - \ / \ /
Development Strategy / \ / \ \ / \ / - - - - - - / \ / \ \ / \ / - - - - - - \ / \ / / \ / \ - - - - - - \ / \ / First version (unstructured, redundant): Create an empty program and main method. Copy the expected output into it, surrounding each line with System.out.println() syntax. Run it to verify the output.
Program Version 1 public class Figures1 { public static void main(string[] args) { System.out.println(" "); System.out.println(" / \\"); System.out.println("/ \\"); System.out.println("\\ /"); System.out.println(" \\ /"); System.out.println(); System.out.println("-\"-'-\"-'-\"-"); System.out.println(); System.out.println(" "); System.out.println(" / \\"); System.out.println("/ \\"); System.out.println("\\ /"); System.out.println(" \\ /"); System.out.println(); System.out.println("-\"-'-\"-'-\"-"); System.out.println("\\ /"); System.out.println(" \\ /"); System.out.println(); System.out.println(" "); System.out.println(" / \\"); System.out.println("/ \\"); System.out.println("-\"-'-\"-'-\"-"); System.out.println("\\ /"); System.out.println(" \\ /");
Development Strategy (cont) / \ / \ \ / \ / - - - - - - / \ / \ \ / \ / - - - - - - \ / \ / / \ / \ - - - - - - \ / \ / Second version (structured, without redundancy): Identify the structure of the output Identify redundancy in the output Divide the main method into static methods based on this structure. Identify redundancy in the output, and create methods to eliminate as much as possible. Add comments to the program.
Output Structure/Redundancy / \ / \ \ / \ / - - - - - - / \ / \ \ / \ / - - - - - - \ / \ / / \ / \ - - - - - - \ / \ / The structure of the output: initial total" figure ( top + bottom ) second line" divider figure third total" figure ( top + bottom ) fourth line + bottom" figure fifth top+line+bottom" figure This structure can be represented by methods: top line bottom
Program Version 2 // Prints several figures, with methods for structure and // redundancy. public class Figures2 { public static void main(string[] args) { total(); System.out.println(); line(); System.out.println(); total(); System.out.println(); lineplusbottom(); System.out.println(); totalwithline(); // Draws the total figure. public static void total() { top(); bottom(); // Draws the divider line. public static void line() { System.out.println("-\"-'-\"-'-\"-");...
Program Version 2, cont'd.... // Draws the line+bottom figure. public static void lineplusbottom() { line(); bottom(); // Draws total figure with divider line in middle. public static void totalwithline() { top(); line(); bottom(); // Draws the top half of the total figure. public static void top() { System.out.println(" "); System.out.println(" / \\"); System.out.println("/ \\"); // Draws the bottom half of the total figure. public static void bottom() { System.out.println("\\ /"); System.out.println(" \\ /");
Structure Diagram (Figures2) main total line lineplusbottom totalwithline top bottom line bottom top line bottom