Learn to Code via Tutorials on Repl.it!

← Back to all posts
How to code Java (Basics) ( 300 Cycle Special! )
studentAlfredAl (431)

Java Tutorial (Basics) Understanding and coding Java

Hey guys! In this tutorial, I'll be going over most of the basics of Java and most of what I have learned. At the end there is some extra stuff that’s not in the basics, but useful stuff that I was able to learn from Stack Overflow. I know this is really long, but hang in there. Feel free to give me feedback in the comments!

Class

You cannot write any program in Java without having a class. In Repl.it when you make a new repl in Java, your class is already printed there for you. It looks something like this: public class Main {}. It will look different when you start up a new Repl because there will be code inside the curly braces. Also, note that the word class, isn’t capitalized. It is very important that you keep this in mind, otherwise your program will return an error.

Curly Braces

One of the most important parts of Java that allow your code to run is curly braces. Curly braces are the outline of the code you are running; everything inside of them belongs to the function, class, or method you are running.

Indentation

Indentation is one of the main things you need to check over to make sure that your code works the way you want it to. For example, when you open up a new repl, notice the lines that appear. All the code that is to the right of the first gray line belongs to the main class because of the curly braces. Everything right of the second gray line still belongs to the main class, but first does any commands that belong to the public static void main curly braces.

Main Method

You'll notice that on the next line of code, it says public static void main(String[] args) {}. This is basically the main method showing that you can access the code file anywhere.
The most important part that you need to remember when typing this is that after this part [], there needs to be a space. Then you can type in args. It is also very important to not capitalize any of the words in that line except for the word String.
Note: There is a way to make it private, but I’m not sure about how to do it exactly and if it would work on Repl.it

Comments

Comments do not affect your code at all. They are just there so you can annotate your code without making any real changes to it. To type in single-line comments, simply do this:

//This is a comment

To type in multiple line comments, do this:

/*This
is
also
a comment */

Print Statements

To print something in Java, you can just type in System.out.println("Hello world!");
This tells the system to output whatever is inside the parenthesis. Inside the parenthesis, it is very important to use double quotes, unless you're typing in a variable, which we'll get to later.

Terminal

In case you are new to coding and are not familiar with terms, the place where your code is outputted is called the Terminal.

Semicolons

Semicolons are also one of the most important parts of Java. You need to place a semicolon after every function or statement that you use otherwise your code won't run. Comments don't count.

Variable Types

Functions are pieces of data that are called and can store values.
Some data types are:

  • int (stores integers)
  • double (stores integers with decimal values)
  • String (stores text)
  • boolean (true or false statements)

How to make variables:

To make variables, you need to name them. The way to name a variable is usually for the purpose that it is created for. You can have numbers in the variable name, but they can’t be the first character in the name. If you would like to have more than one word in the name of your variable, the first word is all lowercase. If your variable name isn't more than two words, then it should be in all lowercase. Here are some examples:

class Main {
   public static void main(String[] args) {
   
   System.out.println("Hello world!"); //This is a comment
   String myName = "Chicken Alfredo";
   String hello = "Hello, ";
   String world = "World! ";
   int one1 = 1;
   double two2 = 2;
   boolean playAgain = true;
  }
}

When you set the value of each variable, make sure you use the correct type of value, otherwise, you will get an error. For example, if you try to type words into a variable classified as an integer (int slices = "8 slices of pizza."), it would return an error, because you can't store text in a number value. #### Once you declare variables the first time, you don’t need to make them again. Just type in the name of the variable, but not the type, whenever you want to do something with it later on in the code.

Arithmetic Operators ( Math Operators )

Inside the variable you create, you can do anything that involves math with them. If you want to add numbers or something, use the + between them. To multiply use this: *. To divide use this (only one): /, and to subtract, do this: -. A special operator, which is called the modulus, looks like this: %. The modulus gives the remainder of something that you divide. For example, if I coded int myNumber = 5 % 2; and printed it, I would see the number 1, because that is the remainder. The ++ operator increases the value of a variable by 1, and the -- decreases the value of a variable by 1. If you use the += or -= operators, you can add or subtract any value you want from the variable. For example:

int myAge=15;
myAge++1;
myAge--1;
myAge+=4;
myAge-=4;

Concatenation

If you want to print several things together on the same print line, just add a + between each part. But if you're doing strings and regular variables, you need to place the + after the quotation marks. All examples:

class Main {
   public static void main(String[] args) {
   
   System.out.println("Hello world!");
   //This is a comment
   String myName = "Chicken Alfredo";
   String hello = "Hello, ";
   String world = "World! ";
   int one = 1;
   double two = 2;
   boolean playAgain = true;
   System.out.println(hello + " world! My name is " + myName + ". " + one + two);
   }
}

This would output:
Hello World!
Hello, world! My name is Chicken Alfredo. 12

Creating Scanners

If you would like to take in user input, you need to import a Scanner. This is easy to do, but you must place all imports before the class. After you import the Scanner, you need to create one. Here is how to do it:

import java.util.Scanner; //Yes, you need a semicolon at the end of all imports
class Main {
     public static void main(String[] args) {
	Scanner key = new Scanner(System.in); //You can name your scanner whatever you want (keyboard, input, etc.)
   }
}

Taking in User Input

To take in user input after asking a question, there are several ways depending on the type of variable that is being entered. I will print out an example of what the code will look like, then break it down:

Import java.util.Scanner;
class Main{
     public static void main(String[] args {
	Scanner key=new Scanner(System.in);
	System.out.println(“What is your name? ”);
	String yourName = key.nextLine();
     }
}

The key.nextLine() tells the program that the next line (until the user presses Enter), is what will be stored in the variable yourName. Naturally, for each type of variable, you will have different ways to read in the user input. For example if you asked how old the user was, you would have to do: int age = key.nextInt(). Or if you asked them how much money they have: double money = key.nextDouble().

Logical Operators

There are 3 logical operators in Java. The ‘and’ operator, the ‘or’ operator, and the ‘not’ operator. The ‘and’ operator is represented by this: &&; This is the ‘or’ operator: ||. And this is the ‘not’ operator: !. These logical operators are mostly used in conditional statements (next section), so advanced Java coders don’t always use logical operators in conditional statements.

Conditional Statements ( If / Else if / else )

If and else if statements are similar to booleans, except that they are conditional statements, and they will only run the code inside of them if the condition is true. In a typical if statement, you will see something like this: if (userGuess==secretNumber). Inside the parenthesis is the condition. When you are comparing two values to see if the condition is true or false, you need to use two equal signs if it’s a number. For strings, there are two ways to compare the strings. You can do this if (yourName.equalsIgnoreCase(“Jeff”)). The .equalsIgnoreCase() is the ultimate way to make sure if the user’s answer (only text), is the same, or not the same, no matter the capitalization. Inside the parentheses at the end of the .equalsIgnoreCase()<-, you need to enter text in quotation marks or the name of a String variable. When you are trying to make the condition to do something as long as the number/string does not equal another number/string, then you need to use the ‘not’ operator. The placement of the exclamation mark is also important. If you are dealing with numbers, you need to put the exclamation mark after the variable name but before the equal sign: if (money!=0). If you are doing it with strings, you need to do the same thing with the exclamation mark as you did with the numbers, but you also need to remember to put the quotation marks if you are typing in text. You don’t need to do that if you are putting in the name of a variable: if (bank!=“none”). If you use the .equalsIgnoreString() way, then here’s another example: if (!bank.equalsIgnoreCase(“none”)). When you use else if statements, you need to put them after if statements, and only because the if statement is false but you would like to add another condition. When you use the else statement, you only put that if all the conditional statements you put are going to be false. Let me give you an example:

if (age<=17 && age>=0)
	System.out.println(“You are underage.”);
else if (age>=18)
	System.out.println(“You are overage.”);
else
	System.out.println(“You are a fetus.”);

(I know the example is really bad) Another important thing to keep in mind while doing conditional statements is that if the code that belongs to them is more than one line long, you need to add curly braces, and everything indented inside the curly braces is what happens if the conditional statement is true/false. For example:

if (age<=17 && age>=17)
{
     System.out.println(“You are underage.”);
     System.out.println(“It is truly amazing that you have stuck with this tutorial because of how long it is”);
}
else
{
     System.out.println(“You are overage”);
     System.out.println(“I am glad you are trying to learn Java. Since you have to read a lot in your classes, I don’t think this will tutorial will be as bad for you (but still pretty bad) ”);
}     

If you would like to set two or more conditions, then you would need to use the logical operators.

For Loops

There are three parts to a for loop (four if you are counting the parenthesis). An example of a for loop would look like this: for (int a=0; a<=10; a++). In the first part of the for loop (int a=0;), we are declaring the variable. It must be an integer. In the next part, it says that as long as a is less than or equal to 10, the for loop will run. The last part increases the value of a by one every time the code in the for loop is run. In this section, you can set the condition of the variable to be greater or less than or just equal to a value. In the next line of code, put in curly braces, and put your code after that (Don’t forget to indent). Once again, this code will run as long as the second part of the condition is true.

While Loops

A while loop looks the same as the if / elif / else statements, with the only differences being that the word is while, and that it will keep running until the condition is met. The most common example of a while loop is this: while (playAgain==true) {}. This would mean all the code put in the curly braces of the while loop would keep running as long as the boolean playAgain is false. You can put multiple conditional statements inside a while loop, and you can even put conditional statements inside other conditional statements. Here is an example of a while loop (obviously not going to display all the code here):

boolean playAgain=true;
while (playAgain==true)
{
     System.out.println(“Would you like to play again (y/n) ?”);
     String choice=key.nextLine();
     if (choice.equalsIgnoreCase(“y”))
	playAgain=true;
     else
	playAgain=false;
}

Extras:

Generating randoms

In order to generate random numbers, you need to first declare the name and the type of variable you are using (ex: int secretNumber =). After that you enter the type of variable in parenthesis, so it would start to look like this: int secretNumber = (int). Now you are ready for the last part: int secretNumber = (int)(Math.random() * 50 + 1); Math.random is helping to create something random, and the int I put in parenthesis earlier tells it what type of random variable to make. The 50 tells the program the maximum value the random int can be, while the one shows the lowest value the random int can be. You can generate random doubles or integers, but as far as I know, that’s it. You can’t generate Strings, and definitely not booleans.

Clearing the terminal

If it’s possible for you to memorize this code, then great! I don’t really understand how the arrangement of the characters work. I recommend creating a repl to clear the terminal and place this code there, so you don’t need to keep coming back here or to another website. Here is the code to clear the terminal:

   System.out.print("\033[H\033[2J"); 
   System.out.flush();

Changing the color of text you output

So this one is actually pretty special because you have to play around with the numbers (31m to 33m, etc.) in order to change the color of the text, make it bold or underlined, etc. Make sure before each color you have the \033[31m part.
Here are some different ways to print unique colors, and 2 text effects:

   System.out.println("\033[31;1mHello\033[0m, \033[32;1;2mworld!\033[0m");
   System.out.println("\033[31mRed\033[32m, Green\033[33m, Yellow\033[34m, Blue\033[0m");

Congratulations on reading to the end of this tutorial (maybe)! I hope this tutorial helped you to learn Java and be able to understand it better. Please give me feedback in the comments, and if you have any questions, please leave them in the comments as well. I hope you enjoyed (and stayed awake lol) and don’t forget to stay safe! :)

Also, for the repl below, yes you can enter a negative number for your age if you want :)

Commentshotnewtop
CodingCactus (3009)

you made a tutorial a cycle special???

ok.....

CodingCactus (3009)

also, it is a nice tutorial, I don't code in java, but it seems to have covered most things