Title | Code Academy-Learn Java Notes |
---|---|
Author | Brian Hall |
Course | Software I |
Institution | Western Governors University |
Pages | 39 |
File Size | 443.6 KB |
File Type | |
Total Downloads | 93 |
Total Views | 173 |
CodeAcademy Learn Java Notes for all modules...
Cheatsheets / Learn Java
Hello World Print Line System.out.println() can print to the console:
System.out.println("Hello, world!"); System is a class from the core library
// Output: Hello, world!
provided by Java out is an object that controls the output println() is a method associated with that
object that receives a single argument
Comments Comments are bits of text that are ignored by the compiler. They are used to increase the readability
// I am a single line comment!
of a program. Single line comments are created by using // .
Multi-line comments are created by starting
/* And I am a multi-line comment! */
with /* and ending with */ .
main() Method In Java, every application must contain a main() method, which is the entry point for the
public class Person {
application. All other methods are invoked from the main() method. The signature of the method is public static
public static void main(String[] args) {
void main(String[] args) { } . It accepts a single
argument: an array of elements of type String .
System.out.println("Hello, world!"); } }
Classes A class represents a single concept. A Java program must have one class whose name
public class Person {
is the same as the program filename. In the example, the Person class must be declared in a program file named Person.java.
public static void main(String[] args) { System.out.println("I am a person, not a computer."); } }
Compiling Java In Java, when we compile a program, each individual class is converted into a .class file,
# Compile the class file:
which is known as byte code.
javac hello.java
The JVM (Java virtual machine) is used to run the byte code.
# Execute the compiled file: java hello
Whitespace Whitespace, including spaces and newlines, between statements is ignored.
System.out.println("Example of a statement"); System.out.println("Another statement"); // Output: // Example of a statement // Another statement
Statements In Java, a statement is a line of code that executes a task and is terminated with a ; .
System.out.println("Java Programming ");
Cheatsheets / Learn Java
Variables boolean Data Type In Java, the boolean primitive data type is used to store a value, which can be either true or false .
boolean result = true; boolean isMarried = false;
Strings A String in Java is a Object that holds multiple characters. It is not a primitive datatype.
// Creating a String variable
A String can be created by placing characters
String name = "Bob";
between a pair of double quotes ( " ). To compare Strings, the equals() method must be used instead of the primitive equality comparator == .
// The following will print "false" because strings are case-sensitive System.out.println(name.equals("bob") );
int Data Type In Java, the int datatype is used to store integer values. This means that it can store all positive and
int num1 = 10;
// positive value
negative whole numbers and zero.
int num2 = -5;
// negative value
int num3 = 0; // zero value int num4 = 12.5; // not allowed
char Data Type In Java, char is used to store a single character. The character must be enclosed in single quotes.
char answer = 'y';
Primitive Data Types Java’s most basic data types are known as primitive data types and are in the system by
int age = 28;
default. The available types are as follows: int
char grade = 'A'; boolean late = true;
char boolean byte
byte b = 20; long num1 = 1234567;
long short
short no = 10;
double
float k = (float)12.5; float null is another, but it can only ever store the
double pi = 3.14;
value null .
Static Typing In Java, the type of a variable is checked at compile time. This is known as static typing. It has
int i = 10;
// type is int
the advantage of catching the errors at compile
char ch = 'a';
// type is char
j = 20;
// won't compile,
no type is given char name = "Lil";
// won't compile,
time rather than at execution time. Variables must be declared with the appropriate data type or the program will not compile.
wrong data type
final Keyword The value of a variable cannot be changed if the variable was declared using the final keyword.
// Value cannot be changed:
Note that the variable must be given a value when
final double PI = 3.14;
it is declared as final . final variables cannot be changed; any attempts at doing so will result in an error message.
double Data Type The double primitive type is used to hold decimal values.
double PI = 3.14; double price = 5.75;
Math Operations Basic math operations can be applied to int , double and float data types:
int a = 20; int b = 10;
+ addition - subtraction * multiplication / division % modulo (yields the remainder)
These operations are not supported for other data types.
int result; result = a + b;
// 30
result = a - b;
// 10
result = a * b;
// 200
result = a / b;
// 2
result = a % b;
// 0
Comparison Operators Comparison operators can be used to compare two values:
int a = 5; int b = 3;
> greater than < less than >= greater than or equal to b; // result now holds the boolean value true
Compound Assignment Operators Compound assignment operators can be used to change and reassign the value of a variable using
int number = 5;
one line of code. Compound assignment operators include += , -= , *= , /= , and %= .
number += 3; // Value is now 8 number -= 4; // Value is now 4 number *= 6; // Value is now 24 number /= 2; // Value is now 12 number %= 7; // Value is now 5
Increment and Decrement Operators The increment operator, ( ++ ), can increase the value of a number-based variable by 1 while the
int numApples = 5;
decrement operator, ( -- ), can decrease the value
numApples++; // Value is now 6
of a variable by 1 .
int numOranges = 5; numOranges--; // Value is now 4
Order of Operations The order in which an expression with multiple operators is evaluated is determined by the order of operations: parentheses -> multiplication -> division -> modulo -> addition -> subtraction.
Cheatsheets / Learn Java
Object-Oriented Java Java objects’ state and behavior In Java, instances of a class are known as objects. Every object has state and behavior in the form of
public class Person {
instance fields and methods respectively.
// state of an object int age; String name; // behavior of an object public void set_value() { age = 20; name = "Robin"; } public void get_value() { System.out.println("Age is " + age); System.out.println("Name is " + name); } // main method public static void main(String [] args) { // creates a new Person object Person p = new Person(); // changes state through behavior p.set_value(); } }
Java instance Java instances are objects that are based on classes. For example, Bob may be an instance of
public class Person {
the class Person .
int age;
Every instance has access to its own set of
String name;
variables which are known as instance fields, which are variables declared within the scope of
// Constructor method public Person(int age, String name)
the instance. Values for instance fields are assigned within the constructor method.
{ this.age = age; this.name = name; } public static void main(String[] args) { Person Bob = new Person(31, "Bob"); Person Alice = new Person(27, "Alice"); } }
Java dot notation In Java programming language, we use . to access the variables and methods of an object or a
public class Person { int age;
Class. This is known as dot notation and the structure looks like thisinstanceOrClassName.fieldOrMethodName
public static void main(String [] args) { Person p = new Person(); // here we use dot notation to set age p.age = 20; // here we use dot notation to access age and print System.out.println("Age is " + p.age); // Output: Age is 20 } }
Constructor Method in Java Java classes contain a constructor method which is used to create instances of the class.
public class Maths {
The constructor is named after the class. If no
public Maths() { System.out.println("I am
constructor is defined, a default empty constructor is used.
constructor"); } public static void main(String [] args) { System.out.println("I am main"); Maths obj1 = new Maths(); } }
Creating a new Class instance in Java In Java, we use the new keyword followed by a call to the class constructor in order to create a
public class Person {
new instance of a class.
int age;
The constructor can be used to provide initial
// Constructor:
values to instance fields.
public Person(int a) { age = a; } public static void main(String [] args) { // Here, we create a new instance of the Person class: Person p = new Person(20); System.out.println("Age is " + p.age); // Prints: Age is 20 } }
Reference Data Types A variable with a reference data type has a value that references the memory address of an
public class Cat {
instance. During variable declaration, the class
public Cat() {
name is used as the variable’s type.
// instructions for creating a Cat instance } public static void main(String[] args) { // garfield is declared with reference data type `Cat` Cat garfield = new Cat(); System.out.println(garfield); // Prints: Cat@76ed5528 } }
Constructor Signatures A class can contain multiple constructors as long as they have different parameter values. A
// The signature is `Cat(String
signature helps the compiler differentiate between
furLength, boolean hasClaws)`.
the different constructors.
public class Cat {
A signature is made up of the constructor’s name
String furType;
and a list of its parameters.
boolean containsClaws; public Cat(String furLength, boolean hasClaws) { furType = furLength; containsClaws = hasClaws; } public static void main(String[] args) { Cat garfield = new Cat("Longhair", true); } }
null Values null is a special value that denotes that an
object has a void reference.
public class Bear { String species; public Bear(String speciesOfBear;) { species = speciesOfBear; } public static void main(String[] args) { Bear baloo = new Bear("Sloth bear"); System.out.println(baloo); // Prints: Bear@4517d9a3 // set object to null baloo = null; System.out.println(baloo); // Prints: null } }
The body of a Java method In Java, we use curly brackets {} to enclose the body of a method.
public class Maths { public static void sum(int a, int
The statements written inside the {} are executed when a method is called.
b) { // Start of sum int result = a + b; System.out.println("Sum is " + result); } // End of sum
public static void main(String [] args) { // Here, we call the sum method sum(10, 20); // Output: Sum is 30 } }
Method parameters in Java In java, parameters are declared in a method definition. The parameters act as variables inside
public class Maths {
the method and hold the value that was passed in.
public int sum(int a, int b) {
They can be used inside a method for printing or
int k = a + b;
calculation purposes.
return k;
In the example, a and b are two parameters which,
}
when the method is called, hold the value 10 and 20 respectively.
public static void main(String [] args) { Maths m = new Maths(); int result = m.sum(10, 20); System.out.println("sum is " + result); // prints - sum is 30 } }
Java Variables Inside a Method Java variables defined inside a method cannot be used outside the scope of that method.
//For example, `i` and `j` variables are available in the `main` method only: public class Maths { public static void main(String [] args) { int i, j; System.out.println("These two variables are available in main method only"); } }
Returning info from a Java method A Java method can return any value that can be saved in a variable. The value returned must match
public class Maths {
with the return type specified in the method signature.
// return type is int
The value is returned using the return keyword.
public int sum(int a, int b) { int k; k = a + b; // sum is returned using the return keyword return k; } public static void main(String [] args) { Maths m = new Maths(); int result; result = m.sum(10, 20); System.out.println("Sum is " + result); // Output: Sum is 30 } }
Declaring a Method Method declarations should define the following method information: scope (private or public),
// Here is a public method named sum
return type, method name, and any parameters it
whose return type is int and has two
receives.
int parameters a and b public int sum(int a, int b) { return(a + b); }
Cheatsheets / Learn Java
Conditionals and Control Flow else Statement The else statement executes a block of code when the condition inside the if statement is
boolean condition1 = false;
false . The else statement is always the last
condition.
if (condition1){ System.out.println("condition1 is true"); } else{ System.out.println("condition1 is not true"); } // Prints: condition1 is not true
else if Statements else - if statements can be chained together to
check multiple conditions. Once a condition is true , a code block will be executed and the
int testScore = 76; char grade;
conditional statement will be exited. There can be multiple else - if statements in a single conditional statement.
if (testScore >= 90) { grade = 'A'; } else if (testScore >= 80) { grade = 'B'; } else if (testScore >= 70) { grade = 'C'; } else if (testScore >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println("Grade: " + grade); // Prints: C
if Statement An if statement executes a block of code when a specified boolean expression is evaluated as
if (true) { System.out.println("This code
true .
executes"); } // Prints: This code executes if (false) { System.out.println("This code does not execute"); } // There is no output for the above statement
Nested Conditional Statements A nested conditional statement is a conditional statement nested inside of another conditional
boolean studied = true;
statement. The outer conditional statement is
boolean wellRested = true;
evaluated first; if the condition is true , then the nested conditional statement will be evaluated.
if (wellRested) { System.out.println("Best of luck today!"); if (studied) { System.out.println("You are prepared for your exam!"); } else { System.out.println("Study before your exam!"); } } // Prints: Best of luck today! // Prints: You are prepared for your exam!
AND Operator The AND logical operator is represented by && . This operator returns true if the boolean
System.out.println(true && true); //
expressions on both sides of the operator are
Prints: true
true ; otherwise, it returns false .
System.out.println(true && false); // Prints: false System.out.println(false && true); // Prints: false System.out.println(false && false); // Prints: false
NOT Operator The NOT logical operator is represented by ! . This operator negates the value of a boolean
boolean a = true;
expression.
System.out.println(!a); // Prints: false System.out.println(!false) // Prints: true
The OR Operator The logical OR operator is represented by || . This operator will return true if at least one of the boolean expressions being compared has a true value; otherwise, it will return false .
System.out.println(true || true); // Prints: true System.out.println(true || false); // Prints: true System.out.println(false || true); // Prints: true System.out.println(false || false); // Prints: false
Conditional Operators - Order of Evaluation If an expression contains multiple conditional operators, the order of evaluation is as follows:
boolean foo = true && (!false ||
Expressions in parentheses -> NOT -> AND -> OR.
true); // true /* (!false || true) is evaluated first because it is contained within parentheses. Then !false is evaluated as true because it uses the NOT operator. Next, (true || true) is evaluation as true. Finally, true && true is evaluated as true meaning foo is true. */
Cheatsheets / Learn Java
Arrays and ArrayLists Index An index refers to an element’s position within an
int[] marks = {50, 55, 60, 70, 80};
array. The index of an array starts from 0 and goes up to one less than the total length of the array.
System.out.println(marks[0]); // Output: 50 System.out.println(marks[4]); // Output: 80
Arrays In Java, an array is used to store a list of elements of the same datatype.
// Create an array of 5 int elements
Arrays are fixed in size and their elements are
int[] marks = {10, 20, 30, 40, 50};
ordered.
Array creation in Java In Java, an array can be created in the following ways: Using the {} notation, by adding each
int[] age = {20, 21, 30};
element all at once.
int[] marks = new int[3]; marks[0] = 50;
Using the new keyword, and assigning each
marks[1] = 70;
position of the array individually.
marks[2] = 93;
Changing an Element Value To change an element value, select the element via its index and use the assignment operator to
int[] nums = {1, 2, 0, 4};
set a new value.
// Change value at index 2 nums[2] = 3;
Java ArrayList In Java, an ArrayList is used to represent a dynamic list.
// import the ArrayList package
While Java arrays are fixed in size (the size cannot
import java.util.ArrayList;
be modified), an ArrayList allows flexibility by being able to both add and remove elements.
// create an ArrayList called students ArrayList students = new ArrayList();
Modifying ArrayLists in Java An ArrayList can easily be modified using built in methods.
...