1 of 85

Intro To Java & Computer Science

STEM For Others ©

2 of 85

Table of Contents

  1. Intro + Activity
  2. Data Types + Project
  3. Conditionals
  4. String Methods
  5. Strings and Object Referencing
  6. Review of Week 1-5 + Challenge
  7. Classes + Objects 1
  8. Classes + Objects 2

Additional Project Resources: Java Project List

3 of 85

Week 1 - What is Java?

  • Programming Language - You tell the computer what you want it to do.

  • The “languages” of computer programs: a set of commands that tells the computer what to do

  • What you see on the screens of your computers are all from computer programs

4 of 85

Why is it useful to learn?

  • Learning Java allows you to create your own programs

  • Technology is becoming more and more important in our daily lives

  • You can program games; Minecraft is programmed in Java

5 of 85

Why Java?

  • Simple to learn
    • High skill ceiling
  • It is a very commonly used language
    • Spotify, Minecraft, Netflix

6 of 85

Lets try it out!!

  • Go to your computer’s browser and open repl.it (Set-up accounts if necessary)
  • Open a Java file
    • Try to get it to print out the words “Hello World!”

7 of 85

Lets try it out!!

  • Go to your computer’s browser and open repl.it
  • Open a java file
    • Try to get it to print out the words “Hello World!”

Hint: System.out.print(“what you want to say”)

8 of 85

System.out.println()

  • System.out.println() makes a new line after printing the statement
  • System.out.print() does not make a new line after printing the statement

Try it!

9 of 85

Project

Try making cool shapes and drawings by using System.out.println() for many lines!

For example, try making these cool shapes and drawings!!

10 of 85

Project Solution

Solution code for the drawings!

11 of 85

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.

12 of 85

Data Types, Variables, + Input Function

Data Types: Different attributes used to define data.

  • Integer (int): Whole numbers. Positive or negative without decimals
  • Boolean (boolean): True or False binary
  • Double (double): decimal numbers
  • Character (char): Just one letter

13 of 85

Why do we have different classifications of data?

There are several reasons. One of the main reasons is to help with comparing two things.

  • Can only compare these

if they are the same data type

(like dividing “c” by 7.2, it

doesn’t make sense)

14 of 85

Why do we have different classifications of data?

There are several reasons. One of the main reasons is to help with comparing two things.

  • Can only compare these

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

15 of 85

Variables

  • We’ve been practicing data types in a print function. But what if we want to store and reuse some values that we got or used from our print function for other purposes?

16 of 85

Variables

  • We’ve been practicing data types in a print function. But what if we want to store and reuse some values that we got or used from our print function for other purposes?

  • That’s why variables help! Variables are basically

like boxes where you can put your toys in to save

for later

17 of 85

Variables pt.2

  • We can give names to these boxes and whenever we want to reuse that data in the box, we can simply call the box name and it will give us the value.

18 of 85

Variables pt.2

  • We can give names to these boxes and whenever we want to reuse that data in the box, we can simply call the box name and it will give us the value.
  • The name of the variable is key sensitive. No spaces, if you use different capitalization, you have to call the variable using the exact same capitalization
  • Even if two variables have the same value, they can be different data types and you cannot compare these two which can mess up what you want to achieve.

19 of 85

Practice:

20 of 85

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!

21 of 85

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.

22 of 85

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!

23 of 85

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.

24 of 85

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.

25 of 85

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 ->

26 of 85

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 ->

27 of 85

Writing the Letter

Now that we know how to concatenate strings and variables, we can write our letter!

Tasks

  • Your letter should include a greeting (Hello, Jane) and a closing (From, John).
  • It should talk about an event, include a number, and another person’s name.
  • You need four different variables, one variable that includes all of the other three variables.
  • Use string and variable concatenation.
  • Print out your letter to the terminal window using System.out.println().

28 of 85

Week 2 Project Solution

Output:

Code Solution:

29 of 85

Week 3: Conditionals & Loops

Review: Variables and Datatypes

Name the datatype

30 of 85

