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!.
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.
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!");
}
}
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!
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.
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 {}
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.
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();
print() will print only what is inputted, but println() will print a new line after printing the input.
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.
Try to get the program to print "Hello world!" into the console.
This is the console.
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.
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.
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.
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.
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;
Do not reassign a new value to a final variable! It will produce an error.
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.
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.
Try to print out an equality operation between an integer and a double of the same value.
This is the console.
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;
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.
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.
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
Converting doubles to ints will truncate the value, meaning the decimals are cut off.
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!
Due to how doubles are stored, you might get an error when doing double arithmetic. This is a well known problem of computers.
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.
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
*/
Which of these lines of code will NOT produce a Syntax Error?
int number;
double decimal = 3.5;
boolean isTrue = true;
String sentence = "Hello" + "world!";
final double PI = 3.14159;
Which of these is NOT a primitive type?
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
What does this evaluate to: 3 % ((2 + 3) * 4 / 5)
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;
Which of these is the same as x += x + 2;
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
Which of these will evaluate to 3.5