Download Java Bootcamp - Object-Oriented Programming and Data Structures | CS 2110 and more Study notes Computer Science in PDF only on Docsity!
Page 1
Java Bootcamp
David I. Schwartz
COMS/ENGRD 211
Read Step 1 first on Page 3!
It will explain what you need to do!
Table of Contents
- Page
- Step 0 Understand the notation in this tutorial.
- Step 1 Figure out how to do this tutorial..
- Step 2 How to find Java at Cornell.
- Step 3 What is a Java application?.
- Step 4 Java Language.
- Step 5 Java Character Set.
- Step 6 Java Comments and Whitespace.
- Step 7 Java Tokens.
- Step 8 Java Statements.
- Step 9 Empty and Block Statements
- Step 10 Declaration and Assignment Statements
- Step 11 Introduction to Scope
- Step 12 Control Flow
- Step 13 Methods
- Step 14 Building A Class
- Step 15 Creating Objects
- Step 16 Storing and Accessing Objects (References)
- Step 17 Special reference–null
- Step 18 Special method–toString.
- Step 19 Accessing an object’s members
- Step 20 What is static?
- Step 21 Aliases.
- Step 22 Methods and objects (and aliases)
- Step 23 Using Java’s this
- Step 24 Arrays
- Step 25 Class Object
- Step 26 Java API and import
- Step 27 Constants: Static Import and Enumerations (enum)
- Step 28 Wrapper Classes
- Step 29 Autoboxing
- Step 30 Vectors.
- Step 31 User I/O.
- Step 32 Other things for the future…?.
Step 1: Figure out how to do this tutorial.
1.1 Background
In the past, the Java Bootcamp was taught in a large lecture hall with an instructor or teaching assistant rattling off a blizzard of Java syntax while students’ eyes rapidly glazed over. So, I have created this hopefully more engaging version. There may be a few rough edges, so I hope that you will help me by providing constructive criticism.
1.2 Time?
If you are unfamiliar with Java, you will likely need more that 3 hours. Otherwise, you might want to start with the OOP sections and refer back to previous sections.
1.3 On-line Help:
- Java 5 and JDK 1.5–explanation of these names mean effectively the same thing: http://java.sun.com/j2se/naming_versioning_5_0.html.
- Summary of Java 5 features/changes: http://java.sun.com/developer/technicalArticles/releases/j2se15/
- Java 5 complete release notes: http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html
- Java tutorial: http://java.sun.com/docs/books/tutorial/
- Java API: http://java.sun.com/j2se/1.5.0/docs/api/index.html
- Data structures collection: http://www.nist.gov/dads/
1.4 Some suggestions
- Skim the sections to see what seems unfamiliar. Refer to the Table of Contents.
- If you are familiar with the basics of Java’s language, we suggest starting with Step 14 (OOP in Java).
- If all you need is a quick introduction to Java 5 , see these sections: Step 13.13, Step 24.12, Step 27, Step 28.2, Step 29, and Step 31.
- If you get stuck, try the previous section. You might need to start from the beginning of this tutorial.
- Use companion notes, like the course books, their websites, Java’s online tutorial at, and numerous examples posted on past CS100 Websites. Well…we can’t cram everything about Java into this document.
- Try to do the suggested problems. If you only read the solutions, you have not practiced enough! Programming involves practice.
1.5 Problem 1
Where are the solutions posted for the tutorial?
1.6 Problem 2
What is autoboxing? Check out the Java 5 summary or release notes to find out.
Step 3: What is a Java application?
3.1 Long Answer
Refer to Applications.html , which Step 2 mentions.
3.2 The Gist
- Except for import statements, all Java code must reside inside a class.
- Unless you want your program to run within a webpage (an applet ), you need to write an application. A Java application has a main method that starts the program.
- Every class can have a main method.
- You need to “tell” Java which main method you wish to run when executing a program.
- When compiling from the command-line, each file must include only one public class. If you prefer to place multiple classes in one file, do not modify the classes with the word public –only the class containing method main should have public as part of the declaration.
3.3 Problem 1
Write a Java application that contains the following code in one file called MyProgram.java :
public class MyProgram { public static void main(String[] args) { System.out.println( new Person(args[0],args[1]) ); } }
class Person { private String first; private String last; public Person(String f, String l) { first = f; last = l; } public String toString() { return first + " " + last; } }
From the command-line, compile and run the program with arguments Dimmu and Borgir.
Step 4: Java Language
4.1 Language Analogy
- alphabet ⇔ character set
- punctuation ⇔ punctuation
- whitespace ⇔ whitespace
- words ⇔ tokens
- sentences ⇔ statements
- paragraphs ⇔ modules
4.2 What’s next?
The next few sections go over details and tricks about the Java language. I suggest that you try the problems to see how well you know/remember a lot of the nit-picky items. If you find yourself getting strange results, chances are you missed one of these rules.
4.3 On-line help
Java’s language basics (http://java.sun.com/docs/books/tutorial/java/nutsandbolts) nicely reviews Java’s basics. Note that CS212 doesn’t do much with bitwise operators, which you will see described.
4.4 Problem
Rewrite the code in BasicsDemo.java (below) to add backwards (start from 10 and end at 1).
public class BasicsDemo { public static void main(String[] args) { int sum = 0; for (int current = 1; current <= 10; current++) { sum += current; } System.out.println("Sum = " + sum); } }
Step 6: Java Comments and Whitespace
6.1 Java Comments
- Single line comments: // stuff / stuff /
- Multiline comments: /* *stuff /
- You can nest comments.
6.2 Java Whitespace
- Spacebar, return, new line, tab.
- You can separate tokens and statements with as much whitespace as you want.
- Do not split a token!
6.3 Problem 1
Correct the following program, which should print hello :
public Class Test { public static void ma in (String[] Args) {
// hello / hello System.out.println();*
} }
Step 7: Java Tokens
7.1 Punctuation
- Statements end with semicolon! ( ; ).
- Classes, methods, constructors, statement blocks, inner classes, initialization blocks, and initializer lists use braces ( { } ). Inner classes and initialization blocks aren’t covered in our CS100, so don’t worry about them for now.
- Methods and expressions use parentheses ( ( ) ).
- Arrays use square brackets ( [ ] ).
- Parameter lists and variable declarations use commas ( , ).
- String literals (strings created w/o using a constructor) use double quotes ( " " ).
- Character values use single quotes ( ' ' ).
- Escape characters use a backslash ( ** ).
- What about other symbols, like + and.? Those are operators–discussed soon!
7.2 Problem 1
The following program should print integers from 0 to 10. Unfortunately, we forgot to apply the punctuation! Please fix it.
public class Punctuation public static void main String args
int count = 0 final int STOP = 10 while count <= STOP System.out.println count count++
7.3 Reserved Words
Reserved words are tokens that are reserved for the language and cannot be used to represent any value. See textbook for comprehensive list:
- values: true false null this
- types: boolean int double char void
- control: if else for do while return switch
- modifiers: public private static final protected
- classes: new class extends implements super interface enum
- amusing: goto
7.6 Strings
Making strings:
- Java strings are not primitive values or arrays! Strings are objects in Java.
- Shortcut: use double quotes, which makes a string look like a value: String s = "I wuv u";
- Longer way: String s = new String("I wuv u");
- Also, see string promotion below.
- Once created, cannot change contents. See StringBuffer in API for mutable strings.
Null string ( "" ) is not null!
- The null string is a string object with no character values.
- Very handy for string promotion. See below.
String promotion:
- You can add any value or object to a string, which returns a string object! System.out.println(1+""+1); // what does this output?
- How does an object become a string? toString method, which all classes inherit, which you may implement. More later.
- Strings can’t be demoted to other types. But you can use wrapper classes. For example, Integer.parseInt("4") evaluates to the integer 4.
Convert characters to strings and vice versa?
- You need arrays, which you haven’t seen too much, yet.
- For now, here’s a quick way (initializer list is shortcut for an array): char[] c = {'A','B','C'}; // array of 3 chars String s = new String(c);
Handy built-in methods!
- There are many useful string methods in the Java API. Refer to the String class.
- Number of characters in a string: length() method, e.g., s.length().
- Others: charAt , indexOf , toUpperCase , toLowerCase , toCharArray , equals
String equality:
- Compare strings with equals method!
- Why? Strings are objects. So if you use == , you are comparing addresses, not contents.
- Actually == will work if you created strings with literals, but it’s an obscure rule, so forget you heard it.
- As toString , equals is inherited by all classes. So, you can define it for other classes.
7.7 Problem 2
Are the following statements OK? Why or why not? What do they do?
String s1 = null; String s2 = ""; System.out.println( s1.length() ); System.out.println( s2.length() );
System.out.println("abc" + "123");
String s2 = "abc"; s2[1] = 'd';
String a = "abcd"; String b = new String("abcd"); System.out.println( a == b ); System.out.println( a.equals(b) );
String start = ""; start = start + 1; start = start + "\n"; start = start + 2; System.out.println(start);
7.10 Operators
Review: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/opsummary.html
Basics:
- Arithmetic: + , - , ***** , / , % (mod), - (negation, subtraction)
- Logic: & (and), && (short-circuit and), | (or), || (short-circuit or),! (not), ^ (xor)
- Comparison: == , != , < , <= , > , >=
- Conditional: ?:
- Assignment: = , += , *= , -= , …
- Increment: -- , ++
- Cast: ( type )
- Member access:. (no pointer, dereferencing)
- Array access: [ index ]
- String concatenation: +
- Object type comparison: instanceof
Power?
- Java does not use ****** ; ^ means XOR (exclusive OR, not a power!).
- For , use Math.pow(x,y).
Precedence:
- See http://java.sun.com/docs/books/tutorial/java/nutsandbolts/expressions.html
- Handy to remember that precedence of [] and. are highest.
- Use parentheses ( ( ) ) to control the order of operation in an expression.
Associativity:
- Two main rules people run into:
- Arithmetic works left to right.
- Assignment works right to left.
- Example: System.out.println("answer: "+1+2); // outputs answer: 12 x = y = 3; //
- Use parentheses ( ( ) ) to control the order of operation in an expression.
Promotion (revised):
- Number types: double > int > char.
- Cannot mix boolean with numbers.
- Everything promotes to string with +.
x y
Arithmetic:
- Consequence of int s promoting to double?
- In mixed operations, result becomes double.
- Integer division results in integer result! Not rounded–result is floored!
Casting:
- ( type ) expr
- arrays and inheritance: cast has lower precedence! So, use (( type ) expr )
Conditional operator:
- expr****? expr1 : expr
- Returns either expr1 or expr
- Example: int x = 1; int y = 2; System.out.println( x==y? 'a' : 'b');
Increment operators (some examples):
- prefix example: int x = 1; int y = ++x; System.out.println(x); // outputs 2 System.out.println(y); // outputs 2
- postfix example: int a = 1; int b = a++; System.out.println(a); // outputs 2 System.out.println(b); // outputs 1
- bonkers example (way beyond scope of CS211) int x = 1; x = x++; System.out.println(x); // might not be what you think :-)
7.11 Problem 2
Write a program that checks if 13 is even or odd.
Why does System.out.println(3/4) output zero?
Write a program that generates a random integer between 1 and 100 , inclusive. Hint: Math.random() returns a double in the interval [0, 1).
Write a program that converts all of the lowercase letters to uppercase without using an array or strings. Hint: for(int count=start;count<=stop;count++).
Step 9: Empty and Block Statements
9.1 Empty
The simplest form of a sentence:
- semicolon ;
- empty block: {}
These statements simply succeed without further work.
9.2 Block
- syntax: { statements }
- example if (x == 10) { System.out.println("Hello!"); System.out.println("x is " + x); } else System.out.println("Bye!");
9.3 Expression
- cannot make statements, like 1+1;
- some expression statements are legal: method call, increment, object creation
- see operators for reminders of associativity and precedence
9.4 Problem 1
Write a program that pauses. Do not use a built-in method. Hint: Use a for loop.
Step 10: Declaration and Assignment Statements
10.1 The Rules
- all variables have types (strongly typed)!
- variables may be declared only once in a block!
- all variables must have values before used!
- all variables do not have initial values in methods!
- when variables declared but not assigned in class (fields), defaults are “zero” some tricky ones: references are null , booleans are false
10.2 Declaration Syntax
type name ; type name , …, name ;
10.3 Assignment Syntax
- general: name = expr ;
- combined syntax: type name = expr ; final type name = expr ;
- more about scope? coming up!
10.4 Problem 1
What is wrong with the following code, besides the fact that I did not comment it?
public void something( ) { int x = 1; boolean y; System.out.println(y); System.out.println(x==y); }