Introduction to Java

What is Programming?

  • Basically telling the computer what to do
  • People write out code, which is translated into machine language and executed
  • Code is read sequentially, top-down
    • The computer processes every line of code that you write and executes it exactly as written

Object Oriented Programming

  • Reusable programming objects
  • Like manufacturing multiple cars; instead of redesigning each part every time, a blueprint is made and the cars are created using that blueprint
    • Blueprint == class
    • When the class is made into a real working thing, it's called an object
  • Java is an OOP language

How Java Works

  • Code is written in a programming language (in this case, Java)
  • That human-readable code is compiled into machine language so the computer can execute it using its OS or processor
    • Java is special, it compiles into bytecode, which is run by the JVM
  • Java Virtual Machine (JVM)
    • Abstract computing machine that mimics a processor so it can execute Java bytecode
    • Enables a computer to run a Java program

Preparing for Exercises

  • In your Documents, make a file named java_exercises.java

    • ​cd Documents
    • touch Java_exercises.java
    • nano Java_exercises.java
class Java_exercises {
    public static void main(String[] args) {
        // exercise code here
    }
}

In Java, // denotes comments. Everything after the // is commented out, so the computer doesn't register it

Basic Java/Programming Concepts

  • Syntax
  • Data types
  • Variables
  • Arrays
  • Operators
  • Conditional Statements
  • Loops
  • Methods
  • Classes & Objects

Syntax

  • Basically grammar for computers
  • Fundamental syntax rules for Java:
    • Every statement ends with a semicolon (;)
    • Scopes are defined with braces/curly brackets ({})
    • White space separates things
      • If a name has a space in it, the computer will view the second word as something completely different from the name

Data Types

  • String
    • "This is a string."
  • boolean
    • true/false
  • int
    • Integer (whole numbers)
  • short
  • long
  • float
    • Floating point (decimal numbers)
  • double
  • char
    • Alphanumeric characters

= vs ==

  • = assigns
    • The value on the right gets assigned to the variable on the left

    • ex int num = 10;
  • == compares values and checks for equality
    • Returns true or false
    • ex num == 10;

