CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG 1
Notice Reading Assignment Chapter 1: Introduction to Java Programming Homework 1 It is due this coming Sunday (Sep. 18 th ) at 11:59 PM. Class 3 Exercise The Class Exercise for today is posted here. Try to finish this before the next class, or by the end of the coming weekend. Your score on the Class Exercises account for 15% of your grade. I will send you an email with your score on each Class Exercise. If you do not finish a Class Exercise, you will get periodic email reminders. 2
Announcement The first graded quiz will be given next week. If you miss Tuesday's class, your only other opportunity to take this quiz will be the following Thursday. Get the Tools for This Course How many of you have Unix account and class directory? How many of you who use Windows have download Java? How many of you who use Windows have download PuTTY? How many of you have downloaded DrJava? How many of you have downloaded FileZilla? 3
Requirements Comments All code submitted for this course must have comments If you don t add comments, you will lose points I discuss comments further here Credit Comments There is nothing wrong with getting help from others on an assignment... as long as you are honest about it... and mention it in a credit comment I discuss credit comments further here 4
Requirements Where to Put Your Work Under your it114 directory you need to create two sub- directories ce for Class Exercises hw for Homework Each time you submit an assignment, you create a new directory for it... either under it114/ce or it114/hw For homework assignments the name of the directory will begin with 'hw, followed by the number of the assignment So you submission for homework 3 should be in a new directory named hw3... and your first Class Exercise should be in ce3 You must get these directory names exactlyright I have created scripts to collect your work If you put your work in the wrong directory, my scripts will not be able to collect them 5
Tips Fixing Problems with Accounts If you have problems with your Unix account You need to deal with the CS Operators I discuss this further here: http://www.cs.umb.edu/~jane/cs114/fixing_problems_with_accounts.html Finding Your DrJava Files After you have compiled and run a DrJava file You need to move it to the Unix machines at UMB If you followed my advice, you have already created a directory for your DrJava files... And you know where it is 6
Tips If you have not done this or forgotten where you created the directory Follow this procedure Click on the Open button at the top left of the DrJava window A window will appear showing the contents of the directory holding your files At the top of the window is a drop down box which shows the name of that directory Click on that drop down box and you will see the path to that directory It s a good idea to create a separate folder or directory for your DrJava files 7
Review Java Classes Java is an object oriented language A class is a group of objects that has common properties. Classes are the templates used to create objects Classes are software written in Java Objects are the contents of RAM created from a class There is only one class for each object but a single class can create many objects 8
Java Classes Every Java source file contains at least one class... and the name of the source file is the class name with the.java extension A Java program is made up of one or more source files... each containing at least one Java class 9
Writing a Java Class Every Java program is contained in a Java class A Java class has a particular format If you do not use this format, the code will not compile... Here is the format for writing a simple Java class public class CLASS_NAME { METHOD... } Each class contains one or more methods... which must be inside the curly braces, { }... 10
Java Methods The actual work in a Java program is done by methods Methods perform a specific task Methods are the basic unit of work in a Java program Methods are composed of individual statements A statement is a line of code that contains a complete Java command Every Java statement must have a semicolon, ;, at the end If you leave it off, you will get a compile error Every method starts with a method header The method header contains important information about the method... including the name of the method 11
The main Method In order to run a Java program, there must be one source code file with a method called main The main method starts the action when you run a Java program A class without a main method cannot be run by itself The main method is in overall control of what happens when you run a Java program It usually does this by calling other methods 12
The main Method The main method has the following format public static void main(string[] args) { STATEMENT;... } The method header for a main method is always public static void main(string[] args) 13
New Material The Linux/Unix Home Directory Each Linux/Unix account has a home directory The home directory is where you find yourself after you first log in to a Linux or Unix machine Your home directory is where your.forward file needs to be On the UMB Linux machines all home directories are contained in a single directory called /home Since my account name it jane... my home directory is /home/jane 14
The Linux/Unix Home Directory If you get lost in the Unix filesystem you can always get back to your home directory by using cd without any arguments cd You can specify any file on the system with a list of directories This list of directories is called a path If I wanted to see what was in the hw21 directory... inside the hw directory inside the it114 directory I would use the following ls it114/hw/hw21 15
Basic Unix Commands In order to use the Unix machines for this class, you need to know a few Unix commands Each command you type must be letter for letter correct When you connect to users3you will be in your home directory If you ever get lost, you can get back to your home directory by typing cd To see the contents of your current directory, type ls To go to a new directory, use the cd command. cd stands for change directory 16
Basic Unix Commands Follow cd with the name or address of the directory you want to enter cd NAME_OR_ADDRESS_OF_DIRECTORY A directory is the same thing as a folder Whenever you go to a new directory, its a good idea to look at the contents of that directory using the ls command The pwd command will tell you your current directory Use pwd without any arguments pwd pwd stands for print working directory Use pwd whenever you are not sure of your current directory 17
Basic Unix Commands To create a new directory, use mkdir followed by the directory name mkdirdirectory_name To remove a file, use rm. rm stands for remove rm FILENAME To move a file use mv. mv stands for move mv FILENAME NEW_DIRECTORY You also use mv to change the name of a file or directory mv CURRENT_NAME NEW_NAME To see the contents of a file use cat. cat stands for concatenate cat FILENAME Check the Unix Essentials page for more information 18
Indenting Java Code As long as a Java program is syntactically correct, the compiler will not complain But compilers aren't the only ones looking at Java source code files People have to read them too Two types of people have to read Java programs The person who writes them The people who maintain them To help people read programs, they must be indented properly 19
Indenting Java Code Compare this Java class public class NumberTriangle1 { } with this one public static void main (String[] args){ } for (int i = 1; i <= 7; i++){ } for(int j = 1; j <= i; j++){ } System.out.println(); System.out.print(i); public class NumberTriangle2 {public static void main (String[] args){for (int i=1;i<=7;i++){for(int j=1;j<=i;j++){system.out.print(i);}system.out.println();}}}} 20
Indenting Java Code The code in both is the same, except for the different class names and they both produce the same output 1 22 333 4444 55555 666666 7777777 21
Indenting Java Code Which would you rather have to debug? Indentation is a part of what is called coding style which I'll say more in a future class The rules of indentation are simple When an opening brace appears, increase the indentation of the lines that follow it by one tap stop When a closing brace appears, reduce the indentation by one tap stop A class definition should always start at the left side of the page Every method within that class should be indented one tab stop... and every statement inside a method should be indented one more tab stop 22
Indenting Java Code We see this style employed in Hello.java public class Hello { } public static void main(string[ ] args) { System.out.println("Hello, world!") ; } If you do not indent your code properly... I will deduct points 23
Indenting in DrJava DrJava makes it easy to indent your code properly. All you have to do is hit the Tab key You can do this with the text insertion point anywhere on the line you do not have to go to the beginning of the line to have DrJava indent your code properly If you have a source code file that is not properly indented 24
Indenting in DrJava You can select the contents of the entire file... using Cntrl A on a PC... or Command A on a Mac 25
Indenting in DrJava then hit the Tab key DrJava will indent the entire file 26
Strings As you will see shortly, Java treats different types of data differently One type of data are integers like 1, 2 and 3 Another type are a series of characters like "Hello, world!" You can add integers 1 + 2 = 3. But not groups of characters Integers and sequences of characters are examples of data types Data types are very important in Java You cannot declare a variable without specifying its type This is one of those things that Java is very fussy about The first chapter of the textbook introduces the first data type... 27
Strings strings, which are a series of characters, one right after the other Strings can include spaces and tabs In Hello.java, we saw the string "Hello, world!" The representation of a string value within the source code is called a string literal In Java, a string literal must be enclosed with double quotation marks You must use double quotes, not single quotes A string literal must be on a single line A string literal cannot continue onto the next line 28
Printing a Line in Java Java methods consist of one or more statements Each statement is a line of code containing a single action and must be have a semi- colon at the end The first Java statement you need to learn prints a line of text It has the following form System.out.println(STRING); Remember, STRING is a placeholder You replace it with something you want to print like "Hello world!" 29
Printing a Line in Java This may seem like a lot of characters to perform a simple action The statement looks like this due to Java's object oriented design Don't worry about why the extra stuff is needed... just memorize it like some sort of magical incantation If you leave out System.out, you will get an error message 30
Printing a Line in Java The compiler objects because it does not know println it only knows System.out.println System.out.println statement prints whatever is inside the parentheses and then advances to the next line If the parentheses are empty, it simply prints a blank line 31
Escape Sequences When we think about text characters, we usually think about letters, digits and punctuation But the Java character set includes some special characters... such as the Tab and newline characters... which don't print a character you can see But you sometimes want to use these characters inside a string You can do this in Java using an escape sequence An escape sequence is a set of two characters... the first of which is a backslash, \ 32
Escape Sequences Here is a list Sequence Represents \t Tab character \n New line character \ Double quote \\ backslash 33
Escape Sequences You can use an escape sequence to print more than one line of output With a single println statement 34
The print Statement But what if you wanted to print something but not move to the next line? Then you would have to use System.out.print... which has the following form System.out.print(STRING); Let s look at an example notice that I had to put a space as the last character in the first three lines If I had not done this, the output would be: To beor not to be. That isthe question. 35
Identifiers A important concept in computer languages is the identifier An identifier is a name of something like a class, method or variable Identifiers must start with a letter That letter can be followed by any number of other letters and digits Java thinks of two special characters as letters... when creating an identifier $ - dollar sign _ - underscore 36
Identifiers The following are legal identifiers two_plus_two _count $2donuts MAX_COUNT But these are not legal identifiers two+two hi there hi- There 2by4 37
Naming Conventions Part of good coding style is choosing good identifiers The identifier should be descriptive And it should follow the following conventions All class names should start with a Capital letter All methods names and variable names should start with a lowercase letter Constant name should be ALL CAPITALS Don't hesitate to use more than one word in an identifier When you combine several words to form an identifier... each new word should begin with a capital letter The make it easier to spot the words inside the identifier This convention is called camel case 38
Naming Conventions Camel case cannot be used with constants Instead we use the underscore character, _... to separate the words in the identifier of a constant Java is case sensitive... so the following are all distinct Java identifiers maxvalue MaxValue MAXVALUE maxvalue 39
Keywords Java reserves certain words for its own use These words are called keywords If you try to use them as identifiers, you will get an error Here is the complete list of Java keywords 40
Readability The way the statements in a program are arranged on the page affect how easily the code can be read Consider the following code public class Ugly{ public static void main(string[ ] args) { System.out.println("This is ugly code") ; } } This code will compile and run, but it is very hard to read Good coding style uses spaces and tabs and puts new constructs on different lines The following rules will make you code much more readable Put class and method headers on lines by themselves Put no more than one statement on each line Indent your program properly Use blank lines to separate parts of the program (e.g., methods) You will lose points if you don't do this 41
Java Comments There are three types of comments in Java Single line comments Multiple line comments JavaDoc comments The third type of comment, JavaDoc comments, are not covered in this course Whenever two slashes appear one after the other, //... Java ignores anything else on the rest of the line This is a single line comment mindivisor = 1; // divisor cannot be zero or division by zero error will occur 42
Java Comments A multiple line comment starts with a slash followed immediately by an asterisk, /* Any text between this pair and an asterisk followed by a slash, */, is ignored by Java Here is an comment from the code for my Masters project The multiple line comment allows you to write a lengthy description of what is going on The actual comment as it appeared in the code looked a different... because it is better style to have a * at the beginning of each line of a multiple line comment to make it clear that the comment continues 43
Java Comments Notice that The comment starts on a line with no text and ends on a line with no text Each line of the comment other than the first and last has a single asterisk at the start of the line All the asterisks are in the same column Multiple line comments are also useful in debugging The most important idea in debugging is identifying the source of the problem Often, when doing this, you need to turn off a section of code The easiest way to do this is by wrapping the code section in a multiple line comment 44