This is the console.

Introduction

What Is This Website?

Hi! Welcome to Javatastic's first lesson page: Unit 1! These lessons are based off of the AP Computer Science A curriculum, but the content has been specifically designed and reworked for beginners. There will be a multitude of interactive objects in this website such as exercises, quizzes, and videos. These lessons will teach you very important concepts in Java and computer science in general. We also have very useful "Codingbat-style" exercises for intermediate programmers and a challenging quiz for AP CS students. If you're looking for those resources, check out the exercises and quiz links in the navigation menu, otherwise, continue on ahead!.

Check out the units within the AP Computer Science A course to get a sense of this website's content.

You can check out this video if you want a slower paced introduction to Java.

Where Do I Start?

If you have experience in coding in block languages, you may be pretty familiar with the content within these lessons. One thing you should keep in mind though is that Java requires a careful attention to detail. If you mispell a keyword or forget a semicolon in your program, you're toast! In order to write code, you're gonna need an Integrated Development Environment, also called IDEs for short. They make coding a lot easier and you can pick the one you like best! There's also a built-in IDE that you can open up in the bottom left corner of the website.

Here's a bunch of IDES you can check out.

IntelliJ IDEA

Eclipse

Apache Netbeans

Android Studio

NOTE!

Do you see the tab with the white arrow pointing up in the bottom left corner of the browser window? Click on it to open up the IDE (Integrated Developer Environment).

This is what java code looks like. Try copying it and pasting it into your IDE!


public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}
                        

What If I'm Lost?

Learning to code can be tough, but it feels very rewarding when you finally figure it out! Your brain also grows while you're figuring out how to solve problems and fix errors, so keep a growth mindset and stay positive. And if you want some help while coding, try pair programming with a friend. It's when two people work together on one computer. One person types while the other gives ideas and feedback. It's a great way to learn and write better code!

Section 1: First Steps

What Is Java?

Java is a Programming Language, a special kind of language that you can use to communicate with the computer. You can use Java to create all sorts of applications such as Minecraft and Netflix. There are different types of programming languages, such as Python or C++, and these programming languages each fall into their own categories. Java is an Object-Oriented Language, meaning it is designed around objects rather than functions. To put it simply, objects are things that store data while functions are things that receive and do stuff with data. A vital aspect of Java and Object-Oriented Programming as a whole is the Class. A Class is basically a blueprint for making objects.

Apps made with Java.

Minecraft

Netflix

Procedural vs Object-Oriented Programming Languages

This is how classes are set up. You can change the name of the class "Main" to anything you want, but make sure it is the same name as your Java file


public class Main {}
                        

NOTE!

Due to how this website's IDE is set up, you can not change the name of the Main class or else it won't run your code.

Use the .java extension so the computer knows it is a Java file.

The Main Method

In order for your program to actually do something, you're gonna need a Main Method. A method is just a fancy term for a function within an object. The Main Method is a special type of method that automatically runs when the program starts. However, you will need to define what your main method will do, that is where Statements come in. A Statement is just a line of code that does a specific action, such as calling another function. You can write a Print Statement to print out anything you specify within the parentheses.

Take a look at this code. Notice how the main method is structured within the class.


public class Main {
    public static void main(String[] args) {}
}
                        

You can write print statements like this.


System.out.print();
System.out.println();
                        

NOTE!

print() will print only what is inputted, but println() will print a new line after printing the input.

String Literals

You can input numbers into the print statement for them to printed out into the console. If you've noticed, putting letters into your print statement will give you an error. In order to fix this issue, you will need to create a String Literal. String Literals are letters, words, or sentences surrounded by quotation marks so that Java will recognize them as such. The program runs the what is in the main method and will output the results into the console. The console is the place where the results of your code is outputted.

Try out the exercise below to get a taste of printing strings.

Printing Strings

Try to get the program to print "Hello world!" into the console.

This is the console.

Bugs

