Java Basics

Program Structure

Every program in Java is written as a Class. We’ll learn more about this much later in the course. For now, just use the defaults provided by the IDE.

But the one thing we should be aware of now is…

The main method

Java will always start running in the main method! All of your programs will need this in order to run.

public class Main {

   public static void main(String[] args) {

      // Put your code here!

   }

}


In Java every open curly brace { must have a matched close curly brace }. These are used to start and end a block of code.

Printing in Java

You can print in a few ways, but I’ll show you two:

System.out.println(value)

System.out.print(value)

public class Main {

   public static void main(String[] args) {

      System.out.print("beep");

      System.out.println("boop");

      System.out.println("click clack moo cows that type");

   }

}

beepboop

click clack moo cows that type

Debugging

Syntax errors

These are the types of errors that will prevent your code from running at all. Syntax errors occur because your code doesn’t follow the “grammar rules” of Java.

Some very common, basic errors in Java include:

When you experience an error in your program, Java will try to help you fix it! The compiler will give you an error message.

Commenting

Comments are little notes in your code. They won’t actually affect the code or how it is run. In fact, the compiler will just ignore comments all together! But they are still a good idea to include so that you or other programmers can understand what’s going on in your code.

// is used to mark the beginning of a single-line comment.

/* is used to start a multi-line comment. The comment will end with a */

The header comment that should start all of your files should include:

For example:

// Example Program

// An example header comment

// Written by Ms. Fisher

// Last updated: Feb 4, 2024

Data Types

There are two types of data in Java: primitive types and objects.

Primitive Types

Type

What is it?

Example

int

Signed, whole numbers

-100, 75

double

Signed, decimal numbers

-0.123, 3.14

char

Single character, surrounded by single quotations

'h', 'i', '\n', '='

boolean

True or false

true, false

There are other primitive types, but these are the ones you will use most often in this course.

Objects

Type

What is it?

Example

String

A sequence of chars, surrounded by double quotations

"hello", "world"

Type

What is it?

Example

System

The standard input and output stream

The thing you use to print to the console

Again, there are many more, but these are the ones that you will need at this stage of the course.

Declaring variables

To declare a variable, you must tell Java its data type and its name. For example:

int score;

After declaring a variable, you can give it a value using an equals sign = followed by the value. For example:

int score;

score = 4;

Or instead, you can set an initial value for the variable when you create it! For example:

int score = 4;

Another example with an Object:

String myName = "Ms. Fisher";

public class Main {

   public static void main(String[] args) {

      String myExample = "im declaring a string";

      System.out.println("myExample");

      System.out.println(myExample);

   }

}

myExample

im declaring a string

Naming variables

While you can name your variable almost anything, there are some rules and some guidelines.

Rules for naming variables:

A variable name…

  1. Must start with a letter
  2. Must only include alphanumeric characters and underscores (No spaces!!)
  3. Cannot use any keywords or reserved words in Java (e.g. print, main, int, double, etc.)
  4. Is case-sensitive and spelling sensitive (e.g. foo, FOO)

Guidelines for naming variables:

Why is it called camelCase?

Basic math operations

Operation

Symbol

Example

Addition

+

3 + 2

Subtraction

-

3 - 2

Multiplication

*

3 * 2

Operation

Symbol

Example

Division

/

3 / 2

Modulus

%

3 % 2

int x = 10;

int y = 5;

System.out.println(x+y);

System.out.println(x-y);

System.out.println(x*y);

System.out.println(x/y);

System.out.println(x%y);

// We don't need variables to do math

// But does Java know BEDMAS?

System.out.println(5+10*(2+1));

15

5

50

2

0

35

Tricky division

int a = 8;

int b = 10;

System.out.println(a/b); // Division of only integers

int c = 8;

double d = 10;

System.out.println(c/d); // Division with a double

0

0.8

NOTE: Java will try to guess what type of data the answer to a math problem is. If only integers are involved, Java will give an integer answer. Java will always round down in these cases.

Modulus operator

The modulus operator (%) is also known as the remainder operator. It returns the remainder after you divide the first number by the second. Remember long division?

System.out.println(10%2);

System.out.println(11%2);

int a = 27;

int b = 3;

System.out.println(a/b%b);

0

1

0


There are a lot of uses for the modulus operator, but one common one is testing if a number is even or odd!

Math class

Java has some basic math operations built in, but for more complicated ones, we need to use the Math Class. You can think of it as a collection of extra things that Java knows how to do already.

Operation

Method

Example

Exponents

Math.pow(x,y)

Math.pow(3,2)

Square Root

Math.sqrt(x)

Math.sqrt(64)

Rounding

Math.round(x)

Math.sqrt(2.6)

public class Main {

   public static void main(String[] args) {

      int x = 4;

      System.out.println(Math.pow(x,2));

      System.out.println(Math.sqrt(x));

      System.out.println(Math.round(10.1));

      System.out.println(Math.round(10.8));

      // Pay attention to what data types are returned!

   }

}

16.0

2.0

10

11

Assignment operators

Compound assignment operators are shortcuts that do a math operation and assignment in one step. For example, the following blocks of code do the exact same thing:

int x = 5;

x = x + 1;

This will take what was inside x and then add 1 to it.

int x = 5;

x += 1;

This also adds 1 to whatever was inside of x.

Each column means the same thing in Java

+

-

*

/

%

x = x + 1

x = x - 1

x = x * 2

x = x / 2

x = x % 2

x += 1

x -= 1

x *= 2

x /= 2

x %= 2

x++

x--

int score = 0;

System.out.println(score);

score++;

System.out.println(score);

score *= 2;

System.out.println(score);

int penalty = 5;

score -= penalty/2;

System.out.println(score);

0

1

2

0