Variables

  • A variable is something that store data
  • Must follow certain naming conventions
    • NEVER start with a number
    • NO spaces
      • Use underscores or camel casing
      • ex thisIsCamelCasing
    • No special characters (*,.!@#;: etc)
    • Do NOT use Java key words as variable names
  • In Java, they must be typecasted
    • ex int varName = 10;
    • ex String varName = "This is a string.";
  • Initialization syntax: dataType variableName = value;
    • If you don't assign a value, it initializes to null, 0, or false (depending on the data type)

Variables

  • In your main method, type the following code:
class Java_exercises {
    public static void main(String[] args) {
        int irene = 100;
        System.out.println(irene);
    }
}
  • We just created a variable, called "irene"
  • What is the data type of the variable irene?

Variables

  • A variable varies, and can be reassigned. Try:
class Java_exercises {
    public static void main(String[] args) {
        int irene = 100;
        irene = 200;
        int john;
        john = irene;
        System.out.println(john)
    }
}
  • Notice any differences in the initialization and assignment of irene and john?
  • What was the value of john before assigning it irene?

Strings and Variables

  • Anything encased in quotes (" ") is a string
    • ​Without quotes, it'll be read as a variable name
  • Change the code in your main method to:
    • String fred = "This is a string.";
    • System.out.println(fred);
  • Now add the following code:
    • fred = "This is not a string;
  • Concatenation
    • You can combine strings with other strings and variables (even of different data types) with +
    • int age = 5;
    • fred = "My age is " + age;
    • System.out.println(fred);

Operators

  • +, -, *, /, %, <, >
  • Order of operations anyone?
  • Change the code in main():
float num = 5*5+10/3;
System.out.println(num);
num = num*12;
System.out.println(num);

Arrays

  • If you wanted to store a shopping list in a variable, you could create a string:
    • String shopping_list = "eggs, milk, baking soda";
  • Another way we could do it is by using an array
    • String[] shopping_list = new String[5];
    • shopping_list[0] = "eggs";
    • shopping_list[1] = "milk";
    • shopping_list[2] = "baking soda";
  • This is useful if you want to access specific entries
    • Access or change values with [index#]
  • Java uses zero-based indexing
  • Syntax for arrays:
    • dataType[] arrayName = new dataType[size];

If Statements

  • if is followed by a condition in parentheses and curly braces.  If the condition is met, the block of code inside the braces is executed.
if(age > 17) {
    System.out.print("You are too old!");
}
  • Conditional operators
    • ==, !=, >, <, >=, <=

What Else is There?

  • If statements can be extended with an else statement
  • So, if the condition isn't met, it would execute a different block of code (if something is true, then do this, otherwise do that)
int age = 18;

if (age == 12) {
    System.out.print("Hello");
} else {
    System.out.print("Goodbye");
}

Else if Statements

  • If statements can be further extended using else if
  • If the previous if statement's condition isn't met, then it check the else if's condition, and so forth.
    • Once an if statement's condition is met and it executes, it does not move on to the next else if or else statement.

else if example

int age = 12;

if (age == 11) {
    System.out.print("You are 11");
} else if (age == 12) {
    System.out.print("You are 12");
} else if (age < 13) {
    System.out.print("You are younger than 13");
} else {
    System.out.print("You are older than 13");
}

What will be printed?

Combining Conditions

  • You can have multiple conditions in any conditional statement, by using && (and) and || (or) 
if (age == 12 || age == 13 || age == 14) {
    System.out.print("You are "+age+" yrs old);
}
  • If any of the conditions are met, then the code runs, hence the or
if (age >= 10 && age <= 14) {
    System.out.print("You are "+age+" yrs old);
}
  • If all of the conditions are met, then the code runs, hence the and

Quick Review Exercises

  • Create variables for your first name, last name, and age. Now concatenate your variables to a string to form a cohesive sentence. Print that string.
    • Ex. My name is John Headland, and I'm 27 years old.

 

  • Write a sequence of conditional statements that prints a number if that number is equivalent to 15, 16, 17, or 20.

 

  • Create an array that contains a list of your favorite foods as strings. Set it to a certain size and completely fill it with elements.

Quick Review Exercise

Create an array containing at least 3 of your hobbies. Then, use conditional statements to print each element if they are less than 10 characters, or a string saying "That information is inaccessible, there are X characters." where X is the amount of characters in the string.

 

Hint: append .length() to the String name (Ex. hobby1.length()) to access an int containing the length of the string.

Loops

  • Repeatedly executing code written in the loop until/while a condition is met
  • for loop & while loop
  • How can this be useful?

For loops

  • For loops iterate a limited number of times, by initializing a variable and incrementing or decrementing that variable until it stops meeting a given condition
  • for (type var = value; var == condition; var = var + 1) {}
int y = 1;

for (int x = 0; x < 5; x++) {
    y = y + x;
    System.out.println(y);
}

While we're on Loops

  • While loops iterate through the block of code while a condition is met
    • Different from for loops, because it's while, not until
  • while (condition) { // code here }
int x = 1;

while (x < 200) {
    System.out.println(x);
    x = x*2;
}

Break

  • You can break out of a loop before the ending condition is met
​while (true) {
    // tons of code
    if someCondition == true {
        break;
    }
}

Nested Loops

  • Loops placed inside each other are nested loops, and each inner loop fully complete before returning to the outer loop
String[] array = new String[3];
array[0] = "a";
array[1] = "b";
array[2] = "c";

for (int u = 0; u < array.length; u++) {
    System.out.println(array[u]);
    for (int v = 0; v < array.length; v++) {
        System.out.println(array[v]);
    }
}

Loop Review Exercise

If you have $100 saved in your bank account, and they pay you 3% interest every year, how much money will you have for each year, up to 10 years?

 

Hint: Use a for loop (you can use a while loop, but it'll take more code).

Methods

  • Methods (known as functions in other languages) allow you to write your code just once and reuse that code in your programs, multiple times
  • Methods take in parameters, which are variables you give it that are only available in the body of the method (the code inside of it)
modifier returnType function(parameter) {
    // code goes here
}

Example of a Method

You define (make) the method outside of main() like this:

public static void printName(String name) {
    System.out.println("Hello " + name);
}

And call the method inside of main() like this:

printName("John");

Which will print out: Hello John

Example of a Method

Another example, except with return instead of print():

public static int savings(int job, int spending) {
    return job - spending;
}

And call it (inside of main()) like this:

int money = savings(20, 5);
System.out.println(money);

What does return do? What's the difference between return and print()?

Return Values

  • You determine whether a method returns something or not, and its data type when defining the method
    • Ex. public static int savings(parameters) {}
      • This method returns an integer
  • When a method returns something, it saves the value that goes after the word return
    • Ex. int x = savings(20, 5);
      • The savings() method returns an int and that returned value gets assigned to x
    • If you don't save/assign the returned value to a variable or immediately print it, it disappears
  • Put void as the return type if your method just does something and doesn't need to store a value

Modifiers (Privacy/Mutability)

  • You define the privacy of a method with the first word when making it
    • public: it can be accessed anywhere
    • private: it can only be accessed within the class it's defined
    • protected: it can only be accessed within the package
    • All of the previous examples use public, you can ignore private/protected for now
  • Mutability determines if something can be changed or stays the same
    • static: it belongs to the class, not the instances of the object.

Scope

  • Not all variables are accessible from all parts of our program.
  • Where a variable is accessible depends on how it is defined.
  • We call the part of a program where a variable is accessible its scope.
  • ​A variable which is defined in the main body of a file is called a global variable.
    • It will be visible throughout the file, and also inside any file which imports that file.
  • A variable which is defined inside a method is local to that function.
    • It is accessible from the point at which it is defined until the end of the method
// This is a global variable
int a = 0;

if (a == 0) {
    // This is still a global variable
    int b = 1;
}

public static void my_method(int c) {
    // this is a local variable
    int d = 3;
    System.out.println(c);
    System.out.println(d);
}

// Now we call the function, passing the value 7
// as the first and only parameter
my_function(7);

// a and b still exist
System.out.println(a);
System.out.println(b);

// c and d don't exist anymore -- these statements
// will give us name errors!
System.out.println(c);
System.out.println(d);

Main Method

  • The main() method is where everything runs!!
    • So when you execute your program, the JVM only runs what you've written in main()
    • Make sure you call your other methods and classes within main()!
public static void main(String[] args) {
    // code that gets executed
}
  • Methods should be defined outside of main()
    • It would be best to define the methods in another class, and call them after instantiating that class into an object (we will get to what these terms mean after the exercise)
// This is how your code should be structured!

public class MyClass {

    public static void method1() {
        // code
    }

    public static double multiply(int num1, int num2) {
        // code
    }

    public static void main(String[] args) {
        method1();
        double product = multiply(12, 3.3334);
    }

}

Method Review Exercise

Define a method overlapping() that takes two arrays as arguments (parameters) and returns true if they have at least one element in common, false otherwise.

Then call the method, and if it evaluates to true, print out a string, "There is a common element in the arrays!" Print "These arrays do NOT have a common element" if it is false.

 

Note: Write this using a nested for-loop

If you finish early: Modify the code so the print statement specifies the amount of common elements.

Classes

  • A class is a blueprint in which individual objects are created
  • Each .java file that begins with a capital letter is a class
  • Classes have their own member variables, methods, and constructors
    • Member variables are information pertaining to the object that are necessary for the class
    • Methods are the actions the objects can do/undergo
    • Constructors are the default state of the objects created from the class 
      • Defined with the same name and no return type
  • The objects (that are instances of classes) model real world objects using Object Oriented Programming (OOP)
// This class models a bicycle
public class Bicycle {

    // Bicycle has two member variables
    public int gear;
    public int speed;

    // Bicycle has one constructor
    public Bicycle(int startSpeed, int startGear) {
        gear = startGear;
        speed = startSpeed;
    }

    // Bicycle has three methods
        
    public void setGear(int newValue) {
        gear = newValue;
    }
        
    public void applyBrake(int decrement) {
        speed -= decrement;
    }
        
    public void speedUp(int increment) {
        speed += increment;
    }

}

Objects

  • Objects are instances of classes
    • Essentially making the object from the blueprint
  • You initialize objects by defining them with the new keyword, and making the data type the class:
    • ClassType objectName = new ClassType(constructorParameters);
    • Ex. Bicycle bike = new Bicycle(45, 1);
  • You access the class's public member variables and methods with a period (.) after the object's name
    • objectName.method(parameter);
    • Ex. bike.speedUp(3);

Introduction to Java

By jtheadland

Introduction to Java

  • 850