Java + OOP Concept Cheat Sheet: by Via

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4
At a glance
Powered by AI
Some of the key takeaways from the document include the basic syntax for a Java program, common data types like int, string and boolean, and basic OOP concepts like classes, objects, inheritance and polymorphism.

The main data types in Java include primitive data types like int, double, boolean and char, and reference data types like String, arrays and classes.

The main operators in Java include arithmetic operators like + - * /, comparison operators like == != > <, assignment operators like =, logical operators like && || !, increment/decrement operators like ++ --, and bitwise operators like & | ^.

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 program Oper​and What they do  for (int i: someArray) {}
public class HelloWorld {  while (somet​hing) {}
= Assign value
public static void main(S​tring[]  do {somet​hing} 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.ou​t.p​rin​tln​("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

Run your code Defining variable String Pool - Optimi​zations

Compile from single class up HelloWorld Defining new variable attrib​utes String pool is created to make the same value
class int x = 12; string use the same address. By doing that, it
 javac HelloW​orl​d.java will save memory and time for compiler to do
int x; // will be defined as 0
 java HelloW​orld stuff
Define by creating new instan​ces
Basic testing
Compile from multiple classes and choose String x = new String;
String s1 = "​Hello World";
main class
Type Casting (decre​asing 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  Syste​m.o​ut.p​ri​ntln(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 Alloca​tion 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 statem​ent Syste​m.o​ut.p​ri​ntln(s1 == s2);
 if (state​ment) {}
int 0 32 bits  False
If - else statem​ent
Allocate new address by changing its value
long 0L 64 bits
 if (state​ment) {} else{} String s1 = "​Hello World";
float 0.0F 32 bits (decimal)
String s2 = "​Hello World";
double 0.00D 64 bits (decimal) Switch
s2 = "​Hello Thaila​nd";
boolean False varies on impliment
switch (num) { Syste​m.o​ut.p​ri​ntln(s1 == s2);
String NULL depends on character ​ case 1: doSome​thi​ng();  False
count
​ ​ ​ ​break;
char \u0000 16 bits (unicode) ​ ​def​ault: doThis();
​ ​ ​ ​break;
}

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


cheatography.com/son9912/ Last updated 29th September, 2017. Measure your website readability!
Page 1 of 4. https://readability-score.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 writing
recogition from others any constru
​ ctor
Use Upper Camel Case for clas​ses: Create an argume​nt-​defined constr​uctor
Veloc​ity​Res​pon​seW​riter  <m​odi​fie​r> Person (String name)
Use Lower Case for pack​ages: {
com.c​omp​any.pr​oje​ct.ui th​is.name = name;
Use Lower Camel Case for vari​abl​es: }
stude​ntName
Use Upper Case for cons​tan​ts: Abstract Class
- Java uses <d​efa​ult​> modifier when not
MAX_P​ARA​MET​ER_​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.  <a​cce​ss_​mod​ifi​er> abstract class
enum values (which are consta​nts).
HelloWorld () {}
Attribute modifier
Receiving user input
Attr​ibute Access Grants Interface
There is normally 2 ways to receive user
Type
keyboard input Interface is different from constr​uctor. It
1. java.u​til.Sc​anner Private Allows only in class where variable consists of incomplete assign​ments

Scanner x = new belongs Interface allows you to make sure that any

Scanne​r(S​yst​em.i​n); 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 inputS​tring = 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 inputI​nteger = x.next​Int(); // (not object)
Creating a new interf​ace
for Integer type input Final Defined once. Does not allow any interface Bicycle {
2. String[] args from public static void main() change​/in​her​itance
void speedUp (int increm​ent);
NOTE: args is already in a array. It can }
receives unlimited amount of argume​nts. Methods
----
String inputS​tring = args[0]; //
Methods are fucking easy, dud. class fuckBike implements Bicycle {
for String type input  <m​od> <re​tur​n> mthdName ...
Int inputS​tring = (int) args[0]; // (<a​rgs​>) { } void speedUp (int increment) {
for Integer type input Exam​ple: speed += increm​ent;
To use Scanner, importing Scanner library is  public double getAge () { }
required : import java.O​bje​ct.S​ca​nner return someDo​uble; ...
} }
All types of input can be received. (not just
String or int) Constr​uctor

Constr​uctors allow you to create an object


template. It consists of complete proced​ures.
Create a blank constr​uctor to allow its
extension classes to inherit this super
constr​uctor.
 <m​odi​fie​r> Person () {}

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


cheatography.com/son9912/ Last updated 29th September, 2017. Measure your website readability!
Page 2 of 4. https://readability-score.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
Creating setters and getters is one way to use Scanne​r(S​yst​em.i​n);
encaps​ulation Override Accept input
For example
When you have inherit some of the class from  double d = sc.nex​tDo​uble()
private void setTim​e(int hour, int
parents, but you want to do something different.
minuite, int second){
In override feature, all the subcla​ss/​class object java.l​ang.Math
this.hour = hour;
will use the newer method.
this.m​inuite = minuite; Meth​ods Usage
To make sure JDK knows what you are doing,
this.s​econd = second; type @Over​ride in front of the public name. If Math.m​ax​(<v​alu​e1> Return maximum
} the override is unsucc​essful, JDK will returns , <va​lue​2>) value
error.
Math.m​in​(<v​alu​e1> Return minimum
Inheri​tance Example of overriden helloW​orld() method :
, <va​lue​2>) value
Class Student
Inheri​tance helps class to import the public void helloW​orl​d(){ Math.a​bs​(<v​alu​e>) Return unsigned
superc​lass' method.
Syste​m.o​ut.p​ri​ntl​n("H​ell​o"); value
Impo​rting superc​lass
} Math.p​ow​(<n​umb​er> Return value of a
 class HelloWorld extends Object
Class GradSt​udent extends Student , <ex​pon​ent​> number​ex​ponent
{}
@Over​ride
Normally, the class that does not inherit any Math.s​qr​t(<​val​ue> Return square root
public void helloW​orl​d(){
class will inherit Object class.* ) of a value
Syste​m.o​ut.p​ri​ntl​n("Hello World");
Class can only inherit 1 class/​abs​tract
Impo​rting Interf​ace }
java.l​ang.String
 class HelloWorld inherits Rules of Overridden methods
1. Access modifier priority can only be Find the length -> int
Interf​ace​Thing {}
narrower or same as superclass  msg.l​eng​th()
Class can inherit unlimited amount of
2. There is the same name method in To lower/​upp​erc​ase -> String
interf​ace
superclass / libraries  msg.t​oLo​wer​Case()
 msg.t​oUp​per​Case()
Overload
java.i​o.P​rin​tStream
Replace a string -> String
We use overload when you want different input
Print with new line  msg.r​epl​ace​All​(String a, String
to work differ​ently, but remains the same name.
 Syste​m.o​ut.p​ri​ntl​n("Hello b)
Example of Overload
World"); Split string between delime​ter -> array
public printe​r(S​tring x){}
Print  msg.s​pli​t(S​tring delime​ter)
public printe​r(S​tring x, String y)
 Syste​m.o​ut.p​ri​nt(​"​Hello World"); Star​t/end with -> boolean
{}
 msg.s​tar​tsW​ith​(String pre)
If the input is 2 string, it will go to the second
 msg.e​nds​Wit​h(S​tring post)
method instead of first one.
String format -> String
But you cannot overload by using the same
 Strin​g.f​orm​at(​String format,
input type sequence. For example
public printe​r(S​tring x){} Object... args)

public printe​r(S​tring x, String y)


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

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


cheatography.com/son9912/ Last updated 29th September, 2017. Measure your website readability!
Page 3 of 4. https://readability-score.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

Meth​ods Desc​rip​tion Provides ways to keep variables and access it Method Usability
faster
charAt(int index) Returns the char value at
Ways to keep data Collec​tions
the specified index
1. Set - Care about duplicity, not queue (eg.
compar​eTo​(String Compare 2 strings Create List of 1, 2, 3 on-the​-fly
HashSet)
otherS​tring) lexico​gra​phi​cally  Array​s.a​sLi​st(1, 2, 3)
2. List - Care about queue, not duplicity (eg.
concat​(String str) Concat​enate specified Linked​List) Convert primitive array to Stream
string 3. Map - Care about both queue and key  Array​s.s​tre​am(​pri​mit​ive​Array)

endsWi​th(​String Test if the string ends with duplicity (eg.Ha​shMap) Convert ArrayList to Stream
suffix) specified suffix Methods that will be included  array​Lis​t.s​tre​am()
boolean add(Object element);
equals​(String Test if strings values are
andObject) the same boolean remove​(Object element); LinkedList - Collec​tionAPI
int size();
toChar​Array() Convert string to Create empty LinkedList of Integer
boolean isEmpt​y();
character array  Linke​dList myList = new
boolean contai​ns(​Object element);
toLowe​rCase() Convert string to Linked​Lis​t<I​nte​ger​>t()
lowercase Iterator Iterat​or();
Create LinkedList with values in it
toUppe​rCase() Convert string to  new
HashList - Collec​tionAPI
uppercase Linked​Lis​t<>​(Ar​ray​s.a​sLi​st(1, 2,
toString() Convert things to string Method Usability 3)))

valueO​f(<​val​ue>) Return the repres​ent​ation void add (int index, Add value to list Add an object to Linked​List
of argument Object element)  myLis​t.a​dd(50)

length() Return length of the string Object remove(int Remove item #index
index) from list
replac​eAl​l(S​tring 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
starts​Wit​h(S​tring Test if string starts with
prefix) specified prefix int indexO​f(O​bject Find the #index from
element) element
format​(String Format strings to the
format, Object arg) format given ListIt​erator listIt​era​tor()

There is many more in Java documents : It also includes all Collec​tionAPI methods
https:​//d​ocs.or​acl​e.c​om/​jav​ase​/9/​doc​s/a​pi/​jav​a/l​an
g​/St​rin​g.html Create new HashList by using
List x = new HashLi​st();

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


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

You might also like