General Flashcards
Java is platform independent
Programs written in Java can be executed on any operating system (Windows, Linux, Mac, etc.)
Bytecode
Java compiles source code into bytecode. Bytecode is platform independent. There is no difference between bytecode for Windows, Mac, or Linux. The JVM converts bytecode into machine code for the specific platform that the user uses.
Advantage of this two-step compilation is that Java can be run on all platforms that have the JVM installed.
JDK, JRE, JVM
JDK includes JRE, which contains the JVM
Integrated Development Environment (IDE)
IDE contains text editor and GUI to debug, compile, and run programs.
Package
A grouping of related classes and interfaces. Two or more files can have the same name if they belong to different packages.
Java has many pre-created packages, such as java.io (input/output) and java.awt (code for implementing GUI). To use pre-written packages, you need to import them.
main() method
Whenever a Java application is started, the main() method is the first method to be called. main() takes an array of string as input.
Statement
Every statement ends with a semicolon
Declaration
Example: int age;
Your program allocates memory to store this data.
Primitive data types
8 primitive data types.
4 of them are for integers:
- byte: Integers -128 to 127. Byte of storage.
- short: 2 bytes storage. -32768 to 32767
- int: 4 bytes storage. -2^31 to (2^31) - 1.
- long: 8 bytes. -2^63 to (2^63) - 1. Rarely used.
2 of them for floating point numbers (numbers with fractional parts):
- float: 4 bytes storage. -3.40282347 x 10^38 to 3.40282347 x 10^38. Precision of 7 digits. This means if you use float to store a number like 1.23456789 (10 digits), it will be rounded to 1.234568.
- double: 8 bytes storage. Range of -1.79769313486231570 x 10^308 to 1.79769313486231570 x 10^308. Precision of 15 digits.
By default, floating point in Java is double.
Two more primitive date types:
- char: stores single Unicode character. 2 bytes memory. When you initialize a char you need to put the character in single quotes.
- boolean: can only hold 2 values: true and false.
Naming a variable
First character cannot be number. Reserved words cannot be used. Examples of reserved words are System, if, While, etc.
Initialization
Giving a variable a value. You can initialize at deceleration or in a separate statement. You can initialize severance variables on the same line (you separate them by a comma).
Basic operators
+, -, *, /, %
x = 7, y =2
x / y = 3 (rounds down to nearest integer)
x % y = 1 (gives remainder)
If either x or y is a floating point number, the result will be a floating point number.
++ and - - operators
System.out.println(counter++); will first print counter and then increment it.
System.out.println(++counter); will first increment counter and then print it.
Casting
Do not need to explicitly cast when converting smaller data to large data. (I.g., int to double).
When casting larger data to smaller data, need to explicitly cast.
Example: int x = (int) 20.9.
x = 20.
String
String is a reference data type (not primitive data type). This means it’s an object. Specifically, an object of the String class.
To assign a String variable, you must enclose the text in double quotes.
“+” operator can concatenate two strings.
Java String class has methods.
Whenever you use a method, you need to use the dot operator.
Common ones:
- length(): total number of characters the string has (whitespace included)
- toUpperCase()/toLowerCase(): converts string to upper/lower case.
Example: String uCase “Hello World”.toUpperCase(); uCase = “HELLO WORLD”.
- substring(6): returns a substring starting from index 6 until the end. Indexing in Java starts at 0, not 1.
- substring(1, 8): same as above, but extracts from index 1 to 7. Stops AT index 8, NOT AFTER. Thus letter at index 8 is NOT included.
- charAt(1): returns character at index 1.
- equals(): returns true if two strings are identical. Example: boolean equalsOrNot = “This is Jamie”.equals(“This is Jamie”);
- split(): splits a string into substrings based on a user-defined separator (also known as delimiter). Returns an array that contains resulting substrings.
Example: String names = “Peter, John,” Andy, David”;
String[] splitNames = names.split(“, “); Delimiter is comma followed by space.
Array
Collection of data that are normally related to each other.
Can be declared int[] userAge or int userAge[]. Latter syntax is not proffered.
3 ways to declare and initialize array:
1) int[] userAge = new int[] {21, 22, 23, 24, 25};
Can be simplified to:
2) int[] userAge = {21, 22, 23, 24, 25};
3) int[] userAge = new int[5]; Default values are 0. We then have to initialize.
Array methods (Arrays class)
Arrays come with pre-written methods. They’re found in java.until.Arrays class. To use them, you have to add the statement import java.until.Arrays; to your program. This tells the compiler where to find the code for these methods. Import statement must appear after package statement and before class declaration.
We don’t need an import statement to use String methods since the String class is present in the java.lang package which is imported by default.
Commonly used methods:
- equals(). Returns true if two arrays are equal. (I.g,: boolean result = Arrays.equals(arr1, arr2);
All methods in Arrays are static. Hence we had to add “Arrays” in front of the method name.
- copyOfRange(): 3 arguments. Copy the contents of one array into another. Example: int[] dest = Arrays.copyOfRange(source, 3, 7); Copies elements from 3 to 6 (NOT 7).
- toString(): 1 argument. Returns a String representation of array contents.
- sort(): sorts array in ascending order. Does not return new array. It modifies existing array.
- binarySearch(): 2 arguments. Allows you to search for specific value in SORTED array. Make sure array is sorted first.
Example: int foundIndex = Arrays.binarySearch(myInt, 78); Returns index of 78 if it exists in array myInt. If the number is not found, it will return a negative number. Negative means it’s it’s not found, and the number tells you which POSITION (NOT INDEX) should be if it were to exist in the array (I.g,: -4 means position 4, index 3).
Fields vs methods
Come back
Array length
No length() method. Instead, we use field length.
userAge.length; (no “()” )
Primitive Type vs. Reference Type
All data types in Java fall into one of two categories: Primitive Type or Reference Type. There are only 8 primitive types. The rest are reference types.
Reference types include Strings, arrays, classes, and interfaces.
One of the main differences between the two is how data is stored.
Primitive type stores its own data. With int myNumber = 5; the variable “myNumber” stored the actual value 5.
Reference type does not store the actual data. Instead, it stores a reference to the data. It does not tell the compiler what the value of the data is; it tells the compiler where to find the actual data.
For example, with String message = “Hello”; the variable message does not store the string “hello”. Instead, message stores the address of the memory location of “hello”.
Strings are immutable
Immutable means the value cannot be changed. When we update a Strong variable, we are actually creating a new string and assigning the memory address to the String variable.
Example:
String message = “hello”;
update message:
message = “World”;
The compiler does not go to the storage location where “Hello” is stored and change the value to “World.” Instead, it creates a new string “World” and stores it somewhere else in memory. This new address is then assigned to the variable message. In other words, there are TWO string now: “Hello” and “World”. If “Hello” is no longer needed, it is destroyed to free up memory. This is called garbage collection, which Java handles automatically.
System.out.println();
PrintStream class tbc
Escape sequences
Sometimes we need to print special “unprintable” characters, such as a tab or a newline. You need to use the \ (backsplash) character to escape characters that would otherwise have a different meaning.
Example:
System.out.println(“Hello\tWorld”);
Output:
Hello World
Commonly used escape sequences:
Printing a newline: \n.
Example:
System.out.println(“Hello\nWorld”);
Output:
Hello
World
Print the backslash character itself:
Example: System.out.println(\);
To print double quotes so that the double quotes don’t end the string: \”
Example: System.out.println(“I am 5’9\” tall”);
Output:
I am 5’9” tall
Formatting outputs: printf()
printf() is more complex than println(), but it offers more control.
printf() requires more than one argument. The first argument is the string to be formatted. The other arguments replace the format specifiers (%.3f, %d, etc.) which serve as placeholders.
Format specifiers always begin with a percent sign % and end with a converter (such as f or d). In between % and converter, you can add flags. For example, in %.3f, “.3” is a flag. It indicates that we want to display the number with 3 decimal places.