Intro To Java & Computer Science
STEM For Others ©
Table of Contents
10. Data Structures
12. Semester Project
13. Semester Project
14. Semester Project
15. Semester Project
Additional Project Resources: Java Project List
Week 1 - What is Java?
Why is it useful to learn?
Why Java?
Lets try it out!!
Lets try it out!!
Hint: System.out.print(“what you want to say”)
System.out.println()
Try it!
Project
Try making cool shapes and drawings by using System.out.println() for many lines!
For example, try making these cool shapes and drawings!!
Project Solution
Solution code for the drawings!
Week 2 - Primitive Data Types, Variables
Data Types: Different attributes used to define data.
Primitive Data Types: The most simple data types, cannot be simplified further.
Data Types, Variables, + Input Function
Data Types: Different attributes used to define data.
Why do we have different classifications of data?
There are several reasons. One of the main reasons is to help with comparing two things.
if they are the same data type
(like dividing “c” by 7.2, it
doesn’t make sense)
Why do we have different classifications of data?
There are several reasons. One of the main reasons is to help with comparing two things.
if they are the same data type
(like adding “k” by 8, it
doesn’t make sense)
Practice:
Print out the product of 3 and 10
Print out the sum of 3.5 and 2.0
Bonus: print out the sum of ‘c’ and 29
Variables
Variables
like boxes where you can put your toys in to save
for later
Variables pt.2
Variables pt.2
Practice:
Week 2 Project - Writing a Letter
For this weeks project, we are going to write a letter to any person in the world using what we have learned so far.
To start, search up https://www.bluej.org/ on your web browser and scroll down to the section titled “Download and Install” and click on Windows/macOS (based on what laptop you have)
Finish the setup, open up BlueJ, and click on Project > New Project and rename the project to “writingaletter”
In case you were wondering, Blue J is a free development environment that allows you to develop Java programs quickly and easily!
Week 2 Project - Writing a Letter
*Delete all of the code written in the program currently, you won’t need it for this project.*
Objective
Combine strings and variables to generate a simple letter like this!
In order to combine string and variables, we need to understand what string concatenation is!
Click on New Class > change class name to “Letter” and click OK > click on to open the class.
String Concatenation
concatenation (Merriam-Webster definition): a group of things linked together or occurring together in a way that produces a particular result or effect
String Concatenation - joining two or more strings to create a single new string
Now that we know string concatenation, let’s practice it!
String Concatenation
In BlueJ, let’s write a line of code involving string concatenation. First we need to write our class header. Write this line of code.
Then write Java’s main method inside your class header, like this:
Java’s main method will be explained in the next slide.
Java’s main method
Main method: public static void main (String[] args)
It is the entry point for any Java program.
Keywords
public - makes the method accessible from anywhere
static - allows the method to be called without creating an instance of the class
void - indicates that the method doesn’t return any value
String[] args - array that stores command-line arguments, allowing users to input data when they run the program
This setup is essential for Java programs to function correctly.
String Concatenation
Let’s make the word Snowball. Write this string variable inside our main method in BlueJ.
On the next line, write this line of code to print out Snowb
all to our output window.
Click on Compile (and debug if needed) > right click
> click on “void main(String[] args)” and click OK to see your result ->
Concatenation with a Variable
Let’s concatenate (connect) the strings we used to make the word “Snowball” with a variable to create the word “Snow8ball”.
Write this line of code on the line above the string variable 8.
Then, plug in variable num in your string variable word like this:
Click on Compile (and debug if needed) > right click
> click on “void main(String[] args)” and click OK to see your result ->
Writing the Letter
Now that we know how to concatenate strings and variables, we can write our letter!
Tasks
Week 2 Project Solution
Output:
Code Solution:
Week 3: Conditionals & Loops
Review: Variables and Datatypes
Name the datatype
Week 3: Conditionals
Week 3: Conditionals & Loops
Parts of the conditional
Week 3: Conditionals & Loops
Parts of the conditional
If the condition is true, we can execute the end result
Otherwise the condition executes the other end result.
Week 3: Conditionals & Loops
Parts of the conditional
If the condition is true, we can execute the end result
Otherwise the condition executes the other end result.
Week 3: Conditionals & Loops
Similar to if statement, but while loops will go on forever until the condition isn’t satisfied
(Try it yourself!)
Each time we go through the loop, we add 1 to i until it is equal to 5.
Week 3: Conditionals & Loops
Similar to if statement, but while loops will go on forever until the condition isn’t satisfied
(Try it yourself!)
Each time we go through the loop, we add 1 to i until it is equal to 5. When it is equal to 5, we don’t go through the loop.
Practice: Can we write a while loop to add 1 to i until it equals 27?
Week 3: Conditionals & Loops
Similar to while loops, for loops go on until the 2nd statement is fufilled
Each time we go through the loop, we add 1 to i until it starts to equal 10.
Week 3: Conditionals & Loops
Similar to while loops, for loops go on until the 2nd statement is fulfilled
Each time we go through the loop, we add 1 to i until it starts to equal 10.
Week 3: Conditionals & Loops
Similar to while loops, for loops go on until the 2nd statement is fulfilled
Practice: Just like the while loop, can we write a for loop to add 1 to i until it equals 27?
Week 3: Project!!
Objective: Your task is to create a Java game where the player has to guess a randomly generated number between 1 and 100. The player will have 10 attempts to guess the correct number. After each guess, the game will tell the player whether their guess was too high, too low, or correct. If the player runs out of attempts without guessing correctly, the game will end.
Week 3: Project Solution
Week 4: String Methods
The Java String class has a variety of built in methods that you can use on strings. They are very useful and helpful to know. Some of the most important string methods are:
Week 4: String Methods
String methods are called on string objects using the dot notation
<- Prints out 5, the number of characters in the string “hello”.
Format: string name + period + function name + parenthesis
Week 4: String Methods
Try it out!!
Practice: what will this code print out? (remember, indexes start at 0)
Week 5: String and Object Referencing
Objects, or variables of non-primitive types, hold references (or pointers) to the actual data stored in memory.
When you create an object, you create a reference variable that points to that object which allows you to access the value of that object.
For example:
Here, person is a reference variable pointing to an instance of the Person class.
Week 5: String and Object Referencing
When you assign one reference variable to another, both references point to the same object
For example:
Now, both person and anotherPerson reference the same Person object.
That means that if you make any changes to person, when you access anotherPerson, the same changes will have been made to anotherPerson, and vice versa.
Week 5: String and Object Referencing
Practice: What is printed out?
For reference: this is the Person class
Week 5: String and Object Referencing
Strings are immutable, which means that once a String object is created, its value cannot be changed.
Methods that appear to modify a string actually create a new string object
Strings can be created in two ways:
1: String Literal
When you use string literals, Java has a pool of strings and checks if the string exists in the pool. If it does, the existing reference is returned, or else a new string is added to the pool.
Week 5: String and Object Referencing
2: Using the new keyword
This explicitly creates a new string object in memory, even if an equal string exists in the string pool.
str1 and str2 reference different memory locations, even they have the same contents, because str2 was explicitly created with the new keyword which creates a new string object in memory, different from the one of str1
Practice: What does this print?
Week 6: Review of Week 1-5 + Challenge
Week 6: Review of Week 1-5 + Challenge
Challenge: Create your own Wordle!
Rules: Player gets 6 tries to guess the 5-letter word which you choose. For the word the player guesses to count as a guess, the word needs to be 5 letters long.
Hints: (not required, just some ideas and pointers if you get stuck!)
*For an extra challenge, keep track and print out how many guesses the player has left every time they guess a word!
Week 6: Review of Week 1-5 + Challenge
Sample solution code:
Week 6 Project!
We will be programming a game this week! To be able to we first need to learn how to take input:
*Taking input means taking data from the user to use in the program;
*Keep in mind that there are different ways of taking input for different data types but that for this one you will only need to know how to take in String input
To take input in for this project you need these lines of code:
Week 6 Project
This color is for what the program prints
This color is for what you input
This color is for what is added to the code so it can take input
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println(“What is your name:”);
Scanner scanner = new Scanner(System.in);
String name;
name = scanner.nextLine();
System.out.print("Hello "+ name);
}
}
What appears:
What’s your name:
Sahasra
Hello Sahasra
Week 6 Project
Now that we know how to take in input, we can program our game!
Now you’re done!
Week 7: Arrays P1 - 1D Array, Traversing an Array, Arrays of Strings
An array is a container object that holds a fixed number of values in a single type. The length of an array cannot be changed after its creation.
To declare an array, it’s the same as declaring a variable except the variable type is followed by square brackets
This number is the amount of elements in the array
Array indexes start from 0, and you can access the elements in the array with the array name and then the index in brackets
Week 7: Arrays P1 - 1D Array, Traversing an Array, Arrays of Strings
We can use iteration with a for loop to visit each element of an array, which is called traversing the array.
Starts at the index 0, and loops while the index is less than the array length.
Prints out the elements of the array at each index
Week 7: Arrays P1 - 1D Array, Traversing an Array, Arrays of Strings
There are many uses for arrays of strings. For example, you could sort all the elements and print them out in order, or search for a specific word in the array
Sorts the string array and prints out the elements in ascending order:
apple
banana
cherry
*Another way to create an array is with curly brackets and putting all the elements in it
Week 7: Arrays P1 - 1D Array, Traversing an Array, Arrays of Strings
Checks if the word cherry is in the array, and if it is prints the index
Prints out “Found at index 1”
Week 8: Arrays P2 - ArrayList, 2D Array
The ArrayList class is a resizable array and has a slightly different syntax than the array.
How to create an ArrayList object:
The ArrayList class also has a variety of useful methods:
Week 8: Arrays P2 - ArrayList, 2D Array
Practice: What will be printed out?
Hint: the size of an ArrayList changes when elements are added/removed
Week 8: Arrays P2 - ArrayList, 2D Array
A 2D array is an array of arrays. It is useful when you want to store data in tabular form, like a table with rows and columns.
To create a 2D array, it’s the same as for a regular array except instead of one set of brackets, you put two set of brackets after the variable type.
Instead of just using one set of curly braces, each array within the array has its own set of curly braces
Week 8: Arrays P2 - ArrayList, 2D Array
To access the elements in the 2D array, specify two indexes: one for the array, and one for the element inside that array.
To change the value of an element, it is a similar format to a 1D array
Week 8: Arrays P2 - ArrayList, 2D Array
To loop through a 2D Array, you can use a nested for loop, or a for loop inside another for loop to get the elements of the array (we still have to point to the two indexes)
This will print out all the elements in the 2D array myNumbers
myNumbers.length will get you the number of arrays, myNumbers[i].length will get you the length of each array
Week 9: Objects and Classes
Before continuing to program more complex projects in Java, we need a way to make our code design more organized…
This is where Object Oriented Programming (OOP) comes in!
Object Oriented programming is the process of using organized structures called Objects and Classes to make our code more reusable and easier to understand, which can help us solve problems quicker.
Now let's get into the details of what Objects and Classes really are…
Week 9: Objects and Classes
Week 9: Objects and Classes
Each class in Java has three parts (excluding the header). These parts are the instance variables, constructor, and methods.
This is the header of the class, where you can name it.
Make sure your file is named the same as your class
Week 9: Objects and Classes
The instance variables section will list out all the characteristics of your class. Typically, you use the format private Type Name when creating these. List out all the instance variables for the Car class!
Week 9: Objects and Classes
The instance variables section will list out all the characteristics of your class. Typically, you use the format private Type Name when creating these. List out all the instance variables for the Car class!
Week 10: Constructors
Last week we left off on adding our instance variables, lets now figure out how to create a constructor, an essential part of building a java class!
Week 10: Constructors
To build a constructor we type public Name and add all our instance variables into parentheses after it. Make sure to suse public Car and not public class Car for the constructor.
Week 10: Constructors
Now inside the curly brackets, list your instance variables in this fashion. this.variable = variable. Do this for all your variables. Once you have finished that, your code should look like this.
This syntax can be confusing so take a minute to try and understand the code.
Initializing variables. However, they are empty
Allows for us to pass in values for each of these characteristics
Setting the values we pass in as the values of the variables we initialized
*The use of the word “this” will make more sense when we move onto methods
Week 10: Exercise
Create a your own pet class! Think about what characteristics a pet has and create a class for it. Some examples you can use are species and color. Try to think of at least five class attributes for your pet class.
Week 10: Exercise Solution
This is just one example of a pet class. Your class can have different attributes, so don’t be afraid if it looks a bit different! Just make sure you got the essential syntax right and that your types match your variables.
Week 10: Objects
Now lets learn how to make objects! Creating a new object is a lot like creating a new variable. Let’s use the pet class we just made. Back in your main file, type this.
Notice how the values in the parentheses are the same characteristics I defined in my class. By passing these values im telling the class that my pet lucy is a species: dog, color: yellow, name: Lucy, age: 6, and hasFourLegs: true
Week 10: Objects Mini Exercise
Take this code and modify it to fit either your pet or a made up one. Make sure the values you pass in are the same types as the ones you defined in your own class AND are in the same order
Notice how the values i pass in and the ones i defined in my constructor are aligned in the same order and are the same type
Week 11: Methods
Now that we have a class and an object, we want to achieve something with these structures. Lets trying making our pet do a trick! We can do this using methods. Go back to your Pet.java file and type this. This is the function declaration.
public - this method can be accessed by other classes and files
void - the function doesn’t return anything. We’ll get into returns later
sit - the name of the function
Week 11: Methods
To make the function run code, we type our code inside the braces. I’m going to make my function print “your pet sat” but you can modify that how you like
Week 11: Methods
Instead of printing your pet sat, I want the message to be specific to the pet. For example, for the Lucy object, I want the console to print Lucy sat.
I can do this using the this keyword. “This” represents the object itself. this.name would give me the name of the specific Pet, this.age would give me the age of the object. We can only use this in the class file though.
Let’s try it out!
*In the sit function in Pet.java
And just like that, the message is specific to my pet!
*This also means that instead of modifying the method code whenever we want a different name for the message, we instead just alter the value we pass in the object declaration, “Pet lucy = new Pet("dog", "yellow", "Lucy", 6, true);”
Week 11: Methods
Now to further customize this example, I want the user to be able to pass in what action their pet is doing! We can do this by giving our method parameters. Parameters are customizable values we can pass into methods to change their behavior
Let’s try it out in the Pet class.
In Pet.java create a trick method that takes in an action parameter. The parameter is defined in the parentheses after the method name
Now call it in the main file, and input your value
Week 11: Methods
Sometimes, instead of printing something out, we want to return a value. For example, I may want to return my pet’s age in dog years to store in a variable. We do this using the return keyword and by changing the function declaration.
I’m going to make a new function called returnDogYears which will give me an integer value for my pet’s age in dog years. (feel free to modify this for your specific pet…cat years, fish years, bird years)
*In Pet.java after the sit function
We can then use this function in the main code. If you try printing out this variable you will receive 42.
Return type changed
Return Keyword
Week 12: OOP Design and Inheritance
Week 12: OOP Design and Inheritance
Sometimes we like to create subclasses of other classes. Notice how until now we’ve had a broader Pet class rather than specific pets like a Dog, Fish, or Bird class. Something we can do in Java is pass down all characteristics of the Pet class into smaller subclasses, like a Dog, Fish, or Bird class. This is known as inheritance
*Subclasses are called child classes and the classes they inherit from are called parent classes
This portrays the OOP structure we’ve learned about so far.
Week 12: OOP Design and Inheritance
We inherit from parent classes using the extends keyword. The structure of a child class is nearly identical to that of any regular class. Create a new Dog.java file and begin coding
Keep a track of the syntax.
*don’t worry about the spacing in this example, the constructor is split into different lines to make it more readable
Week 12: Project
Week 12-End: Semester Project