This is a quick introduction meant to introduce Java and basic programming concepts.
You will probably not be able to learn programming entirely from this
but can serve as supplement to other materials. If you are experienced
and looking to pick up Java this is a good introduction and reference
for the basics of the language.
Licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License.
Our updated jar file for the assignment
Licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License.
What is Java?
- made by Sun in 1995, similar to C and C++
- actually denotes a language and a platform
What's a Platform?
- it includes the libraries, developer kit, compiler, and Java Virtual Machine (JVM)
- the first three are very important to writing and making a program
- the JVM is what actually runs a program once it is created (not all languages have this)
What's a programming language (PL)?
- relation to human languages (HL): - similarities: both have punctuation, grammar, vocabulary, and a general way of expressing yourself - differences: programming languages are unambiguous, strictly enforce rules - syntax - what we call these rules in PL, basically a combination of HL grammar and vocab - important because a program must be syntactically correct to run - besides being syntactically correct, a program must be semantically correct - semantics relate to the meaning of a program, whether it runs the way it is expected to - bugs are often the result of semantic problems - besides HL, PLs borrow a lot from math - many of the first programmers and computer engineers were mathematicians - all the normal arithmetic operators are there: +, -, / (divide), * (multiply) - PL variables are very similar to math variables - graphics typically use the normal xy-coordinate system (or xyz for 3D), called Cartesian coordinates - trigonometry and linear algebra are used heavily - PL methods are very similar to the idea of a math function - PLs are something easy for humans to understand that get turned into machine-understandable code
What's Java (the language)?
- it is a compiled, statically typed language - very popular because its platform enables it to be cross-platform, simplifies some of the more confusing parts of C/C++ (like garbage collection - ask me about it later) - it is NOT javascript - its "big thing" is that it is completely Object Oriented (we'll get to this later)
Hello World Revisited
public class HelloWorld
{
public static void main( String args[ ] )
{
System.out.println( "Hello World!" ) ;
}
}
- public class HelloWorld defines a new Java class called HelloWorld - public static void main( String args[ ] ) defines a new function or method called main that takes an array of Strings as its arguments - main is the default beginning point when a program runs - System.out.println( "Hello World!" ) ; is the line that tells the JVM to output the thing between quotes to the screen - This won't all make sense yet, so don't worry
Basic template of a program
public class ClassName
{
// class variables go here, if any
// now the methods, if any
public void someMethod( )
{
...
}
// finally the main method
public static void main( String args[ ] )
{
...
}
}
Comments
- comments inside code are lines of text that are NOT code, in other words not compiled and not part of the program - they are mostly written to explain code or concepts inside of the code - there are two types 1. Single line comments - these have "//" at the beginning of the line and only last for a single line - if you look above I have several of these in the "basic template of a program" 2. Multi-line comments - these start with "/*" and terminate with the first "*/" - something like: /* start my comment keep going more stuff System.out.println( "Hello World!" ) ; this won't do anything because it's in a comment now I'm done! */
Variables
- variables in programming are very similar to variables from mathematics - a variable has a data type and it holds data ONLY of that type - a variable name can be any combination of letters, numbers or underscores but must begin with a letter - also cannot use a reserved word - ex: if, else, switch, for while, do, class, public, private, static - declaring variables:
int x ; // declares a single variable called x of type int
int y, z ; // declares two variables, y and z, of type int
int a = 5 ; // declares an int variable a and assigns 5 to it
int something1, with_underscore ; // examples of how you can use numbers and underscores
- if you do not assign a value to a variable when you declare it (like x, y, and z above) it gets the default value for whatever its data type is. - assigning new values to variables:
a = 6 ; // a now holds 6
x = 7 ; // x now holds 7
z = x ; /* takes the value in x and copies it to z, so z now holds 7 too
CAREFUL: this sometimes does not do exactly want you intend,
more on this later in the object data types section */
Data Types
- because Java is statically typed every variable must have a data type and can ONLY hold that type - the data type comes before the variable name in a declaration - in the above examples the data type was "int" for all the variables - data types can be segmented as: 1. Primitives 2. Objects
Primitive Data Types
- there are many types but we will only worry about four: 1. int - stands for integer, just like the integers from math (any whole number) ex. -1, 0, 34 2. double - a decimal number, ex. 3.14, 1.6180, -0.524 3. char - stands for character, a single letter or symbol, ex. a, b, c, @, # - when typing literals these are surrounded by single quotes ('), ex. 'a', '@' - ex. char c = '!' assigns an exclamation point to the variable c. 4. boolean - holds true or false - these are often used as flags to denote something that can be one thing or the other - ex. whether a light is on or off, whether the player has or has not flipped the switch to launch the rocket, etc - ex. boolean b = true ; - all primitive data types are written in all lower case letters - for assignments, variables can use themselves in the right hand side of the expression - ex. int i = 42 ; i = i + 7 ; // i now equals 49
Object Data Types
- all object data types follow CamelCase standards - no spaces between words and each first letter of a word is Capitalized - ex. String, ArrayList, OvalSprite - objects do not have literal values, so they must be instantiated with a constructor call and the new keyword - ex. OvalSprite s = new OvalSprite( 1, 1 ) ; - a constructor is the same name as the class and handles creating the object - once this happens, s is called an instance of the class OvalSprite - assignment with the = sign like we did with primitives does not work as expected when assigning one variable to another - ex. OvalSprite t = s ; -or- OvalSprite t ; // neither of these do what we expect, that is copy the data t = s ; - so it is best just not to use = with objects for now - objects can have methods that get called from them - ex. we've already seen, where s is some sort of Sprite, things like s.setScale( .5 ) ; - setScale is the method that is called from the object s - more on this when we cover Methods and Functions - more on objects later when we review classes
Strings - the exception to (some) object rules
- as noted, Strings are an object, but they can sometimes behave like primitives
- Strings can be created in 2 ways:
1. instantiated like an object: String s = new String( "test" ) ;
2. assigned with a literal, like primitives: String s = "test" ;
- Also assignment works like it does with primitives:
- ex. String s = "hello" ;
String t = s ; // the contents of s--hello--get copied to t
Literals
- literals are primitives and Strings that are constants typed directly inside of the code - Objects (besides String) do not have literals, they must be instantiated - examples
int x = 5 ; // 5 is an int literal double y = 3.14 ; // 3.14 is a double literal char c = '&' ; // & is a char literal, note char literals are surrounded by single quotes String s = "Hello" // Hello is a String literal , note string literals are surrounded by double quotes
Conversions, Casts and Gotchas
- you can convert between integers and doubles fairly easy: - int to double is automatically done for you:
double x = 1 ; // x stores 1.0
int a = 7 ;
double y = a ; // y stores 7.0
- double to int is a little trickier
- the decimal portion gets chopped off, or truncated
- it is not automatic, you have to explicity tell the program to change the data type, this is a cast
int r = (int)( 5.4564781 ) ; // r stores 5
double t = 7.48 ;
int p = (int)( t ) ; // p stores 7
- conversions involving char are possible but we won't worry about these
- same goes for conversions involving Strings or other objects
- except for when using System.out.println( )
- you can place most anything in there and it will convert to strings where necessary
- this is why something like the following works:
int i = 6 ;
System.out.println( i ) ;
System.out.println( "i stores " + i ) ;
- another gotcha: integer and double division
- when either numerator or denominator are a double the result is a double (a decimal number)
- when both the numerator and denominator are integers the division results is another integer--the dividend--not a decimal value
to get it to result in a decimal must cast one number to a double
- to get the remainder use % instead of /
- ex.
22.0 / 7 = 3.142857.... (22/7.0 is the same thing)
22 / 7 = 3
22 % 7 = 1
Data Types Examples
Random Numbers
- often in games we want to have a random number - this can be for simulating random event like rolling a die or just adding randomness to something like Artificial Intelligence - FANG has a built-in random number generator that we will use called random, more on this later - for now, we will use Java's random number generator for a quick example
Random Numbers Assignment
Arrays
- let's think about the char class for a second:
- a char can hold a single character, what if we want to store many characters in sequence (as in a word)?
- there's an easy answer....
- but you can also use an array
- What is an array?
- it stores many different values of a particular type
- ex. think of CDs in their cases as a type, well an array would be like a storage rack that holds a bunch of them
- ex. so, back to chars, an array of chars could store a word (one char in each array slot)
- array can have any data type, but ONLY one data type
- How do I declare one?
- int[ ] myarray = new int[ the_size_you_want ] ;
- "the_size_you_want" can be anything that evaluates to an int: a literal, a variable, or an expression (like 5+i if i is an int)
- How do I use them?
- keep in mind that arrays start indexes at 0, so if you want an array with 3 slots they are number 0, 1, and 2
- to assign a value to a particular array slot:
int[ ] myarray = new int[ 2 ] ;
myarray[ 0 ] = 7 ;
myarray[ 1 ] = 42 ;- to get a value out you index similarly:
int i = myarray[ 0 ] ; // i now stores 7
- these become very handy and are often used with for loops
Arrays Examples
Arithmetic, Increment, and Decrement
- as mentioned earlier many of the normal math operations exist, especially for int and double data types - +, -, / (divide), * (multiply) - order of operations is the same as in math, use ( ) to group (11+5)/8 -> result is 2 11+5/8 -> result is 11 (remember integer division from the gotchas?) 11+5/8.0 -> result is 11.625 - increment and decrement - often with integers we want to add or subtract one from the value - 2 ways to do this 1. i = i + 1 2. i++ or ++i // both make i one more than it was before - #2's options are called increment operators, they change the value of the variable without an assignment operator - they are slightly different, but for our purposes we'll ignor ++i and only use i++ - similarly, you can decrement (subtract 1) using -- instead of ++ - modulo operator - % - as mentioned in the gotchas, % gives the remainder of a division - ONLY WORKS WHEN BOTH VALUES ARE INTEGERS, int % int - exponentials - ^ does not denote taking something to a power like in math or on a calculator - to do this you must do Math.pow( base, exponent) ex. int i = Math.pow( 2, 3 ) ; -> i gets assigned 8 - sqrt - there is no "square root symbol" key on the keyboard to make it confusing like with exponentials - use Math.sqrt( number ) - a special case of + - Strings can be +'d together, this is called concatenation - this places the string on the right hand side of the + immediately after the left hand side one
Money Calculator Assignment
Comparisons and Relationals
- comparisons are another category that use boolean values - we only want to use these on numeric (int or double) types - are two things equal? - == 5 == 6 -> false 5 == 5 -> true - gotcha with doubles so only use with ints - are two things not equal? - != - also have < (less than), <= (less than or equal to), > (greater than), >= (greater than or equal to) - just like with ==, only use <= and >= with ints
Boolean Arithmetic and Logic
- as mentioned, there is a data type called boolean that stores true or false values
- along with the data type there are boolean operators that allow for boolean logic
- logical NOT - !
boolean b = true ;
boolean c = !b ; // ! reverses the value stored in b to make it false and assigns false to c
- logical AND - &&
- only true when BOTH values are true
- logical OR - ||
- true when either (or both) values are true
- not your mom's OR!
- these can be used with variables or with comparisons and relationals, use ( ) for grouping
boolean a = true, b = false, c = true ;
int i = 5, j = 6, k = 6 ; a && b -> false a && c -> true a || b -> true ( j == k ) && ( i >= 3 ) -> true !( j == k ) && ( i >= 3 ) -> false
Operator Precedence
Unary operators: ++, --, !, unary: - and +, type-cast Multiplication and division: *, /, % Addition and subtraction: +, - Relational operators: <, >, <=, >= Equality and inequality: ==, != Boolean and: && Boolean or: || Conditional operator: ?: Assignment operators: =, +=, -=, *=, /=, %=
Blocks
- a block is a chunk of code basically - blocks begin with a { and end with a } - blocks are the bodies of conditionals, loops, and methods
Conditionals
- conditionals are used to execute code based on a condition - ex. "if you eat your dinner then you can have dessert" if( ateDinner == true ) // the "if you eat your dinner" { eatDessert( ) ; // the body or block of the if is the "then" part } - the part between the ( ) of the if line can be anything that evaluates to a boolean - so, a boolean variable or literal, a comparison, relation, or any boolean logic/arithmetic statement - sometimes you want to do something like "if this then do that, otherwise do this other thing" - example: you're in a store and want to buy a video game, but you obviously on can buy if you have enough money to cover the cost (say $50) - in code this would be: if( myMoney >= 50 ) // asks if the money you have is greater than 50, the cost of the game
{
buyGame( ) ; // if your money was greater than or equal to 50, buy the game
}
else
{
leaveStore( ) ; // if your money was less than 50, meaning you can't buy the game, so leave the store
}
- you can add more conditionals in the middle, these are called an "else if" - example: same as above, but if you can't buy a game, you want to buy a music CD
if( myMoney >= 50 ) // asks if the money you have is greater than 50, the cost of the game
{
buyGame( ) ; // if your money was greater than or equal to 50, buy the game
}
else if( myMoney >= 10 ) // we know we have less than 50, but do we have enough for a CD?
{
buyCD( ) ;
}
else
{
leaveStore( ) ; // if your money was less than 50, meaning you can't buy the game, so leave the store
}
- example: same as above, but if you can't buy a game, you first want to try a movie before a CD
if( myMoney >= 50 ) // asks if the money you have is greater than 50, the cost of the game
{
buyGame( ) ; // if your money was greater than or equal to 50, buy the game
}
else if( myMoney >= 20 ) // we know we have less than 50, but do we have enough for a movie?
{
buyMovie( ) ;
}
else if( myMoney >= 10 ) // we know we have less than 20, but do we have enough for a CD?
{
buyCD( ) ;
}
else
{
leaveStore( ) ; // if your money was less than 50, meaning you can't buy the game, so leave the store
}
- finally, note that you can have a series of if/else if/else if/... without an else at the end just like you can have a lone if without an elseEven or Odd? Assignment
Loops
- loops are something you want to happen over and over with one of two stopping conditions: 1. do it a specific number of times 2. do it until something happens - the first case is called a for loop - a for loop generally looks like this:
for( int variable = starting_value ; variable < ending_value ; variable++ )
{
// do something ending_value-starting_value times
}
- the first part "int variable = starting_value" is the starting condition
- variable can be any valid variable name
- this declares a new variable that exists ONLY inside of the for loop
- it does not have to be an integer type, but our uses always will be int
- the second part "variable < ending_value" is the conditional
- this is what tells the for loop when to quit
- when the conditional evaluates to false (when variable becomes equal to or greater than ending_value) execution skips to the next line after the for loop's body
- if the conditional is true, it executes the code in the for loop's body once and proceeds to...
- the third part "variable++" is how the variable changes after each pass through the for loop's body
- I chose to use an increment operator, which is equivalent to typing variable = variable + 1 there
- could also use decrement, or any other arithmetic operation, but this is not common and a little more confusing, so try to avoid it
- after this third part finishes, it goes back to the conditional (second part) and does the evaluation again
- this back and forth between the second and third parts is what makes it loop
- see ArrayExample for a for loop in action
- note that you can nest for loops inside of each other
for( int i = 0 ; i < 2 ; i++ )
{
// could have other code here
for( int j = 0 ; j < 3 ; j++ )
{
System.out.println( "i: " + i + " j: " + j ) ;
}
// could have even more code here
}
- what happens here is the code enters the outside loop (we'll call it the i-loop), the conditional is true, so it then enters the i-loop body
- in the body the next loop is encoutnered, the j-loop
- the j-loop conditional also evaluates to true, and does so for 3 iterations
- now the j-loop conditional is false, so it goes back to the i-loop
- i-loop is true again, go into body of i-loop
- j-loop encountered again, does another 3 iterations
- back to i-loop, it's conditional is now false so it exits
- the while loop is a similar idea
int i = 0 ;
while( i < 10 )
{
System.out.println( "i: " + i ) ;
i++ ;
}
- a while loop has only a conditional associated with it
- it runs through its body as many times as the conditional is true
- this means that it's possible to make an infinite loop where the conditional never changes to false (very bad!)
- usually the last line of a while body changes the variable (or one of the variables) that the while conditional depends on so that it will eventually result in false and exit the loop
Methods and Functions
- in Java commonly called methods, but depending on who you ask or what language you're using they could be functions
- very similar in theory to math functions, but more robust
- the idea: you have some bit of code that will be used often that you don't want to write over and over, so you write a function to do it
- methods are composed of a name, a return type, the arguments (or parameters) it takes, it's body, and it's modifiers
1. name - function names have the same restrictions as variables and follow CamelCase, except the first letter is NOT capitalized like class names
2. return type - math functions only give you back numbers, programming methods can give back anything
- what a function "gives back", or returns, is called the return type
- to return something you have a statement like "return some_value ;" where some_value is something that evaluates to the method return type
3. arguments - a method can take in any number of arguments, or none, and they may each be of any data type
4. body - where the code goes, what the method does, between the { }
5. modifiers - these effect how the method is used, we won't worry about them for now
- ex.
public static void main( String[ ] args )
{
// something ....
}
- name: main
- return type: void (means you don't return anything)
- arguments: args of type String[ ]
- modifiers: public, static
- ex.
private int addOne( int x )
{
x = x + 1 ;
return x ;
}
- name: addOne
- return type: int
- arguments: x of type int
- modifiers: private
- ex.
public double giveMePI( )
{
return 3.14159 ;
}
- name: giveMePI
- return type: double
- arguments: none
- modifiers: public
- Calling Methods
- now we know what a method looks like, but how do we use them?
- we have to call the method
- using the two above examples:
int i = 6 ;
int j = addOne( i ) ; // j gets the result of addOne called with i as the argument
j = addOne( j ) ; // j gets the result of addOne with itself as the argument
double z = giveMePI( ) // z gets what giveMePI returns
- Calling Methods from an object instance
- sometimes a class will contain
- Arguments
- arguments have two parts:
1. the passed arguments
- these are the variables in the method call, i and j from above
2. the formal arguments
- these are the variables in the method declaration, x from above
- how arguments are handled depends on the type
- passsed primitives are COPIED into the formal argument
- so for addOne( i ), the value of i (6) gets copied to the variable x, any changes to x do not affect i
- passed objects are NOT copied, the formal argument represents an alias or reference to the passed object
- so any changes made to the formal argument are also made to the original that was passed in
Methods Assignment
Dots Assignment
Our updated jar file for the assignment
Common Problems
- assignment (=) for objects - mentioned already
- integer versus double division - mentioned already
- confusing = and ==
- "=" is an assignment operation, it changes the value of something
- "==" is a comparison that results in a true or false
int x = 2 ; // correct
int x == 2 ; // incorrect
while( x = 2 ) // this will compile and run but will result in an infinite loop
while( x == 2 ) // correct
