Java + OOP Concept Cheat Sheet: by Via
Java + OOP Concept Cheat Sheet: by Via
Java + OOP Concept Cheat Sheet: by Via
Start your Java day with Hello World program Operand What they do for (int i: someArray) {}
public class HelloWorld { while (something) {}
= Assign value
public static void main(String[] do {something} while (true)
== Check value/address similarity
args) {
> More than
// Prints "Hello, World" to the Prime number function
>= More than or equals
terminal window.
if (n < 2) { return false; }
System.out.println("Hello, World"); >>> Move bit to the right by
for (int i=2; i <= n/i; i++)
} ++ Increment by 1
if (n%i == 0) return false;
}
inverse of these operands still working the return true;
When you want to run the program, choose this same.
class as main class. For example : != is not equal returns a boolean
Compile from single class up HelloWorld Defining new variable attributes String pool is created to make the same value
class int x = 12; string use the same address. By doing that, it
javac HelloWorld.java will save memory and time for compiler to do
int x; // will be defined as 0
java HelloWorld stuff
Define by creating new instances
Basic testing
Compile from multiple classes and choose String x = new String;
String s1 = "Hello World";
main class
Type Casting (decreasing bit use)
javac *.java String s2 = "Hello World;
Expanding data types will not require type
java HelloWorld // HelloWorld is Check it using "=="
casting. Narrowing does.
your preferred main class System.out.println(s1 == s2);
double x = 10; // Expanding data
True
types
"==" will check its address
Variables int y = (int) 10.222222; //
Allocate a new address using new
Type Default Memory Allocation Narrowing data types
String s1 = "Hello World";
Value
String s2 = new String;
Conditions
byte 0 8 bits s2 = "Hello World";
short 0 16 bits If statement System.out.println(s1 == s2);
if (statement) {}
int 0 32 bits False
If - else statement
Allocate new address by changing its value
long 0L 64 bits
if (statement) {} else{} String s1 = "Hello World";
float 0.0F 32 bits (decimal)
String s2 = "Hello World";
double 0.00D 64 bits (decimal) Switch
s2 = "Hello Thailand";
boolean False varies on impliment
switch (num) { System.out.println(s1 == s2);
String NULL depends on character case 1: doSomething(); False
count
break;
char \u0000 16 bits (unicode) default: doThis();
break;
}
Naming should be regulated for easier But will be created automatically by not writing
recogition from others any constru
ctor
Use Upper Camel Case for classes: Create an argument-defined constructor
VelocityResponseWriter <modifier> Person (String name)
Use Lower Case for packages: {
com.company.project.ui this.name = name;
Use Lower Camel Case for variables: }
studentName
Use Upper Case for constants: Abstract Class
- Java uses <default> modifier when not
MAX_PARAMETER_COUNT = 100
assigning any. Abstract is a type of class but it can consist of
Use Camel Case for enum class names
- public modifier allows same class access incomplete methods.
Use Upper Case for enum values
- Works in inherited class means itself and the Create new abstract
Don't use '_' anywhere except constants and
classes that inherit from it. <access_modifier> abstract class
enum values (which are constants).
HelloWorld () {}
Attribute modifier
Receiving user input
Attribute Access Grants Interface
There is normally 2 ways to receive user
Type
keyboard input Interface is different from constructor. It
1. java.util.Scanner Private Allows only in class where variable consists of incomplete assignments
Scanner x = new belongs Interface allows you to make sure that any
Scanner(System.in); Public Allows any class to have this inherited class can do the following methods.
attribute (It's like a contract to agree that this thing must
String inputString = x.next(); //
be able to do this shit.) The method is then
for String type input Static Attribute that dependent on class
completed in the class that implements it.
int inputInteger = x.nextInt(); // (not object)
Creating a new interface
for Integer type input Final Defined once. Does not allow any interface Bicycle {
2. String[] args from public static void main() change/inheritance
void speedUp (int increment);
NOTE: args is already in a array. It can }
receives unlimited amount of arguments. Methods
----
String inputString = args[0]; //
Methods are fucking easy, dud. class fuckBike implements Bicycle {
for String type input <mod> <return> mthdName ...
Int inputString = (int) args[0]; // (<args>) { } void speedUp (int increment) {
for Integer type input Example: speed += increment;
To use Scanner, importing Scanner library is public double getAge () { }
required : import java.Object.Scanner return someDouble; ...
} }
All types of input can be received. (not just
String or int) Constructor
Encapsulation allows individual methods to Java will not allow this to be run, because it Create a Scanner object
have different access modifier. cannot determine the value. Scanner sc = new
Creating setters and getters is one way to use Scanner(System.in);
encapsulation Override Accept input
For example
When you have inherit some of the class from double d = sc.nextDouble()
private void setTime(int hour, int
parents, but you want to do something different.
minuite, int second){
In override feature, all the subclass/class object java.lang.Math
this.hour = hour;
will use the newer method.
this.minuite = minuite; Methods Usage
To make sure JDK knows what you are doing,
this.second = second; type @Override in front of the public name. If Math.max(<value1> Return maximum
} the override is unsuccessful, JDK will returns , <value2>) value
error.
Math.min(<value1> Return minimum
Inheritance Example of overriden helloWorld() method :
, <value2>) value
Class Student
Inheritance helps class to import the public void helloWorld(){ Math.abs(<value>) Return unsigned
superclass' method.
System.out.println("Hello"); value
Importing superclass
} Math.pow(<number> Return value of a
class HelloWorld extends Object
Class GradStudent extends Student , <exponent> numberexponent
{}
@Override
Normally, the class that does not inherit any Math.sqrt(<value> Return square root
public void helloWorld(){
class will inherit Object class.* ) of a value
System.out.println("Hello World");
Class can only inherit 1 class/abstract
Importing Interface }
java.lang.String
class HelloWorld inherits Rules of Overridden methods
1. Access modifier priority can only be Find the length -> int
InterfaceThing {}
narrower or same as superclass msg.length()
Class can inherit unlimited amount of
2. There is the same name method in To lower/uppercase -> String
interface
superclass / libraries msg.toLowerCase()
msg.toUpperCase()
Overload
java.io.PrintStream
Replace a string -> String
We use overload when you want different input
Print with new line msg.replaceAll(String a, String
to work differently, but remains the same name.
System.out.println("Hello b)
Example of Overload
World"); Split string between delimeter -> array
public printer(String x){}
Print msg.split(String delimeter)
public printer(String x, String y)
System.out.print("Hello World"); Start/end with -> boolean
{}
msg.startsWith(String pre)
If the input is 2 string, it will go to the second
msg.endsWith(String post)
method instead of first one.
String format -> String
But you cannot overload by using the same
String.format(String format,
input type sequence. For example
public printer(String x){} Object... args)
Methods Description Provides ways to keep variables and access it Method Usability
faster
charAt(int index) Returns the char value at
Ways to keep data Collections
the specified index
1. Set - Care about duplicity, not queue (eg.
compareTo(String Compare 2 strings Create List of 1, 2, 3 on-the-fly
HashSet)
otherString) lexicographically Arrays.asList(1, 2, 3)
2. List - Care about queue, not duplicity (eg.
concat(String str) Concatenate specified LinkedList) Convert primitive array to Stream
string 3. Map - Care about both queue and key Arrays.stream(primitiveArray)
endsWith(String Test if the string ends with duplicity (eg.HashMap) Convert ArrayList to Stream
suffix) specified suffix Methods that will be included arrayList.stream()
boolean add(Object element);
equals(String Test if strings values are
andObject) the same boolean remove(Object element); LinkedList - CollectionAPI
int size();
toCharArray() Convert string to Create empty LinkedList of Integer
boolean isEmpty();
character array LinkedList myList = new
boolean contains(Object element);
toLowerCase() Convert string to LinkedList<Integer>t()
lowercase Iterator Iterator();
Create LinkedList with values in it
toUpperCase() Convert string to new
HashList - CollectionAPI
uppercase LinkedList<>(Arrays.asList(1, 2,
toString() Convert things to string Method Usability 3)))
valueOf(<value>) Return the representation void add (int index, Add value to list Add an object to LinkedList
of argument Object element) myList.add(50)
length() Return length of the string Object remove(int Remove item #index
index) from list
replaceAll(String Replace string a to string
a, String b) b Object get(int index) Retrieve item #index
from list
split(String Split string between
delimeter) delimeter void set(int index, Set data to
Object element) correspond #index
startsWith(String Test if string starts with
prefix) specified prefix int indexOf(Object Find the #index from
element) element
format(String Format strings to the
format, Object arg) format given ListIterator listIterator()
There is many more in Java documents : It also includes all CollectionAPI methods
https://docs.oracle.com/javase/9/docs/api/java/lan
g/String.html Create new HashList by using
List x = new HashList();