Oops Java Cheatsheet 2023

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Java + OOP concept Cheat Sheet

by Kunanon S (son9912) via cheatography.com/43384/cs/12920/

Hello World! Operators Loop

Start your Java day with Hello World Operand What they do  for (int i: someArray) {}
program = Assign value  while (somet​hing) {}
public class HelloWorld {  do {somet​hing} while (true)
== Check value/​address similarity
public static void main(S​‐
> More than
tring[] args) { Prime number function
// Prints "​Hello, World" to the >= More than or equals
if (n < 2) { return false; }
terminal window. >>> Move bit to the right by
for (int i=2; i <= n/i; i++)
System.ou​t.p​rin​tln​("Hello, ++ Increment by 1 ​ if (n%i == 0) return false;
World");
inverse of these operands still working the return true;
} same.
 returns a boolean
} For example : != is not equal
When you want to run the program, choose
String Pool - Optimi​zations
this class as main class. Defining variable
String pool is created to make the same
Defining new variable attributes
Run your code value string use the same address. By
int x = 12;
doing that, it will save memory and time for
Compile from single class up HelloWorld int x; // will be defined as 0
compiler to do stuff
class Define by creating new instances Basic testing
 javac HelloW​orl​d.java String x = new String; String s1 = "​Hello World";
 java HelloWorld Type Casting (decre​asing bit use) String s2 = "​Hello World;
Compile from multiple classes and choose Expanding data types will not require type
Check it using "​=="
main class casting. Narrowing does.
 System.ou​t.p​rin​tln(s1 ==
 javac *.java double x = 10; // Expanding data
s2);
 java HelloWorld // HelloWorld types
 True
is your preferred main class int y = (int) 10.222222; //
"​==" will check its address
Narrowing data types
Allocate a new address using new
Variables
String s1 = "​Hello World";
Type Default Memory Allocation Conditions
String s2 = new String;
Value If statement s2 = "​Hello World";
byte 0 8 bits  if (state​ment) {} System.ou​t.p​rin​tln(s1 == s2);
short 0 16 bits If - else statement  False
 if (state​ment) {} else{} Allocate new address by changing its value
int 0 32 bits
String s1 = "​Hello World";
long 0L 64 bits
Switch String s2 = "​Hello World";
float 0.0F 32 bits (decimal)
switch (num) { s2 = "​Hello Thaila​nd";
double 0.00D 64 bits (decimal)
​ case 1: doSome​thi​ng(); System.ou​t.p​rin​tln(s1 == s2);
boolean False varies on impliment ​ ​ ​ ​break;  False
String NULL depends on ​ ​def​ault: doThis();
character count ​ ​ ​ ​break;
char \u0000 16 bits (unicode) }

By Kunanon S (son9912) Published 25th September, 2017. Sponsored by Readable.com


cheatography.com/son9912/ Last updated 29th September, 2017. Measure your website readability!
Page 1 of 4. https://readable.com
Java + OOP concept Cheat Sheet
by Kunanon S (son9912) via cheatography.com/43384/cs/12920/

Naming Grammars Access Modifier Constr​uctor (cont)

Naming should be regulated for easier But will be created automa​tically by not
recogition from others writing any constr​uctor
Use Upper Camel Case for classes : Create an argume​nt-​defined constr​uctor
Veloci​tyR​esp​ons​eWriter  <mo​dif​ier> Person (String
Use Lower Case for packages: com.co​‐ name) {
mpa​ny.p​ro​ject.ui ​ ​thi​s.name = name;
Use Lower Camel Case for variables: }
studen​tName
Use Upper Case for constants: MAX_PA​‐ - Java uses <de​fau​lt>
modifier when Abstract Class
RAM​ETE​R_COUNT = 100 not assigning any. Abstract is a type of class but it can consist
Use Camel Case for enum class names - public modifier allows same class of incomplete methods .
Use Upper Case for enum values access Create new abstract
Don't use '_' anywhere except constants - Works in inherited class means itself and  <ac​ces​s_m​odi​fie​r>
and enum values (which are consta​nts). the classes that inherit from it. abstract class HelloWorld () {}

Receiving user input Attribute modifier Interface


There is normally 2 ways to receive user Attribute Access Grants Interface is different from constr​uctor. It
keyboard input Type consists of incomplete assign​ments
1. java.u​til.Sc​anner
Private Allows only in class where Interface allows you to make sure that any
Scanner x = new Scanne​r(S​yst​‐
variable belongs inherited class can do the following
em.in); methods. (It's like a contract to agree that
Public Allows any class to have this
String inputS​tring = x.next(); this thing must be able to do this shit.) The
attribute
// for String type input method is then completed in the class that
Static Attribute that dependent on
int inputI​nteger = x.next​‐ implements it.
class (not object)
Int(); // for Integer type input Creating a new interface
2. String[] args from public static void main() Final Defined once. Does not allow interface Bicycle {
NOTE: args is already in a array. It can any change​/in​her​itance ​ void speedUp (int increm​‐
receives unlimited amount of arguments. ent);
String inputS​tring = args[0]; Methods
}
// for String type input Methods are fucking easy, dud. ----
Int inputS​tring = (int)  <mo​d> <re​tur​n> mthdName class fuckBike implements
args[0]; // for Integer type (<a​rgs​>) { } Bicycle {
input Example: ​ ...
 public double getAge () { ​ void speedUp (int increment)
To use Scanner, importing Scanner library
is required : import java.O​bje​‐ ​ ​return someDo​uble; {
ct.S​canner } ​ ​ ​ ​speed += increment;
​ }
All types of input can be received. (not just Constr​uctor ​ ...
String or int) Constr​uctors allow you to create an object }
template. It consists of complete
procedures.
Create a blank constr​uctor to allow its
extension classes to inherit this super
constr​uctor.
 <mo​dif​ier> Person () {}

