Objects and Classes 1: Encapsula3on, Strings and Things CSC 121 Fall 2015 Howard Rosenthal

Size: px
Start display at page:

Download "Objects and Classes 1: Encapsula3on, Strings and Things CSC 121 Fall 2015 Howard Rosenthal"

Transcription

1 Objects and Classes 1: Encapsula3on, Strings and Things CSC 121 Fall 2015 Howard Rosenthal

2 Lesson Goals Understand objects and classes Understand Encapsulation Learn about additional Java classes The Random class The String class The StringBuilder class The File Class The DecimalFormat class 2

3 What is an Object? An object has characteristics or attributes. An object also has behaviors The attributes are the data associated with an object The behaviors are the methods used to manipulate the objects We ve already seen and made a bit of use of some objects including: arrays Strings Object oriented programming is all about manipulating objects to perform tasks this matches the way we really think about things 3

4 Some Examples Objects Shoe A remote control A computer mouse or keyboard Non-objects Blue Fast Rough Interesting Return Digest Many of the non-objects are either attributes or methods of the object 4

5 Some Common Characteris8cs of Objects An object is made of tangible material (the pen is made of plastic, metal, ink). An object holds together as a single whole (the whole pen, not a fog). An object has properties (the color of the pen, where it is, how thick it writes...). An object can do things and can have things done to it. 5

6 Iden8fying Objects An object has identity (each object is a distinct individual). An object has state (it has various properties, which might change). An object has behavior (it can do things and can have things done to it). 6

7 A Simple Example Is the tube of tennis balls an object? Yes. It has identity (my tube of balls is different than yours), it has states (opened, unopened), properties (brand name, location), and behavior (although not much). Is each tennis ball an object? Yes. It is OK for objects to be part of other objects. Although each ball has nearly the same state and behavior as the others, each has its own identity. Could the top two balls be considered a single object? Not ordinarily. Each has its own identity independent of the other. If they were joined together with a stick you might consider them as one object. Is the color of the balls an object? No. It is a property of each ball. Is your understanding of tennis balls an object? Probably not, although it is unclear what it is. Perhaps it is a property of the object called "your brain." 7

8 Encapsula8on Encapsulation is a computer language feature that packages attributes and behaviors into a single unit. The data and the methods comprise a single entity When we create objects from the class Scanner it has attributes i.e. System.in and behaviors the various methods 8

9 Object Oriented Programming In object-oriented programming, the programmer uses a programming language (such as Java) to describe various objects. When the program is run (after being compiled) the objects are created (out of main storage) and they start "doing things" by running their methods. Creating an object allows us to access its methods. The methods must execute in the correct order. For an application, the first method to run is the method named main(). There should be only one method named main() in an application. In a small application, main() might do by itself all the computation that needs to be done. In a larger application, main() will create objects and use their methods. 9

10 Classes A class is a template, or blueprint from which objects are created A programmer may define a class using Java, or may use predefined classes that come in class libraries. - We ve already done that!!! A class is merely a plan for a possible object. It does not by itself create any objects. When a programmer wants to create an object the new operator is used with the name of the class. Creating an object is called instantiation. Up to now we have worked with single classes that have included the main method Individual classes usually don t include a main method, rather the main method instantiates objects from classes, and these objects are then used by the various methods (including the main method) Every time we create an object from a class using the keyword new the object has a reference variable that refers to that type of object If the reference is lost then the object becomes garbage 10

11 An Example The Circle Class Is Instan8ated (1) double radius; class Circle double area() { return πr 2 } double circumference() { return 2πr } radius 5.6; radius 19.2; radius 3.4; three Circle objects double area() double circumference() double area() double circumference() double area() double circumference() 11

12 An Example The Circle Class Is Instan8ated (2) Circle ovalguy; ovalguy = new Circle(5.6); or Circle ovalguy = new Circle(5.6); Remember- the new does the instantiation Until then all you ve created is a reference variable In Chapter 10 we describe how to build the constructors needed to create objects. 12

13 Java Libraries and Packages Packages are large files that contain multiple classes Packages are nothing more than logical groupings of classes You can import a single class or an entire package Importing an entire package does not increase the size of the executable code, which only includes those classes actually used We ve done this already for a few months with the Scanner class: import java.packagename.classname i.e. import java.util.scanner import java.packagename.* i.e. import java.util.* 13

