Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
31 views

Introduction To Java

- Java is a popular programming language released in 1995 that is known for being simple, portable, secure, and robust. - Java code can run on any device because it is compiled to bytecode that runs on a Java Virtual Machine, rather than being platform-specific. - Programmers write Java code in .java files using syntax like classes, methods, and print statements, which are then compiled into executable .class files.

Uploaded by

allieashika
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Introduction To Java

- Java is a popular programming language released in 1995 that is known for being simple, portable, secure, and robust. - Java code can run on any device because it is compiled to bytecode that runs on a Java Virtual Machine, rather than being platform-specific. - Programmers write Java code in .java files using syntax like classes, methods, and print statements, which are then compiled into executable .class files.

Uploaded by

allieashika
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Introduction to Java

Welcome to the world of Java programming!

Programming languages enable humans to write instructions that a computer can perform.
With precise instructions, computers coordinate applications and systems that run the modern
world.

Sun Microsystems released the Java programming language in 1995. Java is known for being
simple, portable, secure, and robust. Though it was released over twenty years ago, Java
remains one of the most popular programming languages today.

One reason people love Java is the Java Virtual Machine, which ensures the same Java code
can be run on different operating systems and platforms. Sun Microsystems’ slogan for Java
was “write once, run everywhere”.

Programming languages are composed of syntax, the specific instructions which Java
understands. We write syntax in files to create programs, which are executed by the computer
to perform the desired task.

Let’s start with the universal greeting for a programming language. We’ll explore the syntax
in the next exercise.

Java runs on different platforms, but programmers write it the same way. Let’s explore some
rules for writing Java.

In the last exercise, we saw the file HelloWorld.java. Java files have a .java extension.
Some programs are one file, others are hundreds of files!
Inside HelloWorld.java, we had a class:

public class HelloWorld {

We’ll talk about classes more in the future, but for now think of them as a single concept.

The HelloWorld concept is: Hello World Printer. Other class concepts could be: Bicycle, or:
Savings Account.

We marked the domain of this concept using curly braces: {}. Syntax inside the curly braces
is part of the class.

Each file has one primary class named after the file. Our class name: HelloWorld and our file
name: HelloWorld. Every word is capitalized.

Inside the class we had a main() method which lists our program tasks:

public static void main(String[] args) {

Like classes, we used curly braces to mark the beginning and end of a method.

public, static, and void are syntax we’ll learn about in future lessons. String[] args is a
placeholder for information we want to pass into our program. This syntax is necessary for
the program to run but more advanced than we need to explore at the moment.

Our program also displayed the text "Hello World" on the screen. This was accomplished
using a print statement:

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

We’ll learn more about print statements in the next exercise!

Print Statements

Let’s take a closer look at this instruction from our previous program:

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

Print statements output information to the screen (also referred to as the output terminal).
Let’s break this line of code down a little more. Don’t worry if some of the terms here are
new to you. We’ll dive into what all of these are in much more detail later on!

 System is a built-in Java class that contains useful tools for our programs.
 out is short for “output”.
 println is short for “print line”.
We can use System.out.println() whenever we want the program to create a new line on the
screen after outputting a value:

System.out.println("Hello World");
System.out.println("Today is a great day to code!");

After "Hello World" is printed, the output terminal creates a new line for the next statement
to be outputted. This program will print each statement on a new line like so:

Hello World
Today is a great day to code!

We also can output information using System.out.print(). Notice that we’re using print(), not
println(). Unlike System.out.println(), this type of print statement outputs everything on the
same line. For example:

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

The above code will have the following output:

Hello World

In this example, if you were to use print() or println() again, the new text will print
immediately after World on the same line. It’s important to remember where you left your
program’s “cursor”. If you use println() the cursor is moved to the next line. If you use print()
the cursor stays on the same line.

Note: Going forward, all exercises will use System.out.println() to output values.

Commenting Code

Writing code is an exciting process of instructing the computer to complete fantastic tasks.

Code is also read by people, and we want our intentions to be clear to humans just like we
want our instructions to be clear to the computer.

Fortunately, we’re not limited to writing syntax that performs a task. We can also write
comments, notes to human readers of our code. These comments are not executed, so there’s
no need for valid syntax within a comment.

When comments are short we use the single-line syntax: //.

// calculate customer satisfaction rating

When comments are long we use the multi-line syntax: /* and */.

/*
We chose to store information across multiple databases to
minimize the possibility of data loss. We'll need to be careful
to make sure it does not go out of sync!
*/

Another type of commenting option is the Javadoc comment which is represented by /** and
*/. Javadoc comments are used to create documentation for APIs (Application Programming
Interfaces). When writing Javadoc comments, remember that they will eventually be used in
the documentation that your users might read, so make sure to be especially thoughtful when
writing these comments.

Javadoc comments are typically written before the declaration of fields, methods, and classes
(which we’ll cover later in this course):

/**
* The following class accomplishes the following task...
*/

Here’s how a comment would look in a complete program:

/**
* The following class shows what a comment would look like in a program.
*/
public class CommentExample {
// I'm a comment inside the class
public static void main(String[] args) {
// I'm a comment inside a method
System.out.println("This program has comments!");
}
}

Comments are different from printing to the screen, when we use System.out.println(). These
comments won’t show up in our terminal, they’re only for people who read our code in the
text editor.

public class Timeline {


public static void main(String[] args) {
System.out.println("Hello Java!");

System.out.println("You were born in 1995");

//Sun Microsystems announced the release of Java in 1995

System.out.println("You were created by James Gosling");

/* James Gosling is a Canadian engineer who


created Java while working at Sun Microsystems.
His favorite number is the square root of 2!*/
System.out.println("You are a fun language!");
}
}
Semicolons and Whitespace

As we saw with comments, reading code is just as important as writing code.

We should write code that is easy for other people to read. Those people can be co-workers,
friends, or even yourself!

Java does not interpret whitespace, the areas of the code without syntax, but humans use
whitespace to read code without difficulty.

Functionally, these two code samples are identical:

System.out.println("Java");System.out.println("Lava");System.out.println("Guava");
System.out.println("Java");

System.out.println("Lava");

System.out.println("Guava");

They will print the same text to the screen, but which would you prefer to read? Imagine if it
was hundreds of instructions! Whitespace would be essential.

Java does interpret semicolons. Semicolons are used to mark the end of a statement, one line
of code that performs a single task.

The only statements we’ve seen so far are System.out.println("My message!");.

Let’s contrast statements with the curly brace, {}. Curly braces mark the scope of our classes
and methods. There are no semicolons at the end of a curly brace.

public class LanguageFacts {


public static void main(String[] args) {
// Press enter or return on your keyboard after each semicolon!

System.out.println("Java is a class-based language.");System.out.println("Java classes have


a 'main' method.");System.out.println("Java statements end with a semicolon.");
}
}

Compilation: Catching Errors


Java is a compiled programming language, meaning the code we write in a .java file is
transformed into byte code by a compiler before it is executed by the Java Virtual Machine on
your computer.

A compiler is a program that translates human-friendly programming languages into other


programming languages that computers can execute.

Previous exercises have automatically compiled and run the files for you. Off-platform
development environments can also compile and run files for you, but it’s important to
understand this aspect of Java development so we’ll do it ourselves.

The compiling process catches mistakes before the computer runs our code.

The Java compiler runs a series of checks while it transforms the code. Code that does not
pass these checks will not be compiled.

This exercise will use an interactive terminal. Codecademy has a lesson on the command line
if you’d like to learn more.

For example, with a file called Plankton.java, we could compile it with the terminal
command:

javac Plankton.java

A successful compilation produces a .class file: Plankton.class, that we execute with the
terminal command:

java Plankton

An unsuccessful compilation produces a list of errors. No .class file is made until the errors
are corrected and the compile command is run again.
Compilation: Creating Executables

Compilation helped us catch an error. Now that we’ve corrected the file, let’s walk through a
successful compilation.

As a reminder, we can compile a .java file from the terminal with the command:

javac Whales.java

If the file compiles successfully, this command produces an executable class:


FileName.class. Executable means we can run this program from the terminal.

We run the executable with the command:

java Whales

Note that we leave off the .class part of the filename.

Here’s a full compilation cycle as an example:

// within the file: Welcome.java


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Codecademy's Java course!");
}
}

We have one file: Welcome.java. We compile with the command:

javac Welcome.java

The terminal shows no errors, which indicates a successful compilation.

We now have two files:


1. Welcome.java, our original file with Java syntax.
2. Welcome.class, our compiled file with Java bytecode, ready to be executed by the
Java Virtual Machine.

We can execute the compiled class with the command:

java Welcome

The following is printed to the screen:

Welcome to Codecademy's Java course!


Java Review: Putting It All Together

In this lesson, we’ve started writing our first programs in Java.

We’ve also learned rules and guidelines for how to write Java programs:

 Java programs have at least one class and one main() method.
o Each class represents one real-world idea.
o The main() method runs the tasks of the program.
 Java comments add helpful context to human readers.
 Java has whitespace, curly braces, and semicolons.
o Whitespace is for humans to read code easily.
o Curly braces mark the scope of a class and method.
o Semicolons mark the end of a statement.
 Java is a compiled language.
o Compiling catches mistakes in our code.
o Compilers transform code into an executable class.

1. public class Review {


2. public static void main(String[] args ) {
3. // the code comment
4. System.out.printIn( “Hello world!”);
5. }
6. }

Learn Java: Variables


Introduction

Let’s say we need a program that connects a user with new jobs. We need the user’s name,
their salary, and their employment status. All of these pieces of information are stored in our
program.

We store information in variables, named locations in memory.

Naming a piece of information allows us to use that name later, accessing the information we
stored.
Variables also give context and meaning to the data we’re storing. The value 42 could be
someone’s age, a weight in pounds, or the number of orders placed. With a name, we know
the value 42 is age, weightInPounds, or numOrdersPlaced.

In Java, we specify the type of information we’re storing. Primitive datatypes are types of
data built-in to the Java system. The three main primitive types we’ll cover are int, double,
and boolean; this lesson will introduce these built-in types and more.

We must declare a variable to reference it within our program. Declaring a variable requires
that we specify the type and name:

// datatype variableName
int age;
double salaryRequirement;
boolean isEmployed;

The names of the variables above are age, salaryRequirement, and isEmployed.

These variables don’t have any associated value. To assign a value to a variable, we use the
assignment operator =:

age = 85;

Now, age has a value of 85. When code is used to represent a fixed value, like 85, it is
referred to as a literal.

It’s also common to declare a variable and assign it a value in one line!

For example, to assign 2011 to a variable named yearCodecademyWasFounded of type int,


we write:

int yearCodecademyWasFounded = 2011;

INTS

The first type of data we will store is the whole number. Whole numbers are very common in
programming. You often see them used to store ages, or maximum sizes, or the number of
times some code has been run, among many other uses.

In Java, whole numbers are stored in the int primitive data type.

intshold positive numbers, negative numbers, and zero. They do not store fractions or
numbers with decimals in them.

The int data type allows values between -2,147,483,648 and 2,147,483,647, inclusive.

To declare a variable of type int, we use the int keyword before the variable name:

// int variable declaration


int yearJavaWasCreated;
// assignment
yearJavaWasCreated = 1996;
// declaration and assignment
int numberOfPrimitiveTypes = 8;

//This is the class declaration


public class CountComment {
//This is the main method that runs when you compile
public static void main(String[] args) {
//This is where you will define your variable
int numComments = 6;
//This is where you will print your variable
System.out.println(numComments);
}

//This is the end of the class


}

//This is outside the class

doubles

Whole numbers don’t accomplish what we need for every program. What if we wanted to
store the price of something? We need a decimal point. What if we wanted to store the
world’s population? That number would be larger than the int type can hold.

The double primitive data type can help. double can hold decimals as well as very large and
very small numbers. The maximum value is 1.797,693,134,862,315,7 E+308, which is
approximately 17 followed by 307 zeros. The minimum value is 4.9 E-324, which is 324
decimal places!

To declare a variable of type double, we use the double keyword in the declaration:

// doubles can have decimal places:


double price = 8.99;
// doubles can have values bigger than what an int could hold:
double gdp = 12237700000;

BOOLEANS

Often our programs face questions that can only be answered with yes or no.

Is the oven on? Is the light green? Did I eat breakfast?


These questions are answered with a boolean, a type that references one of two values: true
or false.

We declare boolean variables by using the keyword boolean before the variable name.

boolean javaIsACompiledLanguage = true;


boolean javaIsACupOfCoffee = false;

In future lessons, we’ll see how boolean values help navigate decisions in our programs.

CHAR

How do we answer questions like: What grade did you get on the test? What letter does your
name start with?

The char data type can hold any character, like a letter, space, or punctuation mark.

It must be surrounded by single quotes, '.

For example:

char grade = 'A';


char firstLetter = 'p';
char punctuation = '!';

STRING

So far, we have learned primitive data types, which are the simplest types of data with no
built-in behavior. Our programs will also use Strings, which are objects, instead of
primitives. Objects have built-in behavior.

Strings hold sequences of characters. We’ve already seen instances of a String, for
example, when we printed out "Hello World". There are two ways to create a String
object: using a String literal or calling the String class to create a new String object.

A String literal is any sequence of characters enclosed in double-quotes (""). Like primitive-
type variables, we declare a String variable by specifying the type first:

String greeting = "Hello World";

We could also create a new String object by calling the String class when declaring a
String like so:

String salutations = new String("Hello World");

There are subtle differences in behavior depending on whether you create a String using a
String literal or a new String object. We’ll dive into those later, but for now, we’ll almost
always be using String literals.
Keep Reading: AP Computer Science A Students

Certain symbols, known as escape sequences, have an alternative use in Java print statements.
Escape sequences are interpreted differently by the compiler than other characters. Escape
characters begin with the character \.

There are three escape sequences to be aware of for the AP exam.

The \" escape sequence allows us to add quotation marks " to a String value. :

System.out.println("\"Hello World\"");
// Prints: "Hello World"

If we didn’t use an escape sequence, then Java would think we’re using " to end the String!

Using the \\ escape sequence allows us to place backslashes in our String text:

System.out.println("This is the backslash symbol: \\");


// Prints: This is the backslash symbol: \

This is similar to the last example - just like ", \ usually has a special meaning. In this case, \
is used to start an escape sequence. Well, if we don’t want to start an escape sequence and
just want a \ in our String, then we’ll use \\ — we’re using an escape sequence to say that
we don’t want \ to be interpreted as the start of an escape sequence. It’s a little mind-
bending!

Finally, if we place a \n escape sequence in a String, the compiler will output a new line of
text:

System.out.println("Hello\nGoodbye");
/*
Prints:
Hello
Goodbye
*/

You can think of \n as the escape sequence for “newline”.

Static Checking

The Java programming language has static typing. Java programs will not compile if a
variable is assigned a value of an incorrect type. This is a bug, specifically a type declaration
bug.

Bugs are dangerous! They cause our code to crash, or produce incorrect results. Static typing
helps because bugs are caught during programming rather than during execution of the code.

The program will not compile if the declared type of the variable does not match the type of
the assigned value:

int greeting = "Hello World";


The String "Hello World" cannot be held in a variable of type int.

For the example above, we see an error in the console at compilation:

error: incompatible types: String cannot be converted to int


int greeting = "Hello World";

When bugs are not caught at compilation, they interrupt execution of the code by causing
runtime errors. The program will crash.

Java’s static typing helps programmers avoid runtime errors, and thus have much safer code
that is free from bugs.

NAMING

Let’s imagine we’re storing a user’s name for their profile. Which code example do you think
is better?

String data = "Delilah";

or

String nameOfUser = "Delilah";

While both of these will compile, the second example is way more easy to understand.
Readers of the code will know the purpose of the value: "Delilah".

Naming variables according to convention leads to clear, readable, and maintainable code.
When someone else, or our future self, reads the code, there is no confusion about the
purpose of a variable.
In Java, variable names are case-sensitive. myHeight is a different variable from myheight.
The length of a variable name is unlimited, but we should keep it concise while keeping the
meaning clear.

A variable starts with a valid letter, or a $, or a _. No other symbols or numbers can begin a
variable name. 1stPlace and *Gazer are not valid variable names.

Variable names of only one word are spelled in all lowercase letters. Variable names of more
than one word have the first letter lowercase while the beginning letter of each subsequent
word is capitalized. This style of capitalization is called camelCase.

// good style
boolean isHuman;

// bad styles
// no capitalization for new word
boolean ishuman;
// first word should be lowercase
boolean IsHuman;
// underscores don't separate words
boolean is_human;

public class BadNames {


public static void main(String[] args) {
String nameOfUser = "Samira";
String surnameOfuser = "Smith";
String domainOfuser = "samira@google.com";
int salaryexpectation = 100000;
int year_of_birth = 1955;

System.out.println("The program runs!");


}
}

REVIEW

Creating and filling variables is a powerful concept that allows us to keep track of all kinds of
data in our program.

In this lesson, we learned how to create and print several different data types in Java, which
you’ll use as you create bigger and more complex programs.

We covered:

 int, which stores whole numbers.


 double, which stores bigger whole numbers and decimal numbers.
 boolean, which stores true and false.
 char, which stores single characters using single quotes.
 String, which stores multiple characters using double quotes.
 Static typing, which is one of the safety features of Java.
 Variable naming conventions.

Practice declaring variables and assigning values to make sure you have a solid foundation
for learning more complicated and exciting Java concepts!

Introduction

Let’s say we are writing a program that represents a user’s bank account. With variables, we
know how to store a balance! We’d use a double, the primitive type that can hold big
decimal numbers. But how would we deposit and withdraw from the account?

Lucky for us, we have the ability to manipulate the value of our variables. We can use
expressions, arithmetic operators, and more in order to change our variables’ values.

For example, Java has built-in arithmetic operations that perform calculations on numeric
values:

// declare initial balance


double balance = 20000.99;
// declare deposit amount
double depositAmount = 1000.00;
// store result of calculation in our original variable
balance = balance + depositAmount;

In the final line of the code above, we used the expression balance + depositAmount to
determine the new value of the balance variable. When an expression is executed, it
produces a single value.
The data type of a variable plays a large role in the operations we can use to manipulate it.
We can think of a data type as a combination of a set of values, and a set of operations on
those values. For example, the double data type is comprised of values like 4.8 and
operations like addition (+). For now, we’ll mainly focus on the set of operations that can be
used on numbers and booleans.

The data type of an expression is determined by the resulting value. For example, an
expression that uses two int values will evaluate to an int value. If an expression contains a
double value, then the resulting value will also be type double.

Throughout this lesson, we will learn how to manipulate variables of different data types.

Addition and Subtraction

In our bank account example from the last exercise, we used the + operator to add the values
balance and depositAmount:

double balance = 20000.99;


double depositAmount = 1000.0;
balance = balance + depositAmount;
// balance now holds 21000.99

If we wanted to withdraw from the balance, we would use the - operator:

double withdrawAmount = 500;


balance = balance - withdrawAmount;
// balance now holds 19500.99

Addition and subtraction work with int type values as well! If we had 60 pictures of cats on
our phone, and we took 24 more, we could use the following line of code to store 84 in
numPicturesOfCats.

int numPicturesOfCats = 60 + 24;

What if we took one additional picture of our cat? We can reflect this change using an
increment operator ++. When we append ++ to a number-based variable, it increases the value
by 1. We also have the decrement operator, --, which decreases the value by 1.

// Take a picture
numPicturesOfCats++ // Value is now 85

// Delete a picture
numPicturesOfCats-- // Value is now 84

Instructions

1.

Create an int variable called animalsInZoo that holds the amount of zebras plus the amount
of giraffes at the zoo.
Then, print your animalsInZoo variable.

Checkpoint 2 Passed
2.

Two of the zebras have been traded to a neighboring rival zoo. Subtract 2 from the number of
zebras and store the result in a variable called numZebrasAfterTrade.

Then, print the numZebrasAfterTrade variable!

public class PlusAndMinus {


public static void main(String[] args) {
int zebrasInZoo = 8;
int giraffesInZoo = 4;
int animalsInZoo = zebrasInZoo + giraffesInZoo;
System.out.println(animalsInZoo);
int numZebrasTraded = 2;
int numZebrasAfterTrade = zebrasInZoo - numZebrasTraded;
System.out.println(numZebrasAfterTrade);
}
}

Multiplication and Division

Let’s say that our employer is calculating our paycheck and depositing it to our bank account.
We worked 40 hours last week, at a rate of $15.50 an hour. Java can calculate this with the
multiplication operator *:

double paycheckAmount = 40 * 15.50;


//paycheckAmount now holds 620.0

If we want to see how many hours our total balance represents, we use the division operator
/:

double balance = 20010.5;


double hourlyRate = 15.5;
double hoursWorked = balance / hourlyRate;
//hoursWorked now holds 1291.0

Division has different results with integers. The / operator does integer division, which
means that any remainder is lost.

int evenlyDivided = 10 / 5;
//evenlyDivided holds 2, because 10 divided by 5 is 2
int unevenlyDivided = 10 / 4;
//unevenlyDivided holds 2, because 10 divided by 4 is 2.5
evenlyDivided stores what you expect, but unevenlyDivided holds 2 because ints cannot
store decimals! It’s important to note that the int doesn’t round the decimal, but floors it.
Java removes the 0.5 to fit the result into an int type!

It’s important to note that if we try to divide any number by 0, we will get an
ArithmeticException error as a result.

Instructions

1.

In main(), there is a variable called subtotal, which represents the subtotal of an amount to
pay on a bill, and a variable called tax, which represents the tax rate that will be applied to
that subtotal.

Create a double variable, total, that holds subtotal plus the product of subtotal and tax.

Print the total variable!

Checkpoint 2 Passed
2.

There were 4 people who bought this meal together and want to split the cost.

Create a double variable called perPerson that holds total divided by 4.

Print the perPerson variable!

public class MultAndDivide {


public static void main(String[] args) {
double subtotal = 30;
double tax = 0.0875;
double total = subtotal + (subtotal * tax);
System.out.println(total);
double perPersons = 4;
double perPerson = total / perPersons;
System.out.println(perPerson);
}
}
Modulo

If we baked 10 cookies and gave them out in batches of 3, how many would we have leftover
after giving out all the full batches we could?

The modulo operator %, gives us the remainder after two numbers are divided.

int cookiesBaked = 10;


int cookiesLeftover = 10 % 3;
//cookiesLeftover holds 1

You have 1 cookie left after giving out all the batches of 3 you could!

Modulo can be a tricky concept, so let’s try another example.

Imagine we need to know whether a number is even or odd. An even number is divisible by
2.

Modulo can help! Dividing an even number by 2 will have a remainder of 0. Dividing an
odd number by 2 will have a remainder of 1.

7 % 2
// 1, odd!
8 % 2
// 0, even!
9 % 2
// 1, odd!

Compound Assignment Operators

Sometimes, we need to adjust the value of a variable.

Imagine we’re working at a bake sale and want to keep track of how many cupcakes we have
by creating a variable called numCupcakes:

int numCupcakes = 12;

If we baked 8 more cupcakes, we know that we could update our variable using the +
operator:

numCupcakes = numCupcakes + 8; // Value is now 20

While this method works just fine, we had to write our variable numCupcakes twice. We can
shorten this syntax by using a compound assignment operator.

Compound assignment operators perform an arithmetic operation on a variable and then


reassigns its value. Using the += compound assignment operator, we can rewrite our previous
code like so:

numCupcakes += 8; // Value is now 20


Now we only need to reference numCupcakes once.

We can use compound assignment operators for all of the arithmetic operators we’ve
covered:

 Addition (+=)
 Subtraction (-=)
 Multiplication (*=)
 Division (/=)
 Modulo (%=)

Order of Operations

If we were to place multiple operators in a single expression, what operation would the
compiler evaluate first?

int num = 5 * (10 - 4) + 4 / 2;

The order of operations dictates the order in which an expression (like the one above) is
evaluated. Operators that share the same precedence are evaluated from Left-to-Right within
the expression.

The order is as follows:

1. Parentheses
2. Exponents
3. Modulo/Multiplication/Division
4. Addition/Subtraction

With this new information in mind, let’s dissect the expression from above so that we can
find the value of num:

5 * (10 - 4) + 4 / 2

10 - 4 would be evaluated first because it is wrapped in parentheses. This value would


become 6 making our expression look like this:

5 * 6 + 4 / 2

Next, 5 * 6 will be evaluated because of the * operator. This value is 30. Our expression
now looks like this:

30 + 4 / 2

Following the order of operations, 4 / 2 will be evaluated next because the division operator
/ has higher precedence than the addition operator +. Our expression now resembles the
following:

30 + 2
30 + 2 is 32. This means that the value of num is 32.

public class Operations {


public static void main(String[] args) {

int expression1 = 5 % 2 - (4 * 2 - 1);


System.out.println(expression1);
// answer is -6

int expression2 = (3 + (2 * 2 - 5)) + 6 - 5;


System.out.println(expression2);
//answer is 3

int expression3 = 5 * 4 % 3 - 2 + 1;
System.out.println(expression3);
// answer is 1

Greater Than and Less Than

Now, we’re withdrawing money from our bank account program, and we want to see if we’re
withdrawing less money than what we have available.

Java has relational operators for numeric datatypes that make boolean comparisons. These
include less than (<) and greater than (>), which help us solve our withdrawal problem.

double balance = 20000.01;


double amountToWithdraw = 5000.01;
System.out.print(amountToWithdraw < balance);
//this will print true, since amountToWithdraw is less than balance

You can save the result of a comparison as a boolean, which you learned about in the last
lesson.

double myBalance = 200.05;


double costOfBuyingNewLaptop = 1000.05;
boolean canBuyLaptop = myBalance > costOfBuyingNewLaptop;
//canBuyLaptop is false, since 200.05 is not more than 1000.05

Equals and Not Equals

So how would we validate our paycheck to see if we got paid the right amount?

We can use another relational operator to do this. == will tell us if two variables are equal:
double paycheckAmount = 620;
double calculatedPaycheck = 15.50 * 40;

System.out.print(paycheckAmount == calculatedPaycheck);
// This will print true, since paycheckAmount equals calculatedPaycheck

Notice that the equality check is two equal signs, instead of one. One equal sign, =, is how we
assign values to variables! It’s easy to mix these up, so make sure to check your code for the
right number of equal signs.

To check if two variables are not equal, we can use !=:

double balance = 20000.0;


double amountToDeposit = 620;
double updatedBalance = balance + amountToDeposit;

boolean balanceHasChanged = balance != updatedBalance;


// balanceHasChanged holds true, since balance does not equal
updatedBalance

Greater/Less Than or Equal To

How could we make sure we got paid at least the amount we expected in our paycheck? We
could use greater than or equal to, >=, or less than or equal to, <=!

double paycheckAmount = 620;


double calculatedPaycheck = 15.50 * 40;
System.out.println(paycheckAmount >= calculatedPaycheck);
//this will print true, since paycheckAmount equals calculatedPaycheck

Instructions

1.

You have been trying to complete a 30 day challenge to drink enough water per day.

Create a double variable called totalRecommendedAmount and set it to the product of the
recommended water intake (recommendedWaterIntake) and the amount of days in the
challenge (daysInChallenge).

Checkpoint 2 Passed
2.

Create a boolean variable called isChallengeComplete and set it to the result of checking if
your intake, yourWaterIntake, is at least as much as the totalRecommendedAmount.

Then, print the isChallengeComplete variable.


public class GreaterThanEqualTo {
public static void main(String[] args){
double recommendedWaterIntake = 8;
double daysInChallenge = 30;
double yourWaterIntake = 235.5;
double totalRecommendedAmount = recommendedWaterIntake * daysInChallenge
;
boolean isChallengeComplete = yourWaterIntake >= totalRecommendedAmount;
System.out.println(isChallengeComplete);
}
}

EQUALS()

So far, we’ve only been using operations on primitive types. It doesn’t make much sense to
multiply Strings, or see if one String is less than the other. But what if we had two users
logging into a site, and we wanted to see if their usernames were the same?

With objects, such as Strings, we can’t use the primitive equality operator. To test equality
with objects, we use a built-in method called .equals(). When comparing objects, make
sure to always use .equals(). == will work occasionally, but the reason why it sometimes
works has to do with how objects are stored in memory.

For the purposes of this lesson (as well as good practice) remember to use .equals() instead
of == when comparing objects.

To use it, we call it on one String, by using ., and pass in the String to compare against in
parentheses:

String person1 = "Paul";


String person2 = "John";
String person3 = "Paul";

System.out.println(person1.equals(person2));
// Prints false, since "Paul" is not "John"

System.out.println(person1.equals(person3));
// Prints true, since "Paul" is "Paul"

String Concatenation

We have covered a lot of built-in functionality in Java throughout this lesson. We’ve seen +,
-, <, ==, and many other operators. Most of these only work on primitives, but some work on
Strings too!
Let’s say we want to print out a variable, and we want to describe it as we print it out. For our
bank account example, imagine we want to tell the user:

Your username is: <username>

With the value of the variable username displayed.

The + operator, which we used for adding numbers together, can be used to concatenate
Strings. In other words, we can use it to join two Strings together!

String username = "PrinceNelson";


System.out.println("Your username is: " + username);

This code will print:

Your username is: PrinceNelson

We can even use a primitive datatype as the second variable to concatenate, and Java will
intelligently make it a String first:

int balance = 10000;


String message = "Your balance is: " + balance;
System.out.println(message);

This code will print:

Your balance is: 10000

You might also like