Java is a popular programming language, created in 1995.
It is owned by Oracle, and more than 3 billion devices run Java.
It is used for:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn import metrics
System.out.print("I will print on the same line.");
System.out.println("Hello World!");
// This is a comment
/* The code below will print the words Hello World
to the screen, and it is amazing */
type variableName = value;
final int myNum = 15;
Data Type | Size | Description |
---|---|---|
byte |
1 byte | Stores whole numbers from -128 to 127 |
short |
2 bytes | Stores whole numbers from -32,768 to 32,767 |
int |
4 bytes | Stores whole numbers from -2,147,483,648 to 2,147,483,647 |
long |
8 bytes | Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
float |
4 bytes | Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits |
double |
8 bytes | Stores fractional numbers. Sufficient for storing 15 decimal digits |
boolean |
1 bit | Stores true or false values |
char |
2 bytes | Stores a single character/letter or ASCII values |
byte myNum = 100;
short myNum = 5000;
int myNum = 100000;
long myNum = 15000000000L;
float myNum = 5.75f;
double d1 = 12E4d;
boolean isJavaFun = true;
char myGrade = 'B';
String greeting = "Hello World";
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int
Operator | Name | Description | Example |
---|---|---|---|
+ | Addition | Adds together two values | x + y |
- | Subtraction | Subtracts one value from another | x - y |
* | Multiplication | Multiplies two values | x * y |
/ | Division | Divides one value by another | x / y |
% | Modulus | Returns the division remainder | x % y |
++ | Increment | Increases the value of a variable by 1 | ++x |
-- | Decrement | Decreases the value of a variable by 1 | --x |
Operator | Example | Same As |
---|---|---|
= | x = 5 | x = 5 |
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x - 3 |
*= | x *= 3 | x = x * 3 |
/= | x /= 3 | x = x / 3 |
%= | x %= 3 | x = x % 3 |
&= | x &= 3 | x = x & 3 |
|= | x |= 3 | x = x | 3 |
^= | x ^= 3 | x = x ^ 3 |
>>= | x >>= 3 | x = x >> 3 |
<<= | x <<= 3 | x = x << 3 |
Operator | Name | Example |
---|---|---|
== | Equal to | x == y |
!= | Not equal | x != y |
> | Greater than | x > y |
< | Less than | x < y |
>= | Greater than or equal to | x >= y |
<= | Less than or equal to | x <= y |
Operator | Name | Description | Example |
---|---|---|---|
&& | Logical and | Returns true if both statements are true | x < 5 && x < 10 |
|| | Logical or | Returns true if one of the statements is true | x < 5 || x < 4 |
! | Logical not | Reverse the result, returns false if the result is true | !(x < 5 && x < 10) |
String greeting = "Hello";
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());
String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate")); // Outputs 7
System.out.println("Doe" + " " + "John");
System.out.println("Doe" + " " +.concat("John"));
Escape character | Result | Description |
---|---|---|
\' | ' | Single quote |
\" | " | Double quote |
\\ | \ | Backslash |
Code | Result | |
---|---|---|
\n | New Line | |
\r | Carriage Return | |
\t | Tab | |
\b | Backspace | |
\f | Form Feed |
Math.max(5, 10);
Math.min(5, 10);
Math.sqrt(64);
Math.abs(-4.7);
Math.random();
if (condition) {
// block of code to be executed if the condition is true
}
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
variable = (condition) ? expressionTrue : expressionFalse;
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
while (condition) {
// code block to be executed
}
do {
// code block to be executed
}
while (condition);
for (int i = 0; i < 5; i++) {
}
for (type variableName : arrayName) {
// code block to be executed
}
break;
continue;
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
public class Main {
static void myMethod() {
// code to be executed
}
}
int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)
public class Main {
}
Main myObj = new Main();
// Static method
static void myStaticMethod() {
}
// Public method
public void myPublicMethod() {
}
// Main method
public static void main(String[] args) {
}
Modifier | Description |
---|---|
public |
The class is accessible by any other class |
default | The class is only accessible by classes in the same package. This is used when you don't specify a modifier. |
Modifier | Description |
---|---|
public |
The code is accessible for all classes |
private |
The code is only accessible within the declared class |
default | The code is only accessible in the same package. This is used when you don't specify a modifier. |
protected |
The code is accessible in the same package and subclasses |
Modifier | Description |
---|---|
final |
The class cannot be inherited by other classes |
abstract |
The class cannot be used to create objects |
Modifier | Description |
---|---|
final |
Attributes and methods cannot be overridden/modified |
static |
Attributes and methods belongs to the class, rather than an object |
abstract |
Can only be used in an abstract class, and can only be used on methods. The method does not have a body, for example abstract void run();. The body is provided by the subclass (inherited from) |
transient |
Attributes and methods are skipped when serializing the object containing them |
synchronized |
Methods can only be accessed by one thread at a time |
volatile |
The value of an attribute is not cached thread-locally, and is always read from the "main memory" |
final double PI = 3.14;
static void myStaticMethod() {
}
public abstract void study(); // abstract method
public class Person {
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package
package mypack;
class Vehicle {
}
class Car extends Vehicle {
}
abstract class Animal {
public abstract void animalSound();
}
}
enum Level {
LOW,
MEDIUM,
HIGH
}
Method | Description |
---|---|
nextBoolean() |
Reads a boolean value from the user |
nextByte() |
Reads a byte value from the user |
nextDouble() |
Reads a double value from the user |
nextFloat() |
Reads a float value from the user |
nextInt() |
Reads a int value from the user |
nextLine() |
Reads a String value from the user |
nextLong() |
Reads a long value from the user |
nextShort() |
Reads a short value from the user |
import java.util.Scanner; // Import the Scanner class
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
String userName = myObj.nextLine(); // Read user input
}
}
Class | Description |
---|---|
LocalDate |
Represents a date (year, month, day (yyyy-MM-dd)) |
LocalTime |
Represents a time (hour, minute, second and nanoseconds (HH-mm-ss-ns)) |
LocalDateTime |
Represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns) |
DateTimeFormatter |
Formatter for displaying and parsing date-time objects |
import java.time.LocalDate; // import the LocalDate class
public class Main {
public static void main(String[] args) {
LocalDate myObj = LocalDate.now(); // Create a date object
System.out.println(myObj); // Display the current date
}
}
import java.util.ArrayList; // import the ArrayList class
ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object
cars.add("Volvo");
cars.get(0);
cars.set(0, "Opel");
cars.remove(0);
cars.clear();
cars.size();
for (int i = 0; i < cars.size(); i++) {
System.out.println(cars.get(i));
}
Collections.sort(cars); // Sort cars
Method | Description |
---|---|
addFirst() | Adds an item to the beginning of the list. |
addLast() | Add an item to the end of the list |
removeFirst() | Remove an item from the beginning of the list. |
removeLast() | Remove an item from the end of the list |
getFirst() | Get the item at the beginning of the list |
getLast() | Get the item at the end of the list |
// Import the LinkedList class
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList cars = new LinkedList();
}
}
import java.util.HashMap; // import the HashMap class
HashMap<String, String> capitalCities = new HashMap<String, String>();
capitalCities.put("England", "London");
capitalCities.get("England");
capitalCities.remove("England");
capitalCities.clear();
capitalCities.size();
// Print keys
for (String i : capitalCities.keySet()) {
System.out.println(i);
}
import java.util.HashSet; // Import the HashSet class
HashSet<String> cars = new HashSet<String>();
cars.add("Volvo");
cars.contains("Mazda");
cars.remove("Volvo");
capitalCities.clear();
cars.size();
for (String i : cars) {
System.out.println(i);
}
import java.util.Iterator;
// Get the iterator
Iterator<String> it = cars.iterator();
// Print the first item
System.out.println(it.next());
while(it.hasNext()) {
}
while(it.hasNext()) {
Integer i = it.next();
if(i < 10) {
it.remove();
}
}
Primitive Data Type | Wrapper Class |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
boolean | Boolean |
char | Character |
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}finally {
// After 'try catch' is finished
}
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
Expression | Description |
---|---|
[abc] | Find one character from the options between the brackets |
[^abc] | Find one character NOT between the brackets |
[0-9] | Find one character from the range 0 to 9 |
Metacharacter | Description |
---|---|
| | Find a match for any one of the patterns separated by | as in: cat|dog|fish |
. | Find just one instance of any character |
^ | Finds a match as the beginning of a string as in: ^Hello |
$ | Finds a match at the end of the string as in: World$ |
\d | Find a digit |
\s | Find a whitespace character |
\b | Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b |
\uxxxx | Find the Unicode character specified by the hexadecimal number xxxx |
Quantifier | Description |
---|---|
n+ | Matches any string that contains at least one n |
n* | Matches any string that contains zero or more occurrences of n |
n? | Matches any string that contains zero or one occurrences of n |
n{x} | Matches any string that contains a sequence of X n's |
n{x,y} | Matches any string that contains a sequence of X to Y n's |
n{x,} | Matches any string that contains a sequence of at least X n's |
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("w3schools", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("Visit W3Schools!");
boolean matchFound = matcher.find();
if(matchFound) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}
public class Main extends Thread {
public void run() {
System.out.println("This code is running in a thread");
}
}
public class Main implements Runnable {
public void run() {
System.out.println("This code is running in a thread");
}
}
Main thread = new Main();
thread.start();
Method | Type | Description |
---|---|---|
canRead() |
Boolean | Tests whether the file is readable or not |
canWrite() |
Boolean | Tests whether the file is writable or not |
createNewFile() |
Boolean | Creates an empty file |
delete() |
Boolean | Deletes a file |
exists() |
Boolean | Tests whether the file exists |
getName() |
String | Returns the name of the file |
getAbsolutePath() |
String | Returns the absolute pathname of the file |
length() |
Long | Returns the size of the file in bytes |
list() |
String[] | Returns an array of the files in the directory |
mkdir() |
Boolean | Creates a directory |
import java.io.File; // Import the File class
File myObj = new File("filename.txt"); // Specify the filename
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors
public class CreateFile {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
import java.io.FileWriter; // Import the FileWriter class
import java.io.IOException; // Import the IOException class to handle errors
public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
public class ReadFile {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
import java.io.File; // Import the File class
public class GetFileInfo {
public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.exists()) {
System.out.println("File name: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
System.out.println("Writeable: " + myObj.canWrite());
System.out.println("Readable " + myObj.canRead());
System.out.println("File size in bytes " + myObj.length());
} else {
System.out.println("The file does not exist.");
}
}
}
import java.io.File; // Import the File class
public class DeleteFile {
public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.delete()) {
System.out.println("Deleted the file: " + myObj.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
import java.io.File;
public class DeleteFolder {
public static void main(String[] args) {
File myObj = new File("C:\\Users\\MyName\\Test");
if (myObj.delete()) {
System.out.println("Deleted the folder: " + myObj.getName());
} else {
System.out.println("Failed to delete the folder.");
}
}
}
Keyword | Description |
---|---|
abstract | A non-access modifier. Used for classes and methods: An abstract class cannot be used to create objects (to access it, it must be inherited from another class). An abstract method can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from) |
assert | For debugging |
boolean | A data type that can only store true and false values |
break | Breaks out of a loop or a switch block |
byte | A data type that can store whole numbers from -128 and 127 |
case | Marks a block of code in switch statements |
catch | Catches exceptions generated by try statements |
char | A data type that is used to store a single character |
class | Defines a class |
continue | Continues to the next iteration of a loop |
const | Defines a constant. Not in use - use final instead |
default | Specifies the default block of code in a switch statement |
do | Used together with while to create a do-while loop |
double | A data type that can store whole numbers from 1.7e−308 to 1.7e+308 |
else | Used in conditional statements |
enum | Declares an enumerated (unchangeable) type |
exports | Exports a package with a module. New in Java 9 |
extends | Extends a class (indicates that a class is inherited from another class) |
final | A non-access modifier used for classes, attributes and methods, which makes them non-changeable (impossible to inherit or override) |
finally | Used with exceptions, a block of code that will be executed no matter if there is an exception or not |
float | A data type that can store whole numbers from 3.4e−038 to 3.4e+038 |
for | Create a for loop |
goto | Not in use, and has no function |
if | Makes a conditional statement |
implements | Implements an interface |
import | Used to import a package, class or interface |
instanceof | Checks whether an object is an instance of a specific class or an interface |
int | A data type that can store whole numbers from -2147483648 to 2147483647 |
interface | Used to declare a special type of class that only contains abstract methods |
long | A data type that can store whole numbers from -9223372036854775808 to 9223372036854775808 |
module | Declares a module. New in Java 9 |
native | Specifies that a method is not implemented in the same Java source file (but in another language) |
new | Creates new objects |
package | Declares a package |
private | An access modifier used for attributes, methods and constructors, making them only accessible within the declared class |
protected | An access modifier used for attributes, methods and constructors, making them accessible in the same package and subclasses |
public | An access modifier used for classes, attributes, methods and constructors, making them accessible by any other class |
requires | Specifies required libraries inside a module. New in Java 9 |
return | Finished the execution of a method, and can be used to return a value from a method |
short | A data type that can store whole numbers from -32768 to 32767 |
static | A non-access modifier used for methods and attributes. Static methods/attributes can be accessed without creating an object of a class |
strictfp | Restrict the precision and rounding of floating point calculations |
super | Refers to superclass (parent) objects |
switch | Selects one of many code blocks to be executed |
synchronized | A non-access modifier, which specifies that methods can only be accessed by one thread at a time |
this | Refers to the current object in a method or constructor |
throw | Creates a custom error |
throws | Indicates what exceptions may be thrown by a method |
transient | A non-accesss modifier, which specifies that an attribute is not part of an object's persistent state |
try | Creates a try...catch statement |
var | Declares a variable. New in Java 10 |
void | Specifies that a method should not have a return value |
volatile | Indicates that an attribute is not cached thread-locally, and is always read from the "main memory" |
while | Creates a while loop |
Method | Description | Return Type |
---|---|---|
charAt() | Returns the character at the specified index (position) | char |
codePointAt() | Returns the Unicode of the character at the specified index | int |
codePointBefore() | Returns the Unicode of the character before the specified index | int |
codePointCount() | Returns the number of Unicode values found in a string. | int |
compareTo() | Compares two strings lexicographically | int |
compareToIgnoreCase() | Compares two strings lexicographically, ignoring case differences | int |
concat() | Appends a string to the end of another string | String |
contains() | Checks whether a string contains a sequence of characters | boolean |
contentEquals() | Checks whether a string contains the exact same sequence of characters of the specified CharSequence or StringBuffer | boolean |
copyValueOf() | Returns a String that represents the characters of the character array | String |
endsWith() | Checks whether a string ends with the specified character(s) | boolean |
equals() | Compares two strings. Returns true if the strings are equal, and false if not | boolean |
equalsIgnoreCase() | Compares two strings, ignoring case considerations | boolean |
format() | Returns a formatted string using the specified locale, format string, and arguments | String |
getBytes() | Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array | byte[] |
getChars() | Copies characters from a string to an array of chars | void |
hashCode() | Returns the hash code of a string | int |
indexOf() | Returns the position of the first found occurrence of specified characters in a string | int |
intern() | Returns the canonical representation for the string object | String |
isEmpty() | Checks whether a string is empty or not | boolean |
lastIndexOf() | Returns the position of the last found occurrence of specified characters in a string | int |
length() | Returns the length of a specified string | int |
matches() | Searches a string for a match against a regular expression, and returns the matches | boolean |
offsetByCodePoints() | Returns the index within this String that is offset from the given index by codePointOffset code points | int |
regionMatches() | Tests if two string regions are equal | boolean |
replace() | Searches a string for a specified value, and returns a new string where the specified values are replaced | String |
replaceFirst() | Replaces the first occurrence of a substring that matches the given regular expression with the given replacement | String |
replaceAll() | Replaces each substring of this string that matches the given regular expression with the given replacement | String |
split() | Splits a string into an array of substrings | String[] |
startsWith() | Checks whether a string starts with specified characters | boolean |
subSequence() | Returns a new character sequence that is a subsequence of this sequence | CharSequence |
substring() | Returns a new string which is the substring of a specified string | String |
toCharArray() | Converts this string to a new character array | char[] |
toLowerCase() | Converts a string to lower case letters | String |
toString() | Returns the value of a String object | String |
toUpperCase() | Converts a string to upper case letters | String |
trim() | Removes whitespace from both ends of a string | String |
valueOf() | Returns the string representation of the specified value | String |
Method | Description | Return Type |
---|---|---|
abs(x) | Returns the absolute value of x | double|float|int|long |
acos(x) | Returns the arccosine of x, in radians | double |
asin(x) | Returns the arcsine of x, in radians | double |
atan(x) | Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians | double |
atan2(y,x) | Returns the angle theta from the conversion of rectangular coordinates (x, y) to polar coordinates (r, theta). | double |
cbrt(x) | Returns the cube root of x | double |
ceil(x) | Returns the value of x rounded up to its nearest integer | double |
copySign(x, y) | Returns the first floating point x with the sign of the second floating point y | double |
cos(x) | Returns the cosine of x (x is in radians) | double |
cosh(x) | Returns the hyperbolic cosine of a double value | double |
exp(x) | Returns the value of Ex | double |
expm1(x) | Returns ex -1 | double |
floor(x) | Returns the value of x rounded down to its nearest integer | double |
getExponent(x) | Returns the unbiased exponent used in x | int |
hypot(x, y) | Returns sqrt(x2 +y2) without intermediate overflow or underflow | double |
IEEEremainder(x, y) | Computes the remainder operation on x and y as prescribed by the IEEE 754 standard | double |
log(x) | Returns the natural logarithm (base E) of x | double |
log10(x) | Returns the base 10 logarithm of x | double |
log1p(x) | Returns the natural logarithm (base E) of the sum of x and 1 | double |
max(x, y) | Returns the number with the highest value | double|float|int|long |
min(x, y) | Returns the number with the lowest value | double|float|int|long |
nextAfter(x, y) | Returns the floating point number adjacent to x in the direction of y | double|float |
nextUp(x) | Returns the floating point value adjacent to x in the direction of positive infinity | double|float |
pow(x, y) | Returns the value of x to the power of y | double |
random() | Returns a random number between 0 and 1 | double |
round(x) | Returns the value of x rounded to its nearest integer | int |
rint(x) | Returns the double value that is closest to x and equal to a mathematical integer | double |
signum(x) | Returns the sign of x | double |
sin(x) | Returns the sine of x (x is in radians) | double |
sinh(x) | Returns the hyperbolic sine of a double value | double |
sqrt(x) | Returns the square root of x | double |
tan(x) | Returns the tangent of an angle | double |
tanh(x) | Returns the hyperbolic tangent of a double value | double |
toDegrees(x) | Converts an angle measured in radians to an approx. equivalent angle measured in degrees | double |
toRadians(x) | Converts an angle measured in degrees to an approx. angle measured in radians | double |
ulp(x) | Returns the size of the unit of least precision (ulp) of x | double|float |