14 The Random class(1) The Random class is another class that is imported with the import java.util.*; or import java.util.random; It has a many more methods and is therefore more useful than the Math.random() method (even though that basic Math package did not have to be imported Remember how we achieved the ability to read input from the screen: Scanner keyboard = new Scanner(System.in); Then we had a keyboard reader that could take advantage of all the methods in the class: number = keyboard.nextint(); dnumber = keyboard.nextdouble(); 14

15 The Random class(2) So lets create a new object called randy from the class Random Random randy = new Random(); // note that there are no data attributes, also, that randy is a reference variable that now has a value. Then we can use the methods of Random: int number = randy.nextint(n); // returns an integer greater than or equal to zero but less than n (where n is an integer) In general the format is: referencetoobject.method(any necessary parameters) 15

16 The Random class(3) Method & Description boolean nextboolean() This method returns the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence. void nextbytes(byte[] bytes) This method generates random bytes and places them into a user-supplied byte array. double nextdouble() This method returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence. float nextfloat() This method returns the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this random number generator's sequence. double nextgaussian() This method returns the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence. int nextint() This method returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence. int nextint(int n) This method returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. long nextlong() This method returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence. void setseed(long seed) This method sets the seed of this random number generator using a single long seed. 16

17 The Random class(4) An example with dice Random die = new Random(); int dicesum = (die.nextint(6)+1) + (die.nextint(6)+1); Those two lines would give us the sum of the two dice rolled You could create a coin object and then flip it. 17

18 The java.lang package This package is imported automatically into every application, so you don t need to use an import statement The java.lang package includes many useful classes Math class (discussed previously and not to be confused with the Random class) String class very useful class within java String operations are handled much better in modern object-oriented languages than in older third generation languages such as Fortran 18

19 The String Class The String class allows you to create String objects a String object is not a primitive data type a String variable is a reference to a String object An example: String mydog = new String( Fido ); Because String objects are so common there is a shortcut used to initialize or assign an reference value to a String object: String mydog = Fido ; Remember this assigns the address of the String literal Fido to the reference mydog 19

20 The String Class (2) There are many methods that are available on a String object int length() is a method that returns the String length: mydog.length() returns 4 An empty String has no characters and length equals 0 char charat(int i) returns the character at position i (remember we start counting from 0): mydog.charat(2) returns d String next() returns a reference to the next input String i.e. keyboard.next() This method skips whitespaces and returns the next group of characters as a String 20

21 String Concatena8on - Review Concatenation is the process of joining or linking Strings together The operator is + We ve already seen concatenation: System.out.println( A boy who is +age + is a man ); When you concatenate you create a new reference address String s = Sam String t = Thomas String w = s + +t = Sam Thomas w.length() = 10 21

22 Strings and Characters - Review A + B = 131 (integer) A + B = AB (String) A + B = AB (String) + A + B = AB (String) A gets cast to String A + B + = 131 (String) = 7 (String) = 34 (String) Key is that without parentheses we are reading left to right 22

23 String Opera8ons String touppercase() converts a String from lower to upper case String s1 = lower String s2 = s1.touppercase(); System.out.println(s1 + +s2); The output is: lower LOWER Note: s1 is not capitalized.; the method returns a new String reference that s2 refers to All java String operations can be found at: There is also a new document called Class String Documentation in the Reference material area 23

24 Common String Methods (1) Method Explanation Example char charat(int index) int compareto(string t) int comparetolgnorecase(string t) String concat(string t) s.charat(i) returns the character at index i. All Strings are indexed from 0. compares two Strings, character by character, using the ASCII values of the characters.s.compareto(t) returns a negative integer/ 0/positive integer if the String s lexicographically precedes/equals/ follows the String t. similar to compareto(...) but ignores differences in case. s.concat(t) returns s with t appended. boolean endswith(string suffix) s.endswith(t) returns true if t is a suffix of s. boolean startswith(string prefix) s.startswith(t) returns true if t is a pre x of s. boolean equals(object t) (The strange parameter will make sense later. For now, think of the parameter as String.) boolean equalslgnorecase(string t) s.equals(t) returns true if s and t are identical. s.equalsignorecase(t) returns true if s and t are identical, ignoring case. String s "Titanic"; s.charat(3) returns 'a' String s Shrek ; String t Star Wars ; String u Shrek ; s.compareto(t) returns a negative number. s.compareto(u) returns 0. t.compareto(s) returns a positive number. String s E.T. ; String t e.t. ; s.comparetoignorecase(t) returns 0. String s Spider ; s.concat( -Man ) returns Spider-Man. String s Forrest Gump ; s.endswith( ump ) returns true String s Jurassic Park ; s.startswith( Jur ) returns true s.startswith( jur ) returns false String s FINDING NEMO ; String t Finding Nemo ; s.equals(t) returns false s.equals( FINDING NEMO ) returns true String s FINDING NEMO ; String t Finding Nemo ; s.equalsignorecase(t) returns true 24

25 Common String Methods (2) Method Explanation Example int indexof(string t) int indexof(string t, int from) s.indexof(t) returns the index in s of the first occurrence of t and returns 1 if t is not a substring of s. s.indexof(t, from) returns the index in s of the first occurrence of t beginning at index from; an unsuccessful search returns -1. String s The Lord Of The Rings ; s.indexof( The ) returns 0; s.indexof( Bilbo ) returns 1. String s The Lord Of The Rings ; s.indexof( The, 6) returns 12; int length() s.length() returns the number of characters in s. String s Jaws ; s.length() returns 4 String replace(char oldchar, char newchar) String tolowercase() String touppercase() String trim() s.replace(oldch, newch) returns a String obtained by replacing every occurrence of oldch with newch. s.tolowercase() returns a String formed from s by replacing all uppercase characters with lowercase characters. s.touppercase() returns a String formed from s by replacing all lowercase characters with uppercase characters. s.trim() returns the String with all leading and trailing white space removed. String s Harry Potter ; s.replace ( r, m ) returns "Hammy Pottem" String s The Lion King ; s.tolowercase() returns "the lion king" String s The Lion King ; s. touppercase() returns "THE LION KING" String s Attack of the Killer Tomatoes ; s.trim() returns "Attack of the Killer Tomatoes" 25

26 String Opera8ons substring (1) There are two versions of substring String substring( int start) String substring( int start, int to ) Create a new String object that contains the characters of the method's String from the index start to the end of the String. Create a new String object that contains the characters of the method's String from the index start and continuing to index to-1. 26

27 String Opera8ons substring (2) Line of code: String line = "buttercup" ; New String buttercup String a = line.substring( 0 ); String b = line.substring( 6 ); String c = line.substring( 9 ); String d = line.substring( line.length() ); String e = line.substring( line.length()+1 ); String f = line.substring( -1 ); buttercup (a new String is created, containing all the characters of the original) cup (an empty String is created) (an empty String is created) EXCEPTION EXCEPTION 27

28 String Opera8ons substring (3) Line of code: String line = "buttercup" ; New String "buttercup" String a = line.substring( 0, 6 ); "butter" String b = line.substring( 6, 9 ); String c = line.substring( 0, 1 ); "cup" "b" String d = line.substring( 0, 0 ); "" String e = line.substring( 5, 5 ); "" String f = line.substring( 4, line.length()+1 ); EXCEPTION 28

29 More on Strings and String Methods - References String encrypt(string msg, int shift) really is accepting a String reference, not the String itself Strings are immutable You can change the value in the reference pointer, but not the String itself String s = Big ; s = s.tolowercase(); // A new String is created s Big big 29

30 More on Strings and String Methods - equals Be careful with == and Strings. you are comparing references, not Strings themselves use boolean equals(str1) to compare 2 Strings strx.equals(str1) In the example: String s = new String( ABC ); String t = new String( ABC ); s ==t is not true (s and t refer to different objects s.equals(t) is true- they have the same String value 30

31 More on Strings and String Methods compareto (3) Being able to compare Strings allows us to alphabetize (sort) them, which in turn allows us to search them use int s.compareto(t) or int s.comparetoignorecase(t) String s Shrek ; String t Star Wars ; String u Shrek ; s.compareto(t) returns a negative number. s.compareto(u) returns 0. t.compareto(s) returns a positive number. In other words, if the String that is invoking the method occurs earlier in an alphabetical list than the parameter the number that is returned is negative 31

32 The String Class Some Special Characteris8cs We typically create Strings without the use of new String day6 = Friday ; This creates a new object named day6 However if I now execute the statement String dayf = Friday ; a new object is not created, dayf just refers to the same object as day6 But if I now execute the following statement: String friday = new String( Friday ); a new object is created See String_Test_Example.java 32

33 Visualizing the Friday Example day6 Friday dayf friday Friday constructors constructors methods methods 33

34 String Opera8ons An example Write a program that encrypts a message using the Caesar Cypher. The program accepts one line of text and a character shift value. Eliminate all nonalphanumeric characters and blanks and print the result as all capitals. Enter a message on one line Hello Jim XRAY Enter an integer in the range of The encrypted message is OLSSVQPTEYHF Strategy Capitalize Eliminate non-characters Shift there are 26 characters so we wrap around if character values go beyond 90, the ASCII value of Z See CaesarCipher.java 34

35 The Null Value and Strings null is a special value that means "no object." Your program should set a reference variable to null when it is not referring to any object. Programs often set variables to null when they are declared: String a = null; class NullDemo1 { public static void main (String[] arg) { String a = "Random Jottings"; String b = null; String c = ""; if ( a!= null ) System.out.println( a is " +a ); if ( b!= null ) System.out.println("b is " +b ); if ( c!= null ) System.out.println( c is " +c ); } } 35

36 The nextline() Method (1) nextline() advances the Scanner to the beginning of the next line and returns a reference to a String object comprised of the the characters that were read (or skipped if you wish) in the process, including whitespace, but not including the newline character System.out.print( Enter message on one line: ); String message = keyboard.nextline(); System.out.print( Enter an integer in the range 0-25 ); int shift = keyboard.nextint(); If the inputs are Cato 8 then message points to Cato and shift gets the value 8. 36

37 The nextline() Method (2) However, if you reverse the process: System.out.print( Enter an integer in the range 0-25 ); int shift = keyboard.nextint(); System.out.print( Enter message on one line: ); String message = keyboard.nextline(); The results are different: In the second case once you read the 8 the Scanner still hasn t moved to the next line The nextline() then see nothing prior to the line return and returns an empty String In this case using next instead of nextline fixes the problem 37

38 The StringBuilder Class (1) StringBuilder is a different class than String, even though they do many of the same things With the StringBuilder Class you do not create a new object with each alteration of the String The StringBuilder class may improve performance for concatenation and modification The String class is preferable and more efficient for read-only Strings While there are some similar methods, remember that the type of object determines which method will be executed and that some overloaded method may execute differently A complete list of StringBuilder Methods can be found at: Also uploaded into references 38

39 The StringBuilder Class (2) To create a StringBuilder object: StringBuilder sb = newstringbuilder(); //initial capacity is 16 characters StringBuilder sb = newstringbuilder(50); //initial capacity is 50 characters StringBuilder sb = newstringbuilder( Hello ); //initializes sb to Hello The capacity of a StringBuilder object expands automatically 39

40 The StringBuilder Class (3) How the equals method works for StringBuilder vs. String String s = new String( Monkey Business ); String t = new String( Monkey Business ); System.out.println(s.equals(t)); In the case above true is printed out -for String objects the equals method compares values, not references StringBuilder s = new StringBuilder( Monkey Business ); StringBuilder t = new StringBuilder( Monkey Business ); System.out.println(s.equals(t)); In the case above false is printed out for StringBuilder objects the equals method compares references, not values 40

41 The Mysterious String [] args String [] args is simply an array of Strings i.e. reference pointer to objects It allows you to send inputs to the main method via the command line public class TestMain { public static void main(string [] args) { System.out.println("Hello " + args[0]); System.out.println("Hello " + args[1]); } If you execute: Java TestMain Jerry Newman The output is: Hello Jerry Hello Newman What happens is that Java implicitly creates an array for you of a length equal to the number of input parameters i.e. in the above program what happens is: String [] args = { Jerry, Newman }; You have an array args of type String and args.length is equal to 2. See the TestMain application 41

42 Files A File is a collection of data saved under a single name Files can be structured or free text Java creates File objects Once a File is instantiated you can read or write from the file This is very convenient when testing programs, since you can use the same data over and over again 42

43 Input and Output There are many data sources and destinations that can be used 43

44 Processing Streams A processing stream operates on the data supplied by another stream. Often a processing stream acts as a buffer for the data coming from another stream. Character streams are intended exclusively for character data. Byte streams are intended for general purpose input and output. A buffer is a block of main memory used as a work area. For example, disks usually deliver data in blocks of 512 bytes, no matter how few bytes a program has asked for. Usually the blocks of data are buffered and delivered from the buffer to the program in the amount the program asked for. 44

45 Using Files in java Programs (1) You must include the following statement before the class statement import java.io.*; or the following 3 specific classes in the java.io package import java.io.file; import java.io.printwriter; import java.io.ioexception; You must also include the statement throws IOException after the parentheses of any method that uses File class methods: public static void main (String [] args) throws IOException You must also create a file in the program using the new parameter File inputfile = new File( filename ); If the filename isn t in the same directory as the class file you must use the full path name You can create a String variable with the filename first allows greater flexibility i.e. String inputfilename = input.txt ; Finally create a Scanner for the new input file Scanner inputreader = new Scanner( filename ); or Scanner inputreader = new Scanner(inputfilename); Once this is done you can use the same input functions as you have used previously 45

46 Using Files in java Programs (2) You need to use the File method.exists() i.e. inputfile.exists(); This return true if an input file exists, false otherwise if (!inputfile.exists()) { System.out.println("Error: "+ inputfilename + " not found"); System.exit(0); //This will cause you to exit the program if there is no input file to read from } You want to use the Scanner method hasnext() i.e. inputreader.hasnext(); This method returns a false when you reach the end of an input file You need to close the file that the Scanner is reading at the end Use the method.close(); i.e. inputreader.close(); See Test_File_Input.java. And Test_File_Input_v2.java 46

47 Using Files in java Programs (3) Using an output file involves almost the same process File outputfile = new File( filename ); If the filename isn t in the same directory as the class file you must use the full path name You can create a String variable with the filename first allows greater flexibility i.e. String outputfilename = output.txt ; File outputfile = new File(outputfilename); PrintWriter outputwriter = new PrintWriter(outputFile); outputfile is a reference variable for a new object of type File outputwriter is a reference variable for a new object of type PrintWriter Now you can use outputwriter to write to the file i.e. outputwriter.println((message +intvar + is whatever ); You need to close the file that the PrintWriter is writing to at the end Use the method.close(); i.e. outputwriter.close(); 47

48 Examples: Reversal.java and Reversal2.java Read in lines one by one from an input file, reverse all the characters from the input file, and write the results to an output file. Perform the reversal in a separate method called reverser Strategy Create an input text file In the code create your File, Scanner and PrintWriter Objects Read in text a line at a time from the file until file is completely read Call reverser to reverse the text reverser reads in the characters from back to front to create the new String which it passes back to main Alternatively read the String from front to back and append each new character to front of the new String Write the String to the output file 48

49 Example EncryptFile.java Write a program that encrypts a file of text one-line at a time using an interactively supplied code word and after capitalizing the text outputs that text to an output file. Assume that the text line contains only alpha characters and no white spaces. Use the code word, which has no spaces, as follows: Convert the code word to capitalized code word Use the code word one character at a time to shift corresponding character in message by the position of the code word i.e. if Code word is Dram and word to be coded is Hungrier shift as follows: H 3, U 17 N 0, G 12, R 3, I 17, E 0, R 12; Strategy: Create necessary objects for input and output Figure out shift Shift character i based on the position in the alphabet of the character in the code word, going through the code word characters in a round robin method Add character to message line When complete print line to the output file 49

50 The DecimalFormat Class (1) Allows you to easily format decimal number by pattern pattern looks like: 0.### The 0 s and # s tells you how many places to display With a 0 the number (even a 0) is always displayed Need to either create a separate DecimalFormat object for each pattern or reset the instance variable for the object Use import java.text.* or import java.text.decimalformat to use the DecimalFormat class 50

51 The DecimalFormat Class (2) DecimalFormat myformat = new DecimalFormat( 0o.### ); double x = ; double y =.9876 System.out.println(myformat.format(x) + + myformat.format (y)); myformat.applypattern( ##.## ); // changes the pattern System.out.println(myformat.format (x) + + myformat.format (y)); output: Note: DecimalFormat always rounds (up or down) 51

52 The DecimalFormat Class (3) value of double format pattern Output String ###.###" " " ###.#" "123.5" ###.##" "123.4" #,###.## 1, ###" "123" ###" " " " " " " "0.00" "89.01" "0." "89." " " " " "000.0" "-123.5" "0.00" "-89.01" "0." "-89." -1.1 " " " " 0.0" "- 89.0" 52

53 The DecimalFormat Class (4) Summary DecimalFormat is a class We create objects with specific formatting The String format(string pattern) is the method So far we have shown the method with one argument However, you can have two arguments when you create a DecimalFormat object: DecimalFormat numform = new DecimalFormat(" 00.00;-00.00"); System.out.println( "Pos = " + numform.format(12.6) ); System.out.println( "Neg = " + numform.format(-12.6) ); In this case we retain right justification

54 PuPng it all together RandomArray.java Write a program that does the following: The main program requests from the user the dimensions of a two dimensional array. The main program creates a two-dimensional array. The main program calls a method booleanfull that randomly fills the two-dimensional array with either true or false values in each cell. The main program then calls a second method called calcpercent that returns the percentage of elements in the two dimensional array that are true. The main program then prints out the array and on the next line prints out the percent of cells in the array that have the value true true formatted to two decimal places. Hint: You ll need to create a Random object and use the method nextboolean() in the booleanfull method 54

55 Programming Exercises Class (1) Write a program called AddBlanks that reads in lines from a file one at a time and adds a blank after every fourth character. Write to an output file. 55

56 Programming Exercises Class (2) Exercise 2. Uppercase Conversion Write a program that accepts a String and displays another String composed of the characters of the first String but with all lowercase letters capitalized. Any non-alphabetical letters, such as punctuation, should be left unchanged. For example, the String When Homer blew up the nuclear plant, he yelled #!#!#!& DOH &&####!!!! should become WHEN HOMER BLEW UP THE NUCLEAR PLANT, HE YELLED #!#!#!& DOH &&####!!!! 56

57 Programming Exercises Class (3) Exercise 8. Counting Words Write a method that accepts a String and returns the number of words in the String. For example, the String This sentence has too many words in it. has 8 words. 57

58 Programming Exercises Lab (1) Exercise 3. Random Strings Write a program that prints 25 random String of length 4 such that each String is composed of uppercase alphabetical characters. First do this without storing in an array, and then after storing in an array String [] randstr = new String [25]; Which you then print out all at once line by line. 58

59 Programming Exercises Lab (2) Exercise 12. College Transcript A text file stores the courses you have taken along with the corresponding grade (A,B,C, D, F) that you received in each course. The file might look like: Intro to Sociology A Physics Experimental Psych o o o B C Write a program that uses such a file to calculate a GPA. Print the GPA with two decimal places. 59

Objects and Classes 1: Encapsulation, Strings and Things CSC 121 Fall 2014 Howard Rosenthal

Objects and Classes 1: Encapsulation, Strings and Things CSC 121 Fall 2014 Howard Rosenthal Objects and Classes 1: Encapsulation, Strings and Things CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Understand objects and classes Understand Encapsulation Learn about additional Java classes The

More information

Objects and Classes 1: Encapsula3on, Strings and Things CSC 121 Fall 2016 Howard Rosenthal

Objects and Classes 1: Encapsula3on, Strings and Things CSC 121 Fall 2016 Howard Rosenthal Objects and Classes 1: Encapsula3on, Strings and Things CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand objects and classes Understand Encapsulation Learn about additional Java classes The Random

More information

Objects Classes Strings Review CSC 123 Fall 2018 Howard Rosenthal

Objects Classes Strings Review CSC 123 Fall 2018 Howard Rosenthal Objects Classes Strings Review CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Review objects and classes Review Encapsulation Review the Random class Review the String class Review arrays of String objects

More information

File Input and Output Review CSC 123 Fall 2018 Howard Rosenthal

File Input and Output Review CSC 123 Fall 2018 Howard Rosenthal File Input and Output Review CSC 123 Fall 218 Howard Rosenthal Lesson Goals The File Class creating a File object Review FileWriter for appending to files Creating a Scanner object to read from a File

More information

Final Exam. CSC 121 Fall Lecturer: Howard Rosenthal. Dec. 13, 2017

Final Exam. CSC 121 Fall Lecturer: Howard Rosenthal. Dec. 13, 2017 Your Name: Final Exam. CSC 121 Fall 2017 Lecturer: Howard Rosenthal Dec. 13, 2017 The following questions (or parts of questions) in numbers 1-17 are all worth 2 points each. The programs have indicated

More information

Final Exam. CSC 121 Fall Lecturer: Howard Rosenthal. Dec. 13, 2017

Final Exam. CSC 121 Fall Lecturer: Howard Rosenthal. Dec. 13, 2017 Your Name: Final Exam. CSC 121 Fall 2017 Lecturer: Howard Rosenthal Dec. 13, 2017 The following questions (or parts of questions) in numbers 1-17 are all worth 2 points each. The programs have indicated

More information

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string COMP 202 Built in Libraries and objects CONTENTS: Introduction to objects Introduction to some basic Java libraries string COMP 202 Objects and Built in Libraries 1 Classes and Objects An object is an

More information

A variable is a name for a location in memory A variable must be declared

A variable is a name for a location in memory A variable must be declared Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total;

More information

Using Java Classes Fall 2018 Margaret Reid-Miller

Using Java Classes Fall 2018 Margaret Reid-Miller Using Java Classes 15-121 Fall 2018 Margaret Reid-Miller Today Strings I/O (using Scanner) Loops, Conditionals, Scope Math Class (random) Fall 2018 15-121 (Reid-Miller) 2 The Math Class The Math class

More information

We now start exploring some key elements of the Java programming language and ways of performing I/O

We now start exploring some key elements of the Java programming language and ways of performing I/O We now start exploring some key elements of the Java programming language and ways of performing I/O This week we focus on: Introduction to objects The String class String concatenation Creating objects

More information

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Final Examination

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Final Examination First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Final Examination Thursday, December 11, 2008 Examiners: Mathieu Petitpas [Section 1] 14:00

More information

STUDENT LESSON A10 The String Class

STUDENT LESSON A10 The String Class STUDENT LESSON A10 The String Class Java Curriculum for AP Computer Science, Student Lesson A10 1 STUDENT LESSON A10 The String Class INTRODUCTION: Strings are needed in many programming tasks. Much of

More information

Classes and Objects Part 1

Classes and Objects Part 1 COMP-202 Classes and Objects Part 1 Lecture Outline Object Identity, State, Behaviour Class Libraries Import Statement, Packages Object Interface and Implementation Object Life Cycle Creation, Destruction

More information

Chapter 2 Part 2 Edited by JJ Shepherd, James O Reilly

Chapter 2 Part 2 Edited by JJ Shepherd, James O Reilly Basic Computation Chapter 2 Part 2 Edited by JJ Shepherd, James O Reilly Parentheses and Precedence Parentheses can communicate the order in which arithmetic operations are performed examples: (cost +

More information

appreciate the difference between a char and a string understand and use the String class methods

appreciate the difference between a char and a string understand and use the String class methods 1 8 THE STRING CLASS Terry Marris 16 April 2001 8.1 OBJECTIVES By the end of this lesson the student should be able to appreciate the difference between a char and a string understand and use the String

More information

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while CSCI 150 Fall 2007 Java Syntax The following notes are meant to be a quick cheat sheet for Java. It is not meant to be a means on its own to learn Java or this course. For that you should look at your

More information

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural

More information

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural

More information

Section 2: Introduction to Java. Historical note

Section 2: Introduction to Java. Historical note The only way to learn a new programming language is by writing programs in it. - B. Kernighan & D. Ritchie Section 2: Introduction to Java Objectives: Data Types Characters and Strings Operators and Precedence

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

STRINGS AND STRINGBUILDERS. Spring 2019

STRINGS AND STRINGBUILDERS. Spring 2019 STRINGS AND STRINGBUILDERS Spring 2019 STRING BASICS In Java, a string is an object. Three important pre-built classes used in string processing: the String class used to create and store immutable strings

More information

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI CSCI 2010 Principles of Computer Science Data and Expressions 08/09/2013 CSCI 2010 1 Data Types, Variables and Expressions in Java We look at the primitive data types, strings and expressions that are

More information

More non-primitive types Lesson 06

More non-primitive types Lesson 06 CSC110 2.0 Object Oriented Programming Ms. Gnanakanthi Makalanda Dept. of Computer Science University of Sri Jayewardenepura More non-primitive types Lesson 06 1 2 Outline 1. Two-dimensional arrays 2.

More information

AP Computer Science A

AP Computer Science A AP Computer Science A 1st Quarter Notes Table of Contents - section links Click on the date or topic below to jump to that section Date : 9/8/2017 Aim : Java Basics Objects and Classes Data types: Primitive

More information

Intro to Strings. Lecture 7 CGS 3416 Spring February 13, Lecture 7 CGS 3416 Spring 2017 Intro to Strings February 13, / 16

Intro to Strings. Lecture 7 CGS 3416 Spring February 13, Lecture 7 CGS 3416 Spring 2017 Intro to Strings February 13, / 16 Intro to Strings Lecture 7 CGS 3416 Spring 2017 February 13, 2017 Lecture 7 CGS 3416 Spring 2017 Intro to Strings February 13, 2017 1 / 16 Strings in Java In Java, a string is an object. It is not a primitive

More information

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasketEnhanced { public static void main(string[]

More information

Basic Computation. Chapter 2

Basic Computation. Chapter 2 Basic Computation Chapter 2 Outline Variables and Expressions The Class String Keyboard and Screen I/O Documentation and Style Variables Variables store data such as numbers and letters. Think of them

More information

Text User Interfaces. Keyboard IO plus

Text User Interfaces. Keyboard IO plus Text User Interfaces Keyboard IO plus User Interface and Model Model: objects that solve problem at hand. User interface: interacts with user getting input from user giving output to user reporting on

More information

Intro to Strings. Lecture 7 COP 3252 Summer May 23, 2017

Intro to Strings. Lecture 7 COP 3252 Summer May 23, 2017 Intro to Strings Lecture 7 COP 3252 Summer 2017 May 23, 2017 Strings in Java In Java, a string is an object. It is not a primitive type. The String class is used to create and store immutable strings.

More information

Creating Strings. String Length

Creating Strings. String Length Strings Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and

More information

Final Exam. CSC 121 Fall 2015 TTH. Lecturer: Howard Rosenthal. Dec. 15, 2015

Final Exam. CSC 121 Fall 2015 TTH. Lecturer: Howard Rosenthal. Dec. 15, 2015 Final Exam. CSC 121 Fall 2015 TTH Lecturer: Howard Rosenthal Dec. 15, 2015 Your Name: Key The following questions (or parts of questions) in numbers 1-17 are all worth 2 points each. The programs have

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

Reading Input from Text File

Reading Input from Text File Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Lab 5 Reading Input from Text File Eng. Mohammed Alokshiya November 2, 2014 The simplest

More information

Appendix 3. Description: Syntax: Parameters: Return Value: Example: Java - String charat() Method

Appendix 3. Description: Syntax: Parameters: Return Value: Example: Java - String charat() Method Appendix 3 Java - String charat() Method This method returns the character located at the String's specified index. The string indexes start from zero. public char charat(int index) index -- Index of the

More information

Midterm Exam 2 Thursday, November 15th, points (15% of final grade) Instructors: Jim Williams and Marc Renault

Midterm Exam 2 Thursday, November 15th, points (15% of final grade) Instructors: Jim Williams and Marc Renault Computer Sciences 200 Midterm Exam 2 Thursday, November 15th, 2018 100 points (15% of final grade) Instructors: Jim Williams and Marc Renault (Family) Last Name: (Given) First Name: CS Login Name: NetID

More information

Unit 4: Classes and Objects Notes

Unit 4: Classes and Objects Notes Unit 4: Classes and Objects Notes AP CS A Another Data Type. So far, we have used two types of primitive variables: ints and doubles. Another data type is the boolean data type. Variables of type boolean

More information

c) And last but not least, there are javadoc comments. See Weiss.

c) And last but not least, there are javadoc comments. See Weiss. CSCI 151 Spring 2010 Java Bootcamp The following notes are meant to be a quick refresher on Java. It is not meant to be a means on its own to learn Java. For that you would need a lot more detail (for

More information

Computer Science 300 Sample Exam Today s Date 100 points (XX% of final grade) Instructor Name(s) (Family) Last Name: (Given) First Name:

Computer Science 300 Sample Exam Today s Date 100 points (XX% of final grade) Instructor Name(s) (Family) Last Name: (Given) First Name: Computer Science 300 Sample Exam Today s Date 100 points (XX% of final grade) Instructor Name(s) (Family) Last Name: (Given) First Name: CS Login Name: NetID (email): @wisc.edu Circle your Lecture: Lec001

More information

Hello World. n Variables store information. n You can think of them like boxes. n They hold values. n The value of a variable is its current contents

Hello World. n Variables store information. n You can think of them like boxes. n They hold values. n The value of a variable is its current contents Variables in a programming language Basic Computation (Savitch, Chapter 2) TOPICS Variables and Data Types Expressions and Operators Integers and Real Numbers Characters and Strings Input and Output Variables

More information

Welcome to the Using Objects lab!

Welcome to the Using Objects lab! Welcome to the Using Objects lab! Learning Outcomes By the end of this lab: 1. Be able to define chapter 3 terms. 2. Describe reference variables and compare with primitive data type variables. 3. Draw

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

Project 1. Java Data types and input/output 1/17/2014. Primitive data types (2) Primitive data types in Java

Project 1. Java Data types and input/output 1/17/2014. Primitive data types (2) Primitive data types in Java Java Data types and input/output Sharma Chakravarthy Information Technology Laboratory (IT Lab) Computer Science and Engineering Department The University of Texas at Arlington, Arlington, TX 76019 Email:

More information

More on Strings. Lecture 10 CGS 3416 Fall October 13, 2015

More on Strings. Lecture 10 CGS 3416 Fall October 13, 2015 More on Strings Lecture 10 CGS 3416 Fall 2015 October 13, 2015 What we know so far In Java, a string is an object. The String class is used to create and store immutable strings. Some String class methods

More information

Basic Computation. Chapter 2

Basic Computation. Chapter 2 Walter Savitch Frank M. Carrano Basic Computation Chapter 2 Outline Variables and Expressions The Class String Keyboard and Screen I/O Documentation and Style Variables Variables store data such as numbers

More information

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on: Data and Expressions Data and Expressions Let's explore some other fundamental programming concepts Chapter 2 focuses on: Character Strings Primitive Data The Declaration And Use Of Variables Expressions

More information

8/25/17. Demo: Create application. CS2110, Recita.on 1. Arguments to method main, Packages, Wrapper Classes, Characters, Strings.

8/25/17. Demo: Create application. CS2110, Recita.on 1. Arguments to method main, Packages, Wrapper Classes, Characters, Strings. CS2110, Recita.on 1 Arguments to method main, Packages, Wrapper Classes, Characters, Strings Demo: Create application To create a new project that has a method called main with a body that contains the

More information

"Hello" " This " + "is String " + "concatenation"

Hello  This  + is String  + concatenation Strings About Strings Strings are objects, but there is a special syntax for writing String literals: "Hello" Strings, unlike most other objects, have a defined operation (as opposed to a method): " This

More information

Input. Scanner keyboard = new Scanner(System.in); String name;

Input. Scanner keyboard = new Scanner(System.in); String name; Reading Resource Input Read chapter 4 (Variables and Constants) in the textbook A Guide to Programming in Java, pages 77 to 82. Key Concepts A stream is a data channel to or from the operating system.

More information

String. Other languages that implement strings as character arrays

String. Other languages that implement strings as character arrays 1. length() 2. tostring() 3. charat() 4. getchars() 5. getbytes() 6. tochararray() 7. equals() 8. equalsignorecase() 9. regionmatches() 10. startswith() 11. endswith() 12. compareto() 13. indexof() 14.

More information

Introduction to Computer Programming

Introduction to Computer Programming Introduction to Computer Programming Lecture #8 - Stringing Along Using Character and String Data How Do Computer Handle Character Data? Like all other data that a computer handles, characters are stored

More information

A+ Computer Science -

A+ Computer Science - import java.util.scanner; or just import java.util.*; reference variable Scanner keyboard = new Scanner(System.in); object instantiation Scanner frequently used methods Name nextint() nextdouble() nextfloat()

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4 Assignments Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4 Lecture 6 Complete for Lab 4, Project 1 Note: Slides 12 19 are summary slides for Chapter 2. They overview much of what we covered but are not complete.

More information

Introduction to Java Applications

Introduction to Java Applications 2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use

More information

ing execution. That way, new results can be computed each time the Class The Scanner

ing execution. That way, new results can be computed each time the Class The Scanner ing execution. That way, new results can be computed each time the run, depending on the data that is entered. The Scanner Class The Scanner class, which is part of the standard Java class provides convenient

More information

CS 1301 Ch 8, Part A

CS 1301 Ch 8, Part A CS 1301 Ch 8, Part A Sections Pages Review Questions Programming Exercises 8.1 8.8 264 291 1 30 2,4,6,8,10,12,14,16,18,24,28 This section of notes discusses the String class. The String Class 1. A String

More information

Final Exam. CSC 121 Spring Lecturer: Howard Rosenthal. May 17, 2017

Final Exam. CSC 121 Spring Lecturer: Howard Rosenthal. May 17, 2017 Final Exam. CSC 121 Spring 2017 Lecturer: Howard Rosenthal May 17, 2017 Your Name: Answer Key The following questions (or parts of questions) in numbers 1-17 are all worth 2 points each. The programs have

More information

Computational Expression

Computational Expression Computational Expression Scanner, Increment/Decrement, Conversion Janyl Jumadinova 17 September, 2018 Janyl Jumadinova Computational Expression 17 September, 2018 1 / 11 Review: Scanner The Scanner class

More information

COMP-202 Unit 8: Basics of Using Objects

COMP-202 Unit 8: Basics of Using Objects COMP-202 Unit 8: Basics of Using Objects CONTENTS: Concepts: Classes and Objects Creating and Using Objects Introduction to Basic Java Classes (String, Scanner, ArrayList,...) Introduction (1) As we know,

More information

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 11, Name: KEY

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 11, Name: KEY CSC 1051 Algorithms and Data Structures I Midterm Examination October 11, 2018 Name: KEY Question Value Score 1 20 2 20 3 20 4 20 5 20 TOTAL 100 Please answer questions in the spaces provided. If you make

More information

Fundamentals of Programming Data Types & Methods

Fundamentals of Programming Data Types & Methods Fundamentals of Programming Data Types & Methods By Budditha Hettige Overview Summary (Previous Lesson) Java Data types Default values Variables Input data from keyboard Display results Methods Operators

More information

CSC 1051 Algorithms and Data Structures I. Midterm Examination March 1, Name: KEY A

CSC 1051 Algorithms and Data Structures I. Midterm Examination March 1, Name: KEY A CSC 1051 Algorithms and Data Structures I Midterm Examination March 1, 2018 Name: KEY A Question Value Score 1 20 2 20 3 20 4 20 5 20 TOTAL 100 Please answer questions in the spaces provided. If you make

More information

Getting started with Java

Getting started with Java Getting started with Java Magic Lines public class MagicLines { public static void main(string[] args) { } } Comments Comments are lines in your code that get ignored during execution. Good for leaving

More information

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All Advanced Java This chapter discusses class String, class StringBuilder and class Character from the java.lang package. These classes provide

More information

More on variables and methods

More on variables and methods More on variables and methods Robots Learning to Program with Java Byron Weber Becker chapter 7 Announcements (Oct 12) Reading for Monday Ch 7.4-7.5 Program#5 out Character Data String is a java class

More information

Full file at

Full file at Chapter 1 Primitive Java Weiss 4 th Edition Solutions to Exercises (US Version) 1.1 Key Concepts and How To Teach Them This chapter introduces primitive features of Java found in all languages such as

More information

Computer Science 252 Problem Solving with Java The College of Saint Rose Spring Topic Notes: Strings

Computer Science 252 Problem Solving with Java The College of Saint Rose Spring Topic Notes: Strings Computer Science 252 Problem Solving with Java The College of Saint Rose Spring 2016 Topic Notes: Strings This semester we ve spent most of our time on applications that are graphical in nature: Manipulating

More information

Faculty of Science COMP-202B - Introduction to Computing I (Winter 2009) - All Sections Final Examination

Faculty of Science COMP-202B - Introduction to Computing I (Winter 2009) - All Sections Final Examination First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202B - Introduction to Computing I (Winter 2009) - All Sections Final Examination Wednesday, April 29, 2009 Examiners: Mathieu Petitpas

More information

H212 Introduction to Software Systems Honors

H212 Introduction to Software Systems Honors Introduction to Software Systems Honors Lecture #04: Fall 2015 1/20 Office hours Monday, Wednesday: 10:15 am to 12:00 noon Tuesday, Thursday: 2:00 to 3:45 pm Office: Lindley Hall, Room 401C 2/20 Printing

More information

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4 Assignments Lecture 6 Complete for Project 1 Reading: 3.1, 3.2, 3.3, 3.4 Summary Program Parts Summary - Variables Class Header (class name matches the file name prefix) Class Body Because this is a program,

More information

Chapter. Let's explore some other fundamental programming concepts

Chapter. Let's explore some other fundamental programming concepts Data and Expressions 2 Chapter 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design 2007 Pearson Addison-Wesley. All rights reserved Data and Expressions Let's explore some

More information

Lecture Notes for CS 150 Fall 2009; Version 0.5

Lecture Notes for CS 150 Fall 2009; Version 0.5 for CS 150 Fall 2009; Version 0.5 Draft! Do not distribute without prior permission. Copyright 2001-2009 by Mark Holliday Comments, corrections, and other feedback appreciated holliday@email.wcu.edu Chapter

More information

Strings. Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

Strings. Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. Strings Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS

CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS These are sample pages from Kari Laitinen s book "A Natural Introduction to Computer Programming with Java". For more information, please visit http://www.naturalprogramming.com/javabook.html CHAPTER 5

More information

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003 Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 Java Programs A Java program contains at least one class definition. public class Hello { public static void

More information

A Java program contains at least one class definition.

A Java program contains at least one class definition. Java Programs Identifiers Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 A Java program contains at least one class definition. public class Hello { public

More information

What did we talk about last time? Examples switch statements

What did we talk about last time? Examples switch statements Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Variables and Assignments CSC 121 Spring 2017 Howard Rosenthal

Variables and Assignments CSC 121 Spring 2017 Howard Rosenthal Variables and Assignments CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Understand variables Understand how to declare and use variables in Java Programs Learn how to formulate assignment statements

More information

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation. Chapter 4 Lab Loops and Files Lab Objectives Be able to convert an algorithm using control structures into Java Be able to write a while loop Be able to write an do-while loop Be able to write a for loop

More information

The Irving K. Barber School of Arts and Sciences COSC 111 Final Exam Winter Term II Instructor: Dr. Bowen Hui. Tuesday, April 19, 2016

The Irving K. Barber School of Arts and Sciences COSC 111 Final Exam Winter Term II Instructor: Dr. Bowen Hui. Tuesday, April 19, 2016 First Name (Print): Last Name (Print): Student Number: The Irving K. Barber School of Arts and Sciences COSC 111 Final Exam Winter Term II 2016 Instructor: Dr. Bowen Hui Tuesday, April 19, 2016 Time: 6:00pm

More information

Strings in Java String Methods. The only operator that can be applied to String objects is concatenation (+) for combining one or more strings.

Strings in Java String Methods. The only operator that can be applied to String objects is concatenation (+) for combining one or more strings. The only operator that can be applied to String objects is concatenation (+) for combining one or more strings. Java also provides many methods with the String class to allow us to manipulate text. These

More information

Chapter 2: Data and Expressions

Chapter 2: Data and Expressions Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University January 15, 2015 Chapter 2: Data and Expressions CS 121 1 / 1 Chapter 2 Part 1: Data

More information

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value Lecture Notes 1. Comments a. /* */ b. // 2. Program Structures a. public class ComputeArea { public static void main(string[ ] args) { // input radius // compute area algorithm // output area Actions to

More information

Exam 1 Answer Key CSC 123 Fall 2018 Lecturer: Howard Rosenthal Oct. 17, 2018

Exam 1 Answer Key CSC 123 Fall 2018 Lecturer: Howard Rosenthal Oct. 17, 2018 Your Name: Exam 1 Answer Key CSC 123 Fall 2018 Lecturer: Howard Rosenthal Oct. 17, 2018 The following questions in numbers 1-11 are all worth 3 points each (including each true and false). The programs

More information

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All This chapter discusses class String, from the java.lang package. These classes provide the foundation for string and character manipulation

More information

Computational Expression

Computational Expression Computational Expression Variables, Primitive Data Types, Expressions Janyl Jumadinova 28-30 January, 2019 Janyl Jumadinova Computational Expression 28-30 January, 2019 1 / 17 Variables Variable is a name

More information

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1 topics: introduction to java, part 1 cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 cis20.1-fall2007-sklar-leci.2 1 Java. Java is an object-oriented language: it is

More information

Section 2.2 Your First Program in Java: Printing a Line of Text

Section 2.2 Your First Program in Java: Printing a Line of Text Chapter 2 Introduction to Java Applications Section 2.2 Your First Program in Java: Printing a Line of Text 2.2 Q1: End-of-line comments that should be ignored by the compiler are denoted using a. Two

More information

Chapter 3: Using Classes and Objects

Chapter 3: Using Classes and Objects Chapter 3: Using Classes and Objects CS 121 Department of Computer Science College of Engineering Boise State University August 21, 2017 Chapter 3: Using Classes and Objects CS 121 1 / 51 Chapter 3 Topics

More information

Chapter 4 Classes in the Java Class Libraries

Chapter 4 Classes in the Java Class Libraries Programming Fundamental I ACS-1903 Chapter 4 Classes in the Java Class Libraries 1 Random Random The Random class provides a capability to generate pseudorandom values pseudorandom because the stream of

More information

Lab 14 & 15: String Handling

Lab 14 & 15: String Handling Lab 14 & 15: String Handling Prof. Navrati Saxena TA: Rochak Sachan String Handling 9/11/2012 22 String Handling Java implements strings as objects of type String. Once a String object has been created,

More information

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor:

More information

Full file at

Full file at Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional

More information

Introduction to Java Unit 1. Using BlueJ to Write Programs

Introduction to Java Unit 1. Using BlueJ to Write Programs Introduction to Java Unit 1. Using BlueJ to Write Programs 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save

More information

Faculty of Science COMP-202A - Foundations of Computing (Fall 2012) - All Sections Midterm Examination

Faculty of Science COMP-202A - Foundations of Computing (Fall 2012) - All Sections Midterm Examination First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202A - Foundations of Computing (Fall 2012) - All Sections Midterm Examination November 7th, 2012 Examiners: Daniel Pomerantz [Sections

More information