Week 3: Conditionals

  • Conditionals are statements that require a condition to be true for the statement to be executed.
    • Ex: If we are hungry, we go to the fridge. If we are not hungry, we will continue doing HW.

  • In code, there are 3 main conditionals: If statements, While loops, and For loops
    • Each has its own specific syntax and if you don’t write it out properly, it will give errors

31 of 85

Week 3: Conditionals & Loops

Parts of the conditional

  1. if
  2. condition
  3. Curly bracket
  4. indentation
  5. end result

32 of 85

Week 3: Conditionals & Loops

Parts of the conditional

  • if
  • condition
  • curly brackets
  • end result

If the condition is true, we can execute the end result

Otherwise the condition executes the other end result.

33 of 85

Week 3: Conditionals & Loops

Parts of the conditional

  • if
  • condition
  • curly brackets
  • end result

If the condition is true, we can execute the end result

Otherwise the condition executes the other end result.

34 of 85

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.

35 of 85

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?

36 of 85

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.

37 of 85

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.

  1. The first statement is executed once before everything else
  2. The second statement is the condition that the loop needs to reach before it ends
  3. The third statement is what happens to the variable in the first statement after every loop

38 of 85

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?

  • The first statement is executed once before everything else
  • The second statement is the condition that the loop needs to reach before it ends
  • The third statement is what happens to the variable in the first statement after every loop

39 of 85

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.

  1. Game Setup:
    • The program should generate a random target number between 1 and 100.
    • The player will have 10 attempts to guess the target number.
    • The program should give feedback after each guess: whether the guess is too high, too low, or correct.
    • The game should end when the player guesses correctly or runs out of attempts.
  2. Looping and Conditionals:
    • Use a while loop to keep track of the player's guesses and remaining attempts.
    • Use if-else statements to check whether the guess is too high, too low, or correct.
    • After each guess, display how many attempts are left, unless the game is over.
  3. End Game:
    • If the player guesses the correct number, print a congratulatory message.
    • If the player runs out of attempts without guessing correctly, print a game over message, revealing the correct number.
  4. User Interaction:
    • The player should be prompted to enter their guess after each round.
    • The program should continuously update the player on how many attempts they have left.

40 of 85

Week 3: Project Solution

41 of 85

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:

  • int length() - returns the number of characters in a string object
  • String substring(int from, into to) - returns the substring beginning at index from and ending at index - 1
  • int indexOf(String str) - returns the index of the first occurrence of str; returns -1 if not found
  • boolean equals(String other) - returns true if string this equals string other; returns false otherwise

42 of 85

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

43 of 85

Week 4: String Methods

Try it out!!

  1. Open a new java file in repl.it
  2. Create a new string
  3. Try out the different string methods and print them out!

Practice: what will this code print out? (remember, indexes start at 0)

44 of 85

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.

45 of 85

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.

46 of 85

Week 5: String and Object Referencing

Practice: What is printed out?

For reference: this is the Person class

47 of 85

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.

48 of 85

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?

49 of 85

Week 6: Review of Week 1-5 + Challenge

  • Data types are different attributes used to define data
  • Data types are split into two groups: primitive and non-primitive data types
  • If statements allow you to make decisions based on certain conditions
  • For loops are used to iterate over code based on a condition when you know how many times it will repeat
  • While loops are used to iterate over code when you don’t know how many times it will repeat
  • The Java String class has many useful built-in methods that you can use on strings with dot notation
  • Objects, which are variables of non-primitive types, hold references to the actual data stored in memory
  • String objects are immutable, which means that once a string object is created its value cannot be changed
  • Strings can be created either using string literals or using the new keyword

50 of 85

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!)

  • import and use the Scanner class to read in user input
  • use break to break out of a loop
  • use a for loop with if and else if statements in it, and an else statement at the end of the loop to catch everything else
  • Have an if statement after the loop for when the right word is never guessed
  • Use a boolean to keep track of whether or not the word is guessed

*For an extra challenge, keep track and print out how many guesses the player has left every time they guess a word!

