Unit 1 – Java Basics
Numeric Data Types
Type What it stores Storage Requirements Range
int whole numbers 4 byte 2,147,483,648 to +2,147,483,647
double decimal numbers 8 byte -1.7977+E308 to +1.7977+E308
Non-Numeric Data Types
Type What it stores Examples
char single characters 'C', 'k', '$', '8'
boolean logical values true, false
Important: When a variable is declared of a given type, it is capable of storing a value as described in the above tables. It may not accurately store values of other types. For example, if a double is stored in an int variable, it will lose the decimal part of the number. So choose data types wisely and handle them with care.
i.e. int s = 4/3; // s holds the value of 1
As we learn Java, we will work with many abstract data types. Some of these will be pre-defined and some we will create ourselves. For now, we will work with the abstract data type String. The String data type is capable of holding one or more characters and can be used to store words or even whole sentences. For example, suppose a program we are writing requires that we store the name of a person. A String variable will be the choice for this job. Recall that a char variable is only capable of storing a single character and cannot store an entire word.
Comments:
• Comments are notes in plain English inserted in the source code.
• Comments are used to:
👍 document the program’s purpose, author, revision history, copyright notices, etc.
👍 describe fields, constructors, and methods
👍explain obscure or unusual places in the code
👍temporarily “comment out” fragments of code
Examples:
int s = (int)(Math.random()*3); // s will randomly be assigned either 0, 1, or 2
The above example is called a single line comment.
/* Author: Craig Sapp
This code takes in a number from 1 to 1000 and prints all the numbers that are
even factors of the number. */
The above example is called a block comment. It is placed between /* and */ marks:
Syntax vs. Style:
An identifier is a programmer-defined name for something in Java such as a variable, a class or a method. There are several rules and conventions for names in Java. A rule means that it is a requirement of Java. A convention is a generally accepted way of doing something. It is not a requirement, but rather a good idea. It ensures that all programmers use the same style. That makes it easier for programmers to collaborate.
Identifier Naming Rules
1. Must begin with a letter ('a'..'z', 'A'..'Z')
2. All other characters must be a letter, number or an underscore(_)
3. May not contain any spaces (stateTax not state Tax)
4. Cannot be the same as an already reserved Java keyword, such as public or if
* Note: Java is a case-sensitive language. That means it treats lowercase and uppercase letters as different letters. So when you name a variable, you must type it the same way every time so that it is recognized as the same variable. For example, the identifier number is different from Number.
Identifier Naming Conventions
1. Classes begin with a capital letter, lowercase after except for beginnings of secondary words in the variable (IntNum, not Intnum)
2. Variables and methods begin with lowercase letters, capitalizing secondary words in the name (stateTax, not statetax)
3. Constants are all capital letters with underscores separating words (TAX_RATE not TAXRATE)
Other rules (syntax): End statements with a semicolon; declare a type for each variable
Other conventions (style): Indent braces for easier viewing, space code for easier reading
Reserved Words:
• In Java a number of words are reserved for a special purpose.
• Reserved words use only lowercase letters.
• Reserved words include:
👍primitive data types: int, double, char, boolean, etc.
👍 storage modifiers: public, private, static, final, etc.
👍 control statements: if, else, switch, while, for, etc.
👍 built-in constants: true, false, null
• There are about 50 reserved words total.
Declaring variables:
Before a variable can be used in a program it must be declared. That means it must be given a name and a type (and optionally an initial value). By doing so, we allow Java to set aside storage space for this named variable.
Here are some examples:
int age;
double cost;
char letter;
String name;
boolean gameOver;
It also permitted to declare several variables of one type in the same statement.
int age, year;
double price, cost, tax;
Lastly, it is also possible to give a variable an initial value when it is declared.
int age = 17, year = 2006;
double cost = 12.89;
char letterGrade = 'A';
String name = "Boba Fett";
boolean gameOver = false;
Note the use of single quotes when assigning a character value and double quotes when assigning a string value. They are requirements of these data types.
Assignment:
Note that the form of the assignment statement requires that the variable to be assigned is on the left of the equal sign and that the assigning expression is always on the right. See below.
Correct: age = currentYear - yearBorn;
Incorrect: currentYear - yearBorn = age;
Assign Values before using:
We can also use declared variables in equations and output, but only after first giving the variable a value.
Correct
double price = 18.95, tax;
tax = .0725 * price;
Incorrect
double price, tax;
tax = .0725 * price;
The problem in the second version is that we are trying to use the variable price in an equation, but price does not have a value yet. This will produce a compile-time error. The same error will occur if we try to output price before it has a value.
Compound Operations (Increment/Decrement)
A variable in java is like a slate. We can easily change its value after it’s been created. In fact it is very common to replace a value with “itself with some operation performed on it”.
For example: We want to add 5 to a and store it back into a.
a = a + 5; // Compound operator a += 5;
More compound operators:
a = a – 5; // a -= 5;
a = a*5; // a*= 5;
a = a/5; // a /= 5;
a = a + 1; // a++; Called the increment operator
a = a – 1; // a--; Called the decrement operator
Constants:
Declaring constants Sometimes programmers have the need to store a value which will never or very rarely change. A variable, by its nature, is allowed to be changed. So a variable is not the right choice for this data storage. Instead, programmers use a different type of storage device called a constant.
A constant declaration is just like a variable declaration with the addition of the Java keyword final.
Examples:
final int CURRENT_YEAR = 2006;
final double SALES_TAX_RATE = 0.0725;
final String ERROR_MSG = "Invalid Input";
Benefit of Constants:
a) If the tax rate changes we only have to change it in once place instead of everywhere we use it.
b) It prevents these values from accidentally getting changed
How to Take User Input:
Must have the following imports:
import java.io.*;
import java.util.*;
Create a Scanner object (from the Scanner class that you imported)
Scanner getIt = new Scanner(System.in);
Then print a statement or question that you want the user to enter:
System.out.println(“How many random numbers do you want?”);
Then use nextInt(), nextDouble(), nextLine() – for strings to assign their response to a variable.
int numRand = getIt.nextInt();
Basic Output
There are two main ways that you will use the System.out statement, System.out.print andSystem.out.println (read this as print line) . Both of these statements display information in the same way. It's what they cause to happen after the display takes place is what makes them different. Let's see some examples.
The code...
System.out.print("Hello");
System.out.print("World");
will produce the following output:
HelloWorld
but...
System.out.println("Hello");
System.out.println("World");
will produce:
Hello
World
Basic Math with Java
Mathematics plays a large role in computer programming. Practically everything boils down to math in some way. So Java has to have a way of performing math operations. We will begin with basic arithmetic: addition, subtraction, multiplication and division.
Java's Arithmetic Symbols
operation symbol example of use
addition + a = b + c;
subtraction - a = b - c;
multiplication * a = b * c;
division / a = b / c;
modulus % a = b%c;
Order of Operations Java has the same order of operations as in Algebra. Remember PEMDAS?
Parentheses
Exponents
Multiplication and Division together (Also Modulus)
Addition and Subtraction together
Modulus
The modulus operator is another arithmetic operation that you will find quite useful. Modulus, or mod for short, gives the integer remainder of division. The symbol for modulus is %, but it has nothing to do with percents. Here are some examples of results of modulus calculations:
13 % 5 = 3
26 % 10 = 6
20 % 4 = 0
5 % 7 = 5
Math Class
The Math Class So far we have used only basic math operations. Now we will see how Java provides for more complex math such as square roots and exponents. To perform these and other math functions (or methods), we will use Java's Math class. There are many math methods available, but we will only use the following. Note their use in code in the examples shown. All of the methods in the math class are static (we will learn what this means later) but for now realize that you call the method by its class name.
A Sampling of Java's Math Class Functions
Method What it does
int abs(int x) Returns the absolute value of the integer parameter x
double abs(double x) Returns the absolute value of the double parameter x
double pow(double x, double y) Returns x to the power of y
double sqrt(double x) Returns the square root of x
double random() Returns a number in the range [0,1)
Examples:
double x = Math.sqrt(49); // x would be 7
double y = Math.abs(-4.2); // y would be 4.2
double z = Math.pow(2,5); // z would be 32
double r = 5*Math.random(); // r would be a random double between [0,5)
Mixing Data Types
Integers vs. Doubles We have already seen various scenarios where integers and decimals interact with each other. A little more discussion is necessary in order to truly understand how this works. A few starting points:
1. When integers interact with integers, the result is always integer.
2. When decimals interact with decimals, the result is always decimal.
3. When integers and decimals interact, the result will always be in decimal form.
Let's see some examples. Assume the following declarations:
int t; double dub;
A Sampling of Mixed-Mode Arithmetic
Assignments Results Comment
int t = 3 + 2; t = 5 dub gets the decimal version of
dub = 3 + 2; dub = 5.0
int t = 3.2 + 2.5; t = error t can’t receive a decimal value
dub = 3.2 + 2.5; dub = 5.7
intt = 3.2 + 2; t = error t can’t receive a decimal value
dub = 3.2 + 2; dub = 5.2
intt = 3 + 2.5; t = error t can’t receive a decimal value
dub = 3 + 2.5; dub = 5.5
intt = 3 / 2; t = 1 both get the truncated value of 1.5 (1)
dub = 3 / 2; dub = 1.0
Division with Integers
The last example requires further analysis. The rule to remember is that integers mixing with integers results in an integer. Even though the result is stored in a double, it is a truncated integer before it is stored.
So how can we get the correct decimal answer when dividing integers? Below are two ways to accomplish that. Assume the variable declarations given.
quotient = 3.0/2;
quotient = (double) 3 / 2; //NOT (double) (3 / 2);
The second example makes use of typecasting, temporarily assigning or casting an int value as a double. Note the use of parentheses around the keyword double.
Typecasting can also enable a decimal value to be stored in an int variable, as a truncated integer. Recall the loss of precision errors from above when attempting to store a decimal in an int. If we typecast, as follows
intt = (int)(3.2 + 2.5);
the result is that intt will contain 5, the truncated form of 5.7.
Example: int r = (int)(Math.random()*5); // results in 0,1,2,3, or 4 randomly
Note: Remember 1 is not possible to get from Math.random() range = [0,1)
Basic Boolean Expressions:
A boolean variable is a variable that can either be true or false.
Logical Operators: && (and) || (or) ! (not)
Relational Operators:
< (less than) <= (less than or equal) > (greater than) >= (greater than or equal) == (equal to) != (not equal to)
boolean s = 5 > 3 || 2 != 2; //s will be true because 5 > 3 so one of the two
conditions is true
boolean t = (5 ==3) && (2==2); // t will be false because 5 is not equal to 3 and
both cases must be true to be true
Basic String Operations:
A String is a “string” of characters which can be a word or several words (including numbers and symbols). The indices of the characters are numbered from 0 to str.length – 1.
Concatenation: The process of combining two or more strings with the + operator is called concatenation.
String combination = “Let’s” + “Go”;
System.out.println(combination); //returns Let’sGo (no space)
String Methods:
int length() returns the number of characters in the String
int indexOf(String str) returns the first index in the string equal to str
String substring(int first) returns the String from index first to the end of the String
String substring(int first, int last) returns the String from index first to the index right before last
Example:
String sample = “This class”;
int len = sample.length();//len is equal to 10 because there are 10 characters including the space
int index = sample.indexOf(“is”);//index is equal 2 because that’s the first index of “is”
String partOne = sample.substring(3); // partOne is equal to “s class”
String partTwo = sample.substring(3,5); // partTwo is equal to “s “
Methods and Method Headers:
public int roundedUp(double d)
The above is an example of a method header. The name of the method is roundedUp. It takes in a double as a parameter and returns an int value that is rounded up to the next integer.
public void printStringBackwards(String str)
The method above is a void method, which means it does not return anything. It accepts a String parameter and will print the String str backwards.
Example: Create a method that returns true if the number passed is an odd number that is bigger than 7.
public boolean seven(int n)
{
return (n %2 == 1 && n > 7);
}
or
public boolean seven(int n)
{
if (n%2 ==1 && n > 7)
{
return true
}
else
{
return false;
}
}
Errors and Exceptions:
Compile Errors: These errors occur when we compile our program. Usually the culprit of a compile error is a syntax error, which is an error caused by violating the rules of the programming language.
i.e. forget braces, semicolons, having parameters that don’t match in type and number
Run-Time Errors: In this case, the compiler will compile the program but we get an error when we run it. The java run-time environment throws an exception which means it stops execution and prints an error message.
i.e. dividing by 0, out of bounds index with Arrays, infinite loop (no thrown exception in this case)
Logic Errors: The program compiles and runs without an exception thrown; it simply does not accomplish the goal of the program.