By Kunanon S (son9912) Published 25th September, 2017. Sponsored by Readable.com


cheatography.com/son9912/ Last updated 29th September, 2017. Measure your website readability!
Page 2 of 4. https://readable.com
Java + OOP concept Cheat Sheet
by Kunanon S (son9912) via cheatography.com/43384/cs/12920/

Encaps​ulation Overload (cont) java.u​til.Sc​anner

Encaps​ulation 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 Scanne​r(S​‐
Creating setters and getters is one way to yst​em.in);
use encaps​ulation Override Accept input
For example  double d = sc.nex​tDo​uble()
When you have inherit some of the class
private void setTim​e(int hour,
from parents, but you want to do something
int minuite, int second){ different. In override feature, all the subcla​‐ java.l​ang.Math
this.hour = hour; ss/​class object will use the newer method. Methods Usage
this.m​inuite = minuite; To make sure JDK knows what you are
Math.m​ax(​<va​‐ Return maximum
this.s​econd = second; doing, type @Override in front of the
lue​1>, <va​‐ value
} public name. If the override is unsucc​essful,
lue​2>)
JDK will returns error.
Inheri​tance Example of overriden helloW​orld() method : Math.m​in(​<va​‐ Return minimum

Class Student lue​1>, <va​‐ value


Inheri​tance helps class to import the superc​‐
public void helloW​orld(){ lue​2>)
lass' method.
Importing superclass System.ou​t.p​rin​tln​("He​‐ Math.a​bs(​<va​‐ Return unsigned
 class HelloWorld extends llo​"); lue​>) value
Object {} } Math.p​ow(​<nu​‐ Return value of a
Normally, the class that does not inherit any Class GradSt​udent extends Student mbe​r>, <ex​‐ numberexponent
class will inherit Object class.* @Override
pon​ent>
Class can only inherit 1 class/​abs​tract public void helloW​orld(){
Math.s​qrt​(<v​‐ Return square
Importing Interface System.ou​t.p​rin​tln​("Hello
alu​e>) root of a value
 class HelloWorld inherits World");
Interf​ace​Thing {} }
java.l​ang.String
Class can inherit unlimited amount of Rules of Overridden methods
interface 1. Access modifier priority can only be Find the length -> int
narrower or same as superclass  msg.le​ngth()
Overload 2. There is the same name method in To lower/​upp​ercase -> String
superclass / libraries  msg.to​Low​erC​ase()
We use overload when you want different
 msg.to​Upp​erC​ase()
input to work differ​ently, but remains the
java.i​o.P​rin​tStream Replace a string -> String
same name.
 msg.re​pla​ceA​ll(​String a,
Example of Overload Print with new line
String b)
public printe​r(S​tring x){}  System.ou​t.p​rin​tln​("Hello
Split string between delimeter -> array
public printe​r(S​tring x, World");
 msg.sp​lit​(String delimeter)
String y){} Print
Start/end with -> boolean
If the input is 2 string, it will go to the second  System.ou​t.p​rin​t("Hello
 msg.st​art​sWi​th(​String pre)
method instead of first one. World");
 msg.en​dsW​ith​(String post)
But you cannot overload by using the same
input type sequence. For example String format -> String

public printe​r(S​tring x){}  String.fo​rma​t(S​tring

public printe​r(S​tring x, format, Object... args)

String y){} // conflict


public printe​r(S​tring y,
String x){} // conflict

By Kunanon S (son9912) Published 25th September, 2017. Sponsored by Readable.com


cheatography.com/son9912/ Last updated 29th September, 2017. Measure your website readability!
Page 3 of 4. https://readable.com
Java + OOP concept Cheat Sheet
by Kunanon S (son9912) via cheatography.com/43384/cs/12920/

java.l​ang.String java.u​til.Co​lle​ction (Colle​cti​onAPI) HashMap - Collec​tionAPI

Methods Descri​ption Provides ways to keep variables and Method Usability


charAt(int index) Returns the char value access it faster
at the specified index Ways to keep data Collec​tions
1. Set - Care about duplicity, not queue (eg.
compar​eTo​‐ Compare 2 strings Create List of 1, 2, 3 on-the-fly
HashSet)
(String otherS​‐ lexico​gra​phi​cally  Arrays.as​List(1, 2, 3)
2. List - Care about queue, not duplicity (eg.
tring) Convert primitive array to Stream
Linked​List)
concat​(String str) Concat​enate specified  Arrays.st​rea​m(p​rim​iti​‐
3. Map - Care about both queue and key
string veA​rray)
duplicity (eg.Ha​shMap)
Convert ArrayList to Stream
endsWi​th(​String Test if the string ends Methods that will be included
 arrayL​ist.st​ream()
suffix) with specified suffix boolean add(Object element);
equals​(String Test if strings values boolean remove​(Object element);
LinkedList - Collec​tionAPI
andObject) are the same int size();
boolean isEmpty(); Create empty LinkedList of Integer
toChar​Array() Convert string to
 LinkedList myList = new
character array boolean contai​ns(​Object
Linked​Lis​t<I​nte​ger​>t()
toLowe​rCase() Convert string to element);
Create LinkedList with values in it
lowercase Iterator Iterat​or();
 new Linked​Lis​t<>​(Ar​ray​‐
toUppe​rCase() Convert string to s.a​sLi​st(1, 2, 3)))
HashList - Collec​tionAPI
uppercase
Add an object to LinkedList
toString() Convert things to string Method Usability
 myList.ad​d(50)
valueO​f(<​val​ue>) Return the repres​ent​‐ void add (int index, Add value to list

ation of argument Object element)

length() Return length of the Object remove(int Remove item

string index) #index from list

replac​eAl​l(S​tring Replace string a to Object get(int index) Retrieve item

a, String b) string b #index from list

split(​String Split string between void set(int index, Set data to

delimeter) delimeter Object element) correspond #index

starts​Wit​h(S​tring Test if string starts with int indexO​f(O​bject Find the #index

prefix) specified prefix element) from element

format​(String Format strings to the ListIt​erator listIt​era​tor()

format, Object format given It also includes all Collec​tionAPI methods


arg)

There is many more in Java documents : Create new HashList by using

https:​//d​ocs.or​acl​e.c​om/​jav​ase​/9/​doc​s/a​pi/​‐ List x = new HashLi​st();

jav​a/l​ang​/St​rin​g.html

By Kunanon S (son9912) Published 25th September, 2017. Sponsored by Readable.com


cheatography.com/son9912/ Last updated 29th September, 2017. Measure your website readability!
Page 4 of 4. https://readable.com

You might also like