51 of 85

Week 6: Review of Week 1-5 + Challenge

Sample solution code:

52 of 85

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;

  1. Ex. There can be code that tells the program to ask for the user's name, and then there will be a place for the user to type that information in, which the program will then use and print.

*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:

  1. Scanner scanner = new Scanner(System.in)
  2. [variable_name] = scanner.nextLine()

53 of 85

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

54 of 85

Week 6 Project

Now that we know how to take in input, we can program our game!

  1. Set the Secret Number:�Create a variable to hold the number the user needs to guess.
  2. Prompt the Player:�Display “Guess the number:” on the screen. Use another variable to take the player’s input.
  3. Provide Feedback:
    1. Check if the guessed number matches the secret number.
    2. Print helpful hints:
      1. “Go up!” if the guess is too low.
      2. “Go down!” if the guess is too high.
      3. “Correct!” if the guess is right.
  4. Handle Invalid Inputs:�If the input isn’t a valid number, print: “Invalid guess. Please enter a number.”
  5. Track Attempts:�Keep a count of the guesses the player makes.
  6. End:
    • Once the player guesses the number print Number of guess: [number of guesses]

Now you’re done!

55 of 85

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

56 of 85

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

57 of 85

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

58 of 85

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”

59 of 85

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:

60 of 85

Week 8: Arrays P2 - ArrayList, 2D Array

  • ArrayList methods are called using dot notation

  • All elements in an Arraylist are objects

Practice: What will be printed out?

Hint: the size of an ArrayList changes when elements are added/removed

61 of 85

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

62 of 85

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

63 of 85

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

64 of 85

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…

65 of 85

Week 9: Objects and Classes

  • We use classes to represent things with characteristics in Java
  • Let's say I wanted to represent a car in Java. I could create a car class with characteristics such as color, manufacturer, model, and fuel source. The CLASS is the blueprint while the OBJECT is the actual car (Ex. Green Ford Mustang)
  • A class can also perform actions, these are called methods
  • For example, we could make a honk method that prints out the word honk and call it from our class

66 of 85

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

67 of 85

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!

68 of 85

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!

69 of 85

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!

70 of 85

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.

71 of 85

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

72 of 85

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.

73 of 85

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.

74 of 85

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

75 of 85

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

76 of 85

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

77 of 85

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

78 of 85

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);”

79 of 85

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

80 of 85

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

81 of 85

Week 12: OOP Design and Inheritance

  • A common design pattern in OOP Java programming is the use of “getter” and “setter” functions.
  • A getter function is a public method that returns the value of an attribute
  • A setter function is a private method that sets the value of an attribute
  • Getter functions take no parameters but share the return type of the attribute their returning
  • Setter functions take parameters but have a void return type

82 of 85

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.

83 of 85

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.

  • public class -> class
  • We add any new characteristics as new instance variables.
  • We pass in old arguments to the constructor as well as new ones
  • We use a super keyword to assign values of the old attributes, and create separate lines for new ones

*don’t worry about the spacing in this example, the constructor is split into different lines to make it more readable

84 of 85

Week 12: Project

  • Goal: Create a child class representing a specific animal for your parent Pet class
  • Make sure it has two new attributes in it and getter and setter functions for those attributes
  • In the child class create a convertToYears function that returns an integer of the pet’s age in its respective years. Ex. dog’s age=normal age*7
  • Create a feedPet function which takes in a food parameter and prints out “PET ate FOOD!” where PET is the name attribute and FOOD is the parameter. Call it in the main file. Ex. Lucy ate chicken!

85 of 85

Week 12-End: Semester Project

  • Last week, you had a taste of what it looks like to combine everything we’ve learned into a single program.

  • From this point on (depending on how much time is left before the semester), you will now be focused on creating your own project.

  • It doesn’t have to be as complex as what we did (or it can be more!), but really try practicing what you know, and have fun while doing it!

  • If you need a review/help , your instructor can go back to previous weeks if you ask! GOOD LUCK!!!