Remember any errors you've encountered as you've been coding? They're called Bugs, and the specific type of bug you've encountered is called a Syntax Error. The reason they occur is because the Compiler fails to understand and Compile your code. The Compiler is basically a translator that turns your code into machine code that the computer can actually understand. Machine code is just a bunch of 0s and 1s that is unreadable to people, but understood by computers. The process of fixing these bugs is called Debugging. Many professional programmers also write little pieces of code called Comments. These are just notes left by programmers for themselves or other programmers and they are not read by the compiler.

The first bug ever recorded was actually a real bug found inside of the computer.

Comments are written like this. You can use them to hide parts of your code from the compiler so you don't get any errors.

    
    //This is a single line comment. Use it for one line in your code.
    
    /*
    This is a multi line comment
    Use this for multiple lines in your code
    */
                        

Section 2: Variables and Data Types

What Are Variables?

Alright, let's talk about Variables! Variables are pieces of code that you can use to store simple types of data. The type of stuff you can store in a variable is dependent on its Data Type. Data Types are just different types of data, such as numbers or words. Variables can only hold data from one type only. There are two main types of variables, Primitive Variables and Reference Variables (also known as objects!). Primitive Variables are simple and can store numbers. Reference Variables are much more complex and can store a wide variety of things such as other objects and functions.

What Are Data Types?

There are three main types of primitive data types, int, double, and boolean. An int is a whole number that can be positive or negative. A double is just like an integer, but they are decimal numbers instead of whole numbers. A boolean is either a true or false value and are often used for if statements. Remember Strings? Well, it turns out that they aren't primitive types, they're actually reference types (objects). A String, as you've seen before, can store letters, numbers, and symbols. You can Concatenate Strings, meaning you can combine two strings together, by using the + sign.

Chart of Data Types

How Do I Create A Variable?

In order to create a variable, you must Declare it, meaning you must give it a type and a name. When you declare a variable, the computer actually leaves aside a certain number of Bits within the computer's Memory to store data for your variable. Bits are basically just 0s and 1s and are the simplest type of data a computer can store. Technically, all data types are made up of bits, their complexity just depends on the number of bits used to create that data type. The computer's Memory is an electronic device used to store data temporarily, not to be confused with storage. You can name your variables anything you want, except for keywords such as "int" or "boolean". Most professionals use a naming system for their variables, such as Camel Case, to keep them consistent. If you want to make sure the value you give to your variable doesn't change, you can use the final keyword.

Look at the example below to see how variables are declared. Notice how you need a data type as well as a name.

final int num = 1;
double decimal = 3.5;
boolean hasNum = true;
                        
Check out the video below for a more in-depth lesson on how computer memory works.

Funny List of Variable Naming Conventions

Section 3:Operators and Arithmetic

How Do I Assign Values To My Variables?

I hope you like math cause we're gonna use it in our code. Remember variables? Well, to assign values to your variables, you will need the Assignment Operator! An Operator is a symbol used in Expressions to perform actions in your code. Expressions are statements that use operators. The Assignment Operator (=) is a type of operator that is used to assign values to variables. When you assign a value to a variable for the first time, it is called initialization. You can also update variables by reassigning new values to them. You can even use the value within variables to store them within other variables!

Here is how to use the assignment operator. You can also reassign values to variables.


int x = 1;
x = 2;
                        

NOTE!

Do not reassign a new value to a final variable! It will produce an error.

What Are Arithmetic Operators?

There are also other types of operators such as the arithmetic operators. These operators can add, subtract, multiply, and divide integers and doubles. Use the +, -, *, / symbols to perform arithmetic expressions. Expressions with more than one operator are called Compound Expressions. There is a certain order when it comes to compound Expressions and this order is known as Operator Precedence. Basically, they follow the standard conventions of arithmetic, starting with parentheses, then multiplication or division, and then addition or subtraction. If you try to perform an impossible mathematical task, such as dividing by 0, the computer will produce an Arithmetic Exception after compiling. If you perform arithmetic operations with values of the same data type, they will always evaluate to the same data type. For example, ints will always return an int and doubles will always return a double. However, if you combine ints and doubles in an expression, it will always return a double.

Informative Chart of All Operators and their Precedence

Integer Division

If you divide two integers, you'll get an integer in return which may not be what you expected. Try to print out 5/2. Try to find a way to make it print out the correct value using a double.

