An Introduction to Java
Java Tutorial for Beginners
This is a very fast tour of some basic Java
. You should type everything in to a Java repl, and try changing values to see what happens.
You should know how to program in other languages - I'm assuming knowledge of a language like Python or JavaScript.
Basics
Java is OOP (Object-Oriented Programming) so everything must be in a class. The Java compiler will automatically run any code in the main
method.
class Main { public static void main(String[] args) { // This is a comment // This will be run } }
In Java, blocks are defined with curly braces {}
- indentation is not necessary, but improves readability. All lines in Java must end with either ;
, or }
(where appropriate).
You can print stuff to the screen using System.out.println
.
class Main { public static void main(String[] args) { System.out.println("Hello, world!"); // => 'Hello, World!' } }
Mathematical operators are as follows:
class Main { public static void main(String[] args) { System.out.println(2+3); // addition System.out.println(2-3); //subtraction System.out.println(2*3); // multiplication System.out.println(2/3); // division - rounds down System.out.println(3%2); // modulus - remainder of division } }
Variables and Datatypes
When declaring a variable in Java, use the suntax variable_type variable_name;
. This declares an empty variable
class Main { public static void main(String[] args) { int num; num = 3; System.out.println(num); // Or, on one line int another_num = 3; System.out.println(another_num); } }
There are a few datatypes - here are the most common:
class Main { public static void main(String[] args) { // integers up to 2,147,483,647 int i = 3; // integers up to 9,223,372,036,854,775,807 long l = 314159265; // 64-bit floating-point number double d = 3.1415d; // 32-bit floating-point number (for saving memory) float f = 3.14f; // text String s = "Hello, World!"; // single character char c = 'a'; // true/false boolean b = false; } }
Arrays are when you assign multiple values to one variable name, e.g. x = {1,2,3}
. The syntax is type[] name = new type[length];
class Main { public static void main(String[] args) { // integer array of length 10 int[] i = new int[10]; // access elements with 0-based index, i.e. first element is 0, second is 1 e.t.c. i[0] = 1; i[6] = 32; // another way of defining arrays int[] i2 = {1,2,3}; // use .length to find the length of the array System.out.println(i.length); System.out.println(i2.length); } }
The String
datatype is basically an array of char
s.
class Main { public static void main(String[] args) { char[] c = {'H','e','l','l','o'}; String s = new String(c); System.out.println(s); // .length() is used to find the length of a String System.out.println(s.length()); } }
For an array with variable length, you can use an ArrayList
import java.util.ArrayList; class Main { public static void main(String[] args) { ArrayList al = new ArrayList(); al.add('a'); al.add(3); al.add("Hi there!"); // pushes to 0 index al.add(0,"First"); System.out.println(al); System.out.println(al.size()); // => 4 // remove removes by index, not value al.remove(0); System.out.println(al.size()); // => 3 // also, you can set it to only 1 datatype ArrayList<String> sal = new ArrayList<String>(); sal.add("Hi"); sal.add(34); // fails because it is not String } }
HashMaps
give each item a key
and a value
(also called Hashes, dicts or maps in other langs).
import java.util.HashMap; class Main { public static void main(String[] args) { // key is String, value is Integer // datatypes are different than normal // use Boolean, Character, Double for boolean,char,double HashMap<String, Integer> hm = new HashMap<String, Integer>(); hm.put("John",23); hm.put("Anne",17); System.out.println(hm); // use get to find a specific value System.out.println(hm.get("Anne")); hm.remove("Anne"); System.out.println(hm); } }
Control Flow
Comparison operators are used to compare things.
class Main { public static void main(String[] args) { System.out.println(1==1); // equal to System.out.println(2>1); // greater than System.out.println(2<1); // less than System.out.println(1>=1); // greater than or equal to System.out.println(2<=1); // less than or equal to System.out.println(2!=1); // not equal to } }
Logical operators are ways of choosing based on true
s and false
s.
class Main { public static void main(String[] args) { // AND - true if both are true System.out.println(true && true); // OR - true if either are true System.out.println(true || false); // NOT - swaps true with false and vice versa System.out.println(!true); // XOR - true if either are true but not both System.out.println(true^false); System.out.println(true^true); } }
If
statements do things depending on whether certain conditions are evaluated as true
or false
.
class Main { public static void main(String[] args) { // outputs "10 is greater than 5!" if (10>5) { System.out.println("10 is greater than 5!"); } else { System.out.println("10 is not greater than 5"); } int a = 10; // outputs "a is greater than 8" if (a<2) { System.out.println("a is less than 2"); } else if (a<8) { System.out.println("a is less than 8"); } else { System.out.println("a is greater than 8"); } } }
for
loops are used to loop a fixed number of times.
class Main { public static void main(String[] args) { // loops 10 times, incrementing i by 1 each time // (i++) for (int i=0;i<10;i++) { System.out.println(i); } char[] c_array = {'a','b','c','d'}; // loos for each item in the array for (char c:c_array) { System.out.println(c); } } }
while
loops continue looping until a certain criteria is met.
class Main { public static void main(String[] args) { int x = 3; // continues until x=6 // because then 6*4 == 24 while ((x*4)!=24) { System.out.println(x); x++; } } }
Classes and Methods
Methods are another name for functions inside classes.
class Main { public static void main(String[] args) { sayHello(); String farewell = sayGoodbye(); System.out.println(farewell); System.out.println("3 is greater than 5: "+isGreaterThanFive(3)); System.out.println("10 is greater than 5: "+isGreaterThanFive(10)); } // public and static will be covered in a minute // void means the method doesn't return anything public static void sayHello() { System.out.println("Hello!"); } // String means that the method returns a String public static String sayGoodbye() { return "Goodbye!"; } // boolean so returns true/false public static boolean isGreaterThanFive(int n) { return (n>5); } }
A class
is like a blueprint, with which you can make objects
(instances
).
class Main { public static void main(String[] args) { // create a new 'instance' of the dog class, called George Dog George = new Dog("George"); George.bark(); George.live(); George.eat(); // fails because eat() is private } } class Dog { // this is an attribute that all // of our Dog objects will have String name; // this is called the constructor // it is called when the dog is created public Dog(String name) { // this. means that name applies the this dog // it means that it's name can be used elsewhere // in the class this.name = name; System.out.println("A dog called "+this.name+" was just created!"); } // public means that it can be accessed by other classes public void bark() { System.out.println(this.name+" just said 'Woof!'"); } public void live() { this.eat(); } // private so cannot be accessed by other classes private void eat() { System.out.println(this.name+" is eating!"); } }
static
methods can be referenced from a static setting.
class Main { public static void main(String[] args) { // create a new instance of the Shop class Shop Amazon = new Shop(); Amazon.buy(); // static, so we can just do this Shop.buy(); Amazon.showDetails(); // fails because it is not an instance // and the method is not static Shop.showDetails(); } } class Shop { // static so don't need to instantiate in order to // use the method public static void buy() { System.out.println("Buying!"); } public void showDetails() { System.out.println("You have to create a instance for this to work"); } }
Input
The Scanner
class is used to scan text.
import java.util.Scanner; import java.io.File; class Main { public static void main(String[] args) { // creates a new Scanner looking at the string "Hello World" Scanner input_reader = new Scanner("Hello World"); // outputs each word one at a time while (input_reader.hasNext()) { String input = input_reader.next(); System.out.println(input); } } }
You can use the Scanner
class to read input from the keyboard.
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner input_reader = new Scanner(System.in); System.out.println("Enter some text: "); String input = input_reader.nextLine(); System.out.println("You said: "+input); } }
Error Handling
You can handle errors with try..catch
import java.lang.ArithmeticException; class Main { public static void main(String[] args) { try { System.out.println(1/0); } catch (ArithmeticException e) { System.out.println("Got error: "+e); } } }
Conclusion
That was a quick look over some basic Java. You may want to re-read this to make sure you understand it all.
Please upvote if you liked this tutorial, it helps support me :)
Suggested further topics:
- File reading/writing (may not work on repl.it)
- Inner Classes
- Inheritance
- Interfaces
- Packages
I'm overjoyed because this is great https://happywheelsunblocked.io
How do I create unit tests to test the program?
@LuSiWu Replit has test functionalities built in! See this post.
It talks mainly about Python, but Java works too.
How to do shapes
@Tytycoolit to do graphics, you'll want to use the Swing library. You can create a Swing repl here: https://repl.it/languages/java_swing
There are online tutorials for getting started, just search for 'Java Swing Tutorial' on your favourite search engine.
Hope this helps!
Just one question though: what does the public static things do at the beginning of a java file? I have never understood that
@DepthStrider When you run a Java program it will always start by running Main.main()
, passing in any command line arguments. It does this automatically.
e.g. if your file is called test.java
then running java test.java hello there
will result in args
being an array {"hello","there"}
.
Since Main.main
must be accessed outside the class, you have to declare it public
.
Since Main.main
is accessed through the class rather than the object, it must be declared static
.
// if Main.main is static, then to call it: Main.main() // if Main.main is non-static, then to call it: Main a = new Main(); a.main(/* args */);
Since the Java environment expects to be able to call Main.main()
the first way, it has to be declared static.
Ask if there's anything here you don't understand :)
okay. let me think through that.
10 hours later
so when a java file says something like "public static main" that is like the start of the program and the stuff in the parentheses are the arguments?
Also, what would the public static string" or "public static void" or "public static int" do? are those variable types and what do they represent?
@DepthStrider Haha yes
@DepthStrider Those are the return types of the method, so for example if you had a class like this:
class Calculator { public static int add(int a, int b) { return a + b; } }
the add
method returns an integer, so it is declared with a int
at the start. If you tried to return a string like this:
class Calculator { public static int add(int a, int b) { return "mwahaha this is a String not an int"; } }
then it would fail at compile time (before it runs the program) because the method is declared to return an int
but it is actually returning a String
.
This might seem like a limitation, but it is very helpful in catching errors in your code before you run the program.
void
just means it doesn't return anything.
While you could potentially return something that isn't void
from the main
method, it wouldn't be of much use since when you reach the end of the main
method the program stops anyway, so any value you return would just be discarded immediately. So if you try changing main
to something else like public static int
, the compiler will complain at you.
@ArchieMaclean OMG Thank you so much! That is sooooooo helpful! :) :) :)
@DepthStrider If you would like a pretty comprehensive Java tutorial in video form, Derek Banas did a video here: https://www.youtube.com/watch?v=n-xAqcBCws4
@ArchieMaclean Thank you! :)
THANK YOU SO MUCH!!!!!!! I love coding and I think Java is a very versatile language to learn. It also seems so similar to languages like python and javascript, which I know already, so I can't wait to start making stuff with this!
cool!!!
I am having trouble getting JAVA files to compile. Below, I have pasted some sample code I got from a website. I get an error message: "error: class Factorial is public, should be declared in a file named Factorial.java"
The name of my file is Factorial.java, so I'm not sure what the problem is. I would appreciate any insight :)
public class Factorial
{
public static void main(String[] args)
{ final int NUM_FACTS = 100;
for(int i = 0; i < NUM_FACTS; i++)
System.out.println( i + "! is " + factorial(i));
}
public static int factorial(int n) { int result = 1; for(int i = 2; i <= n; i++) result *= i; return result; }
}
@dtnichol Can you give a link to the repl? Thanks.
@dtnichol @ArchieMaclean Sorry for the late reply. You have to change the name of the method to 'Main' since your class is named 'Main.java'. It's a little perk on Repl.it - you have to get used to it.
How do we add a real class in addition to main class? I only seem to add files, not classes.
@AllyLi Can you give me a link to the repl? You should be able to add new classes by just writing out the new class in the same file.
????
Cool!