Basics of Java
Some of the basic concepts when getting started with Java!
0. Printing Stuff
System.out.println(statement);
Prints out whatever the statement is to the console. This is Java’s version of puts/prints/console.log.
- Variables
Variables are written using camel case.
variable variableTwo
When declaring a variable it you should include its data type. There are 8 basic data types, a byte (8 bit signed integer between -128 to 127), a short (16 bit signed integer between -32,768 to 32,767), an int (32 bit signed integer between -2³¹ to 2³¹-1), a long (64 bit signed integer between -2⁶³ to 2⁶³-1), a float (decimal number), a double (a bigger version of the float), a boolean (true/false), and a char (single character)
int number = 10;
float secondNumber = 2.5f;
boolean result = true;
char letter = "C";
String sentence = "This is a sentence!";
- Float also requires you have an f at the end of the number
- String is not actually one of the primitive data types, but has special support from the String class. A string variable is immutable (cannot be changed after it is declared
When declaring a variable, if it is declared without a static field, it is an instance variable.
int speed = 5;
An instance variable is a property that belongs to one specific instance of a class, in this case a single sprinter might have a speed of 5.
If static is declared the variable is a class variable.
static int allSprinters = 8;
A class variable is a variable that belongs to the class as a whole, rather than to an individual instance. In this case the total amount of sprinters in the sprinter class belongs to the Class.
More on what a Class is will be covered later on.
The word final can be included when declaring a variable, turning it into a constant variable that cannot be changed or reassigned.
final int legs = 2;
- (I mean I guess you can change that technically…)
2. Arrays
When you declare an array, you have to declare the data types it will contain, then you have to specify it’s length, which is then fixed.
int[] = newArray;
# declare newArray as an array of integers
newArray = new int[10];
# set the length of newArray to 10
# can combine both steps
int[] newArray = new int[10];
Each element in an array has an index starting at 0, and can be accessed by typing arrayName[indexNumber] or have a value assigned by typing arrayName[indexNumber] = value.
So after declaring an array and its length, you can fill it up by individually assigning values to each index number. If you know the values initially you can include them when declaring the array.
int[] = newArray;
int[] newArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
# or all at once
int[] newArray = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Array Methods
- arrayName.length returns the total number of elements
- To copy an array use:
public static void arraycopy(array1, startPosition,
array2, startPosition2, copyAmount);
int array1 = {1, 2, 3, 4, 5, 6, 7, 8}
int array2 = {10, 11, 12, 13, 14, 15, 16}
public static void arraycopy(array1, 3, array2, 1, 2);
# would return {10, 4, 5, 13, 14, 15, 16}
3.Operators
Arithmetic Operators
Standard =, +, -, *, /, and %.
int number = 5;
1 + 1 = 2;
2 - 1 = 1;
2 * 2 = 4;
4 / 2 = 2;
5 % 2 = 1;
% gives the remainder after diving the first number by the second
Unary Operators
-, ++, --, !
int number = 5;
boolean variable2 = true;
-number is -5
number++ is 6
number-- is 4
!variable2 is false
You can put ++ and -- before or after something. If you put it before the addition/subtraction will be done before the value is evaluated in whatever expression/formula its part of, while if you do it after it will increment after its evaluated.
Equality and Relational Operators
== (equals to), != (not equals to), > (greater than), ≥ (greater than or equal than), < (less than), ≤ (less than or equal than). Using these operators will return true or false if the condition is met.
1 == 1;
#true
1 == 5;
#false
1 != 5;
#true
1 != 1;
#false
5 > 1;
#true
1 > 5;
#false
1 >= 1;
#true
1 >= 5;
#false
1 < 5;
#true
5 < 1;
#false
1 <= 5;
#true
5 <= 1;
#false
Conditional Operators
&& (and), || (or), ?: (ternary operator)
(5 > 3) && (5 > 1)
#true
(5 > 3) && (5 > 7)
#false
(5 > 3) || (5 > 1)
#true
(5 > 3) ||(5 > 7)
#true
(5 > 9) || (5 > 1)
#true
(5 > 9) ||(5 > 7)
#false
if (condition) ? result1 : result2
# the equivalent of if condition is true return result1, else return result2
4. Expression, Statement, Block
An expression is pretty broad, it is just a combination of numbers, variables, and operators.
1 + 2 a * 5 / 2
A statement is basically an expression with a ; at the end of it, signifying that it is a complete unit.
1 + 2; a * 2;
A block is astatement inside some {}
if (condition) {
a * 2;
} else {
block2;
}
5. Control Flow
Control flow is the use of decision making statements (if, then, else, switch), looping statements (for, while, do-while) and branching statements (break, continue, return).
We came across an example of control flow from earlier.
int number = 76
String result
if (number == 100) {
result = "Genius!";
} else if (90) {
result = "Good job!";
} else if (80) {
result = "OK I guess";
} else if (65) {
result = "Close call...";
} else {
result = "That's a paddlin";
}
Starting from top to bottom, each condition will be evaluated. If the condition is met, the block following it will be performed. If not, it will move on and evaluate the next condition. If none of the specified conditions are met it will do whatever is next to “else”.
Switch is similar but has a slightly different format.
int number = 76
String result
switch (number) {
case 100: result = "Genius!";
break;
case 90: result = "Good job!";
break;
case 80: result = "OK I guess";
break;
case 65: result = "Close call...";
break;
default: result = "That's a paddlin";
break;
}
The variable inside the () will be evaluated against each of the cases, and if the the values match that case’ action (switch block) will be performed. Even after matching a case all subsequent cases will be evaluated until a break is encountered, so breaks are in every case. The default is for when none of the other case statements are matched, it is similar to “else” in the other format.
While loop
while (condition) {
statement
}
While the condition evaluates as true, the block will be run.
Do-while loop
do {
statement
} while (expression)
Similar to the while loop, but the while expression is evaluated after the statement is run, so it will always run at least once.
For loop
for (int i = 0; i < 10; i++) {
statement
}
This loop is for performing the statement 10 times. i is a counter variable that starts at 0, next to it is the condition for when to stop executing the loop (i < 10 in this case), and next to that is what to do after each iteration (increment i in this case). This makes it so after every loop i will increment by 1, and by the time it reaches 10, i < 10 will be false and it will stop running.
“break” will break out of a loop, “continue” while skip to the part where the expression for run the loop is evaluated, and “return” exits from the current method and returns to when it was evoked.
6. Classes
To declare a class is:
modifier class ClassName extends ParentClass implements Interface{
field, constructor, methods
}
the modifier is public (field accessible to other classes) or private (field only accessible within own class) the parent class is included if the current class inherits from a different class, and you can have it implement an interface (this will come later).
A basic class would be:
class Hero {
}
Member variables inside a class are called fields, they are variables accessible to any instance of the class.
modifier dataType name
They would be included at the top of a class.
public class Hero {
public String name
public int rating
public int power
}
Typically member variables are set to private, and public methods are added so they can be accessed.
public class Hero {
private String name;
private int rating;
private int power;
public Hero(String name, int rating, int power) {
name = name;
rating = rating;
power = power;
}
public string getName() {
return name;
}
public int getRating() {
return rating;
}
public int getPower() {
return power;
}
public void increaseRating(number) {
rating ++ number;
}
public void strengthen(number) {
strengthen ++ number;
}
}
The part after the field variables is the constructor.
public Hero(String name, int rating, int power) {
name = name;
rating = rating;
power = power;
}
This allows us to create a new hero, which takes in a name, a rating, and a power, which is used to make a new instance of a hero with those attributes.
Hero allMight = new Hero("All Might", 10, 10)
Methods are declared with a modifier and the data type they return, put void if they don’t return anything. Here we do not have direct access to a hero’s attributes, but we have methods that allow us to get them as well as modify them.
If you don’t know how many argument’s are going to be passed in, you can use elipses (called varargs).
public printTeam(teamName ...Heroes) {
System.out.print("The team" + teamName + "consists of" + Heroes)
printTeam("Justice League", "Superman")
# this will print out "The team Justice League consists of ['Superman']"
printTeam("Justice League", "Superman", "Spiderman")
# this will print out "The team Justice League consists of ['Superman', 'Spiderman']"
The … Heroes has all the arguments passed in after teamName as as part of the Heroes array.
There are 3 parts to creating an object.
- Declaration (associating a variable name with an object type)
className variableName Hero allMight
- instantiation (using new keyword to allocate memory for an object), and following that initialization (calling the constructor),
Hero allmight = new Hero("All Might", 10, 10)
You can access an objects field’s by calling
object.fieldName
allMight.name returns "All Might"
You can call a method on an object with:
object.methodName(arguments)
allMight.strengthen(100)
# this will increase allMight's power value to 110
allMight.power will now return 110
7. This
What is “this”?
- Within an instance method or constructor this refers to the object the method is being called on.
Earlier we wrote our constructor as:
public Hero(String name, int rating, int power) {
name = name;
rating = rating;
power = power;
}
But you could also write it as:
public Hero(String name, int rating, int power) {
this.name = name;
this.rating = rating;
this.power = power;
}
Here this refers to the object being passed in those parameters, and it is having its attributes set to the parameters passed in.
- Within a constructor this can be used to call another constructor that is in the same class. This is called “explicit constructor invocation”.
public class hero {
private String name;
private int rating;
private int power;
public Hero() {
this("Unnamed Scrub", 0, 0);
}
public Hero(name) {
this(name, 0, 0);
}
public Hero(String name, int rating, int power) {
this.name = name;
this.rating = rating;
this.power = power;
}
}
Over here the “this”s inside the constructors call the final constructor with default parameters when it doesn’t take them as arguments (“unnamed scrub” and 0, 0) in the first one and the name parameter with 0, 0 for the other one.
8. Class Variables
While member variables can be attributes that every instance of the class possesses such as name or rating in our super hero case, a class member variable is a variable associated with the class. A class variable is declared using the word “static”.
public class Hero {
private static int totalHeroes = 0
public Hero(String name, int rating, int power) {
this.name = name;
this.rating = rating;
this.power = power;
totlHeroes ++
}
public int getTotalHeroes() {
return totalHeroes;
}
}
The constructor now increments the totalHeroes class variable whenever a new hero is created. A class method can be evoked by calling
Class.method
Hero.totalHeroes returns the totalHeroes class variable
Aside from initializing class fields by directly setting them equal to something, you can also initialize them with a block or set them equal to the return value of a method.
private static String initializeName() {
block
}
private static = String methodName
9. Nested Classes
A nested class is a class defined within another class.
class Hero {
...
static class sClassHero{
...
}
}
A nested class can be static (static nested class) or non-static (inner class). An inner class has access to members of its enclosing class, while a static nested class does not.
10. Interfaces
An interface is a reference type (data type based on class rather than a primitive data type) that is used for classes that have shared similarities. An interface can contain method signatures (method name and parameters), default methods, static methods (class method) and constant definitions. For example, a member of the Hero class and a member of the Villain class both would share the ability to punch. You could technically have a bigger class class Fighters with the punch method and have Hero and Villain both be a subclass, but that is a little odd, since there isn’t really any need or focus on Fighter class. So instead you make an interface that contains the name of methods that both the Hero class and Villain class implement.
public interface Fighter {
string setNewRating(target, rating);
}
Would be the interface. The method and its parameters are written but not the actual code it will run.
public class hero implements Fighter {
private String name;
private int rating;
private int power;
string setNewRating(target, rating) {
target.rating = rating
}
}
What it does is defined inside the class that implements the interface.
11. extend interface
If you have an interface
public interface Fight {
void punch(puncher, punchee);
void kick(kicker, kickee);
}
and you wish to add a line to it, anything implementing your old interface will break. To prevent this you create a new interface that extends the old one
public interface SuperFight extends Fight{
void kamehameha(blaster, futureDeadGuy);
}
This allows someone to use your old interface, or to upgrade to your new one. You can also add the new methods as default methods, which don’t have to be compiled
public interface Fight {
void punch(puncher, punchee);
void kick(kicker, kickee);
default void kamehameha(blaster, futureDeadGuy){
method
}
}
Note that for the default method you need to write more than just the method name and attributes.
12. Inheritance
A class can inherit fields and methods from another class. The inheriting class is called the subclass, and the other one is called the superclass.
public class SClassHero extends Hero {
}
The subclass inherits all public fields, methods, and nested classes from its superclass. Private members are not inherited, although they can be accessed through public methods. For a subclass you can define new fields and methods, as well as overwrite a method from the super class by giving it the same signature(method name and parameters), as well as add a constructor that invokes the constructor form the superclass.
An instance method with the same signature will override that of a super class. If it is a class method that share a signature the one in the subclass hides the one from the superclass. When an instance method is being run (overridden) from the new class on an object the class of the new object will be looked at, and the method from the class of that object will be used. For static methods (hidden) the compiler will run the static method from whatever the declared type is, even if it is wrong. If there is a static method and a non-static method with the same signature the result will be an error.
Instance methods override interface default methods. Instances of subclasses can have different behaviors from instances of a parent class or from another subclass with the same parent due to overriding.
When a method is overridden you can access the method form the superclass by calling
super.methodName
You can call the constructor of a super class by calling
public SuperClass(parameter1, parameter2, parameter 7) {
super(parameter1, parameter2);
attributeName = parameter7;
}
Invocation of a superclass constructor must be the first line in the subclass constructor.
super(parameter list)
Method overloading is the process of having multiple functions with the same name, but that are differentiated by the amount of arguments that they take.
public printMethod(parameter1) {
System.out.println(parameter1)
}
public2 printMethod(parameter1, parameter2) {
System.out.println("SORRY SIR THIS PROGRAM ONLY PRINTS ONE THING AT A TIME!")
}
In this case both methods are called “printMethod” but one takes one argument and one takes two. So if you call the method with one argument it will know that you are calling the first one and print your argument, but if you call it with two it will call the second one and instead “SORRY SIR THIS PROGRAM ONLY PRINTS ONE THING AT A TIME!”
The object class sits at the top of all objects, and they all inherit from it. This allows you to run the following methods on any instance of an object.
object1.clone()
# Creates and returns a copy of this object.
object1.equals(object)
# indicates whether another object is equal to this one
object1.finalize()
# when there are no more references to an object this calls it to the big object yard in the sky
object1.getClass()
# returns the class of an object
object1.hashCode()
# returns the hash code value for the object
object1.toString()
# returns a string representation of the object (useful for debugging)
Final can be added to a method to prevent it from being overridden by subclasses. You can also declared an entire class final, in which case it cannot get a subclass.
13. Numbers and Strings
Most of the times numbers are primitive types (like int) but you can turn them into objects by wrapping them with a wrapper type (Byte, Double, Float, Integer, Long, Short). You can do this by creating it as part of the class you want it to be used in.
Integer i = new Integer(num)
# instead of
int i = 57
The following are various methods that can be called on numbers and strings.
byte byteValue()
short shortValue()
int intValue()
long longValue()
float floatValue()
double doubleValue()
#Converts the value of a number object back into primitive form.
num1.compareTo(num2)
#If num2 is bigger it will return -1, if they are equal it will return 0, and if num1 is bigger it will return 1.
num1.equals(num2)
#Similar to ==, but == checks if two things point to the same location in memory, while .equals compares the values.
parseInt(stringNumber)
#Returns value of string as an integer.
Integer.valueOf(stringNum)
#Returns value of string as an integer.
Integer.valueOf(numObj)
#Returns value of number object as an integer.
String.toString(num)
#Returns string object of value of num.
String.valueOf(stringNum)
#Returns value of string as an integer.
String.valueOf(numObj)
#Returns value of number object as a string.
Math.abs(num)
#Returns the absolute value of num.
Math.ceil(num)
#Returns smallest integer greater than or equal to num.
Math.floor(num)
#Returns greatest integer less than or equal to num.
Math.round(num)
#Returns closest long or round, depending on the data type of num.
Math.max(num1 num2)
#Returns larger of two arguments.
Math.min(num1 num2)
#Returns smaller of two arguments.
Math.log(num)
#Returns the log of num.
Math.sqrt(num)
#Returns the square root of num.
Math.sin(num)
Math.cos(num)
Math.tan(num)
#Returns sin/cosine/tangent of num.
Math.random()
#Returns a number between 0.0 and 1.0. You will generally multiply the result of this by something to get an integer, such as multiplying the result by 10 to get a number between 1 and 10.
14. Char
Most of the time a char is of the primitive char type. Like numbers from earlier, you can wrap it in the char class so it becomes an object.
Character ch = new Character('a')
Character class is immutable.
Character.isLetter(char)
# determines if char is a letter
Character.isDigit(char)
# determines if char is a digit
Character.isWhitespace(char)
# determines if char is white space
Character.isUpperCase(char)
# determines if char is a upper case
Character.isLowerCase(char)
# determines if char is a lower case
Character.toUpperCase(char)
# Transforms char to upper case
Character.toLowerCase(char)
# Transforms char to lower case
Character.toString(char)
# Transforms char to string
There are a lot of escape sequences where typing in “\” followed by a letter inserts something in between quotes.
\t
# insert tab
\b
# insert backspace
\n
# insert new line
\r
# insert carriage
\f
# insert formfeed
\'
# insert single quote
\"
# insert double quote
\\
# insert backslash
15. Strings
String are part of the String class.
string1.length()
# returns amount of characters in a string
string1.concat(string2)
# used to add string2 to the end of string1
# can also be done with just string1 + string2
Integer.parseInt(stringNumber)
Integer.valueOf(stringNumber)
# both returns stringNumber as an integer
String.valueOf(num)
Integer.toString(num)
# both returns num as a string
string1.charAt(num)
# returns string form index of num (index starts at 0)
string.substring(num1, num2)
# returns a substring starting at num1 and lasting to num2
string.substring(num1)
# returns a substring starting at num1 and lasting until the end
string1.split(expression)
# splits string into an array of strings seperated by the expression
string1.split(expression, num)
# splits string into an array of strings seperated by the expression with num being the amount length of the array
string1.subsequence(num1, num2)
# returns a charsequence starting at num1 and lasting to num2
string1.trim()
# returns a string1 with no white spaces in front or back
string1.toLowerCase()
# returns string1 converted to all lower case
string1.toUpperCase()
# returns string1 converted to all upper case
string1.indexOf(char)
#returns index of first char
string1.lastIndexOf(char)
#returns index of last char
string1.indexOf(string2)
#returns index of first instance of first char of string2
string1.lastIndexOf(string2)
#returns index of last instance of first of string2
string1.contains(string2)
#returns true if string1 contains string2, otherwise returns false
string1.replace(char1, char2)
#returns string with all of char1 replaced by char2
string1.replace(string2, string3)
#returns string with all of string2 replaced by string3
string1.replace(regex, string2)
#returns string with anything that matches the regular expression replaced with string2
string1.replaceFirst(regex, string2)
#returns string with first instance that matches the regular expression replaced with string2
string1.endsWith(string2)
#returns true if string ends with string2
string1.startsWith(string2)
#returns true if string starts with string2
string1.compareTo(string2)
#returns 1 is lexographically greater than string 2 returns a positive integer, a negative if its less, and 0 if its the same
string1.compareToIgnoreCase(string2)
#same as above but ignores case
string1.equals(string2)
#returns true if same sequence of characters
string1.matches(regex)
#returns true if string mathces regular expression
16. Stringbuilder class
Objects here are treated like arrays containing a sequence of characters.
new StringBuilder
# creates empty string builder with capacity to hold 16 elements
Stringbuilder(string1)
# creates a stringbuilder object with the same characters as string1 + empty 16 elements trailing
string1.charAt(num)
#returns char at index num for string1
string1.append(string2)
# converts string2 to string and adds to the end of string1
string1.delete(num1 num2)
# deletes subsequence from num1 to num2-1 (inclusive)
string1.deleteCharAt(num2)
# deletes subsequence at index num
string1.insert(num1, string2)
# inserts string2 into string1 after index num1
string1.replace(num1, num2, string2)
# replaces subsequence from num1 to num2 with string2
string1.setCharAt(num, char)
# replaces character at index num with char
string1.reverse()
# reverses sequence of string1
string1.toString()
# returns a string with the same character sequence as string1
17. Package
A package is a namespace that organizes a set of related classes and interfaces. To create a package, choose a name and include
package packageName;
at the top of every file that has a type that you want to include in the package.
To use an entire package import it with
import packageName.*;
To import a specific class from a package do
import packageName.ClassName;