This is the console.

NOTE!

If you divide by 0, you'll get an Arithmetic Exception error!

What Are Some Other Operators?

There's also another operator called the Modulo Operator and it looks like this: %. Use this operator to get the remainder of a division. For example, 5 % 2 is 1 because 2 goes into 5 two times with a remainder of 1. There are some other operators that will be talked about later on. You can use the Equality Operator (==) to compare to values. If they are the same, it will return "true", otherwise, it returns false. To negate an equivalence operator, you can use the Not-Equals Operator(!=) to check if two things are NOT equal.

Equality

Try to print out an equality operation between an integer and a double of the same value.

This is the console.

Section 4: Compound Assignment Operators

What If I Want To Operate and Assign Together?

Now you might be wondering, what if I want to perform an operation AND reassign a variable at the same time. Well don't worry, cause you can just reassign a value like this: x = x + 1;. But, there's another operator you can use specifically designed for this called Compound Assignment Operators To write them, just place the arithmetic operator right before assignment operator like so: x += 1;. And guess what? It works with all of the other operators you learned about in the last section. There's also another operator called the Increment Operator that increases a variable by 1. All you have to do is just add two + signs in front of (or behind) a variable, like so: x++. Oh, and guess what? There's also a sign for Decrementing, meaning decreasing by 1, and yes, you use the -- sign.

Here are some examples of compound assignment operators


x += 2; //Same as x = x + 2;
x -= 2; //Same as x = x - 2;
x *= 2; //Same as x = x * 2;
x /= 2; //Same as x = x / 2;
x %= 2; //Same as x = x % 2;
x++; //Same as x = x + 1;
x--; //Same as x = x - 1;
                        

NOTE!

Here's a neat debugging trick called Code Tracing. Basically, you just trace the path your code takes to understand what is happening to your variables and functions to find any possible errors.

Section 5: Type Casting

What If I Want To Change Data Types?

You can simply change the data type of your value or variable by simply using Type Casting! Type Casting is when you convert a value into a different type. In order to cast a value, just use the cast operator right before the value you want to cast. The cast operator is the name of the data type surrounded by parentheses, like this: (int). When you convert a double to an int, it will truncate, or cut off, the decimal values, essentially rounding it down. Remember back when if you use a double and an int in an expressions, a double is returned? Well, that's an example of implicit casting, which means it casts the data type automatically.

Type Casting Diagram for increasing and decreasing bit size

Here's an example of how type casting works


int x = 2; //x is an integer
int y = x / 5; //will evaluate into an integer value of 0
double z = (double) x / 5; //Converts x into a double before division and evaluates to 0.4
                        

NOTE!

Converting doubles to ints will truncate the value, meaning the decimals are cut off.

What's The Biggest Number I Can Store?

Java has a limit for how big integers can be due to how they are stored as bits of memory. ints are stored as 4 bytes of memory, meaning 32 bits. The highest value it can store is a 2147483647, which is also known as Integer.MAX_VALUE. There is also a minimum value it can store which is -2147483648, also known as Integer.MIN_VALUE. If you try to store a value beyond that range, you will get an Integer Overflow error. And that's it for Unit 1! I hope you learned a lot about programming in Java, because we're just getting started!

NOTE!

Due to how doubles are stored, you might get an error when doing double arithmetic. This is a well known problem of computers.

Integer Overflow

See what happens if you try to print an integer that's too big. Try to go over the minimum value.

This is the console.

Unit 1 Summary

Section 1

  • Programming Language: a language used to communicate instructions to a computer.
  • Object-Oriented Language: a type of programming language that is designed around objects.
  • Class: a blueprint for making objects as well as the place where you write your code.
  • Main Method: a method that is automatically called when the program starts
  • Statement: a line of code that performs a specific action.
  • Print Statement: a type of statement that prints a value into the console.
  • String Literal: a value made up of letters and other characters, surrounded by quotation marks.
  • Bug: an error usually caused by a mistake while programming.
  • Syntax Error: a bug caused by faulty syntax such as forgetting a semicolon or misspelling a keyword. Also known as a compilation error.
  • Compiler: a program that compiles your code before executing it.
  • Compile: to translate a higher level programming language into a lower level language so that the computer can understand.
  • Debugging: the process of finding and fixing bugs.
  • Comment: a piece of code that is not read by the compiler, usually meant for programmers to read.
Keywords and Example Code Snippets

public class Main {
    public static void main(String[] args) {

    }
}
                        

System.out.print("Hello");
System.out.println("World!");
                        

//This is a comment
/*
    This is also a comment
*/
                        

Question 1

Which of these lines of code will NOT produce a Syntax Error?

Section 2

  • Variable: a piece of code used to store data like numbers or words.
  • Data Type: the type of data that is being stored, such as int or String.
  • Primitive Variable: a variable that stores primitive types such as int, double, or boolean.
  • Reference Variable: a variable that stores reference types such as String or Array. Also known as an object.
  • Concatenation: Combining multiple strings together into one string.
  • Variable Declaration: Creating a variable by defining a type and a name.
  • Bit: 1s and 0s used to create data types.
  • Memory: an electronic part inside of the computer that holds bits and store data temporarily.
  • Camel Case: a popular naming convention used to keep variable names consistent. The first word is uncapitalized and every word after that is capitalized.
Keywords and Example Code Snippets

int number;
double decimal = 3.5;
boolean isTrue = true;
String sentence = "Hello" + "world!";
final double PI = 3.14159;
                        

Question 2

Which of these is NOT a primitive type?

Section 3

  • Operator: a symbol used in an expression to evaluate into a single value.
  • Assignment Operator: a symbol used to assign a value to a variable. It can also assign a new value to a variable that already has a value.
  • Expression: a piece of code that evaluates into a single value. Can be made up of smaller expressions and makes up a statement.
  • Compound Expression: multiple expressions within one expression. Will eventually evaluate to one value.
  • Operator Precedence: the order in which the expression evaluates. Starts with parentheses, then division or multiplication, and then addition or subtraction.
  • Arithmetic Exception: a bug that occurs due to an impossible mathematical operation, such as dividing by 0.
  • Modulo Operator: an operator that returns the remainder of an expression. Written using the % sign.
  • Equality Operator: an operator that checks if two values are equal and evaluates to true or false. Written using the == sign.
  • Not-Equals Operator: an operator that checks if two values are NOT equal and evaluates to true or false. Written using the != sign.
Keywords and Example Code Snippets

int x = 5;
x = 2 * 10 - 3; //Will evaluate to a single value before assigning
x = 6 / 0; //Produces an Arithmetic Exception error
int y = 23;
y = y % 2; //Evaluates and assigns itself to 1
y == 1; //Evaluates to true
y != 1; //Evaluates to false
                        

Question 3

What does this evaluate to: 3 % ((2 + 3) * 4 / 5)

Section 4

  • Compound Assignment Operators: shortcut operators used to quickly operate and assign a value at the same time.
  • Increment Operator: an operator that increases a variable's value by 1. Written using the ++ sign.
  • Decrement Operator: an operator that decreases a variable's value by 1. Written using the -- sign.
  • Code Tracing: a technique used by programmers to trace the path their code takes to find bugs.
Keywords and Example Code Snippets

x += 2; //Same as x = x + 2;
x -= 2; //Same as x = x - 2;
x *= 2; //Same as x = x * 2;
x /= 2; //Same as x = x / 2;
x %= 2; //Same as x = x % 2;
x++; //Same as x = x + 1;
x--; //Same as x = x - 1;
                        

Question 4

Which of these is the same as x += x + 2;

Section 5

  • Type Casting: an operation that converts a value's data type into a different type.
  • Integer Overflow: a bug caused by storing an int value that is too large (or too small) for the computer's memory to handle.
Keywords and Example Code Snippets

int x = 2;
x += (int) 2.5; //Will truncate 2.5 to 2 and add it to x
double y = (double) 3 / 2; //Evaluates to 1.5
x = Integer.MAX_VALUE + 1; //Will produce an integer overflow error
                        

Question 5

Which of these will evaluate to 3.5