Show Menu

Java + OOP concept Cheat Sheet by

Created by Information Technology, KMITL students #IT14
library     java     oop     coding     oo

Hello World!

Start your Java day with Hello World program
public class HelloWorld {
public static void main(S­tring[] args) {
// Prints "­Hello, World" to the terminal window.
System.ou­t.p­rin­tln­("Hello, World");
}
}

When you want to run the program, choose this class as main class.

Run your code

Compile from single class up HelloWorld class
javac HelloW­orl­d.java
java HelloW­orld

Compile from multiple classes and choose main class
javac *.java
java HelloWorld // HelloWorld is your preferred main class

Variables

Type
Default Value
Memory Alloca­tion
byte
0
8 bits
short
0
16 bits
int
0
32 bits
long
0L
64 bits
float
0.0F
32 bits (decimal)
double
0.00D
64 bits (decimal)
boolean
False
varies on impliment
String
NULL
depends on character count
char
\u0000
16 bits (unicode)

Operators

Oper­and
What they do
=
Assign value
==
Check value/­address similarity
>
More than
>=
More than or equals
>>>
Move bit to the right by
++
Increment by 1
inverse of these operands still working the same.
For example : != is not equal

Defining variable

Defining new variable attrib­utes
int x = 12;
int x; // will be defined as 0

Define by creating new instan­ces
String x = new String;

Type Casting (decre­asing bit use)
Expanding data types will not require type casting. Narrowing does.
double x = 10; // Expanding data types
int y = (int) 10.222222; // Narrowing data types

Conditions

If statem­ent
if (state­ment) {}
If - else statem­ent
if (state­ment) {} else{}

Switch

switch (num) {
  case 1: doSomething();
    break;
  default: doThis();
    break;
}

Loop

for (int i: someArray) {}
while (somet­hing) {}
do {somet­hing} while (true)

Prime number function

if (n < 2) { return false; }
for (int i=2; i <= n/i; i++)
  if (n%i == 0) return false;
return true;
returns a boolean

String Pool - Optimi­zations

String pool is created to make the same value string use the same address. By doing that, it will save memory and time for compiler to do stuff

Basic testing
String s1 = "­Hello World";
String s2 = "­Hello World;

Check it using "­=="
Syste­m.o­ut.p­ri­ntln(s1 == s2);
True
"==­" will check its address

Allocate a new address using new
String s1 = "­Hello World";
String s2 = new String;
s2 = "­Hello World";
Syste­m.o­ut.p­ri­ntln(s1 == s2);
False

Allocate new address by changing its value
String s1 = "­Hello World";
String s2 = "­Hello World";
s2 = "­Hello Thaila­nd";
Syste­m.o­ut.p­ri­ntln(s1 == s2);
False

Naming Grammars

Naming should be regulated for easier recogition from others

Use Upper Camel Case for clas­ses: Veloc­ity­Res­pon­seW­riter
Use Lower Case for pack­ages: com.c­omp­any.pr­oje­ct.ui
Use Lower Camel Case for vari­abl­es: stude­ntName
Use Upper Case for cons­tan­ts: MAX_P­ARA­MET­ER_­COUNT = 100

Use Camel Case for enum class names
Use Upper Case for enum values
Don't use '_' anywhere except constants and enum values (which are consta­nts).

Receiving user input

There is normally 2 ways to receive user keyboard input

1. java.u­til.Sc­anner
Scanner x = new Scanne­r(S­yst­em.i­n);
String inputS­tring = x.next(); // for String type input
int inputI­nteger = x.next­Int(); // for Integer type input

2. String[] args from public static void main()
NOTE: args is already in a array. It can receives unlimited amount of argume­nts.
String inputS­tring = args[0]; // for String type input
Int inputS­tring = (int) args[0]; // for Integer type input
To use Scanner, importing Scanner library is required : import java.O­bje­ct.S­ca­nner

All types of input can be received. (not just String or int)
 

Access Modifier

- Java uses <d­efa­ult­> modifier when not assigning any.
- public modifier allows same class access
- Works in inherited class means itself and the classes that inherit from it.

Attribute modifier

Attr­ibute Type
Access Grants
Private
Allows only in class where variable belongs
Public
Allows any class to have this attribute
Static
Attribute that dependent on class (not object)
Final
Defined once. Does not allow any change­/in­her­itance

Methods

Methods are fucking easy, dud.
<m­od> <re­tur­n> mthdName (<a­rgs­>) { }

Exam­ple:
public double getAge () {
  return someDo­uble;
}

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 () {}
But will be created automa­tically by not writing any constr­uctor

Create an argume­nt-­defined constr­uctor
<m­odi­fie­r> Person (String name) {
  th­is.name = name;
}

Abstract Class

Abstract is a type of class but it can consist of incomplete methods.

Create new abstract
<a­cce­ss_­mod­ifi­er> abstract class HelloWorld () {}

Interface

Interface is different from constr­uctor. It consists of incomplete assign­ments

Interface allows you to make sure that any inherited class can do the following methods. (It's like a contract to agree that this thing must be able to do this shit.) The method is then completed in the class that implements it.

Creating a new interf­ace
interface Bicycle {
  void speedUp (int increm­ent);
}
----
class fuckBike implements Bicycle {
  ...
  void speedUp (int increment) {
    speed += increm­ent;
  }
  ...
}

Encaps­ulation

Encaps­ulation allows individual methods to have different access modifier.
Creating setters and getters is one way to use encaps­ulation

For example
private void setTim­e(int hour, int minuite, int second){
this.hour = hour;
this.m­inuite = minuite;
this.s­econd = second;
}

Inheri­tance

Inheri­tance helps class to import the superc­lass' method.

Impo­rting superc­lass
class HelloWorld extends Object {}

Normally, the class that does not inherit any class will inherit Object class.*

Class can only inherit 1 class/­abs­tract

Impo­rting Interf­ace
class HelloWorld inherits Interf­ace­Thing {}

Class can inherit unlimited amount of interf­ace

Overload

We use overload when you want different input to work differ­ently, but remains the same name.

Example of Overload
public printe­r(S­tring x){}
public printe­r(S­tring x, String y){}

If the input is 2 string, it will go to the second method instead of first one.

But you cannot overload by using the same input type sequence. For example
public printe­r(S­tring x){}
public printe­r(S­tring x, String y){} // conflict
public printe­r(S­tring y, String x){} // conflict

Java will not allow this to be run, because it cannot determine the value.

Override

When you have inherit some of the class from parents, but you want to do something different. In override feature, all the subcla­ss/­class object will use the newer method.

To make sure JDK knows what you are doing, type @Over­ride in front of the public name. If the override is unsucc­essful, JDK will returns error.

Example of overriden helloW­orld() method :
Class Student
public void helloW­orl­d(){
Syste­m.o­ut.p­ri­ntl­n("H­ell­o");
}

Class GradSt­udent extends Student
@Over­ride
public void helloW­orl­d(){
Syste­m.o­ut.p­ri­ntl­n("Hello World");
}

Rules of Overridden methods
1. Access modifier priority can only be narrower or same as superclass
2. There is the same name method in superclass / libraries
 

java.i­o.P­rin­tStream

Print with new line
Syste­m.o­ut.p­ri­ntl­n("Hello World");
Print
Syste­m.o­ut.p­ri­nt(­"­Hello World");

java.u­til.Sc­anner

Create a Scanner object
Scanner sc = new Scanne­r(S­yst­em.i­n);
Accept input
double d = sc.nex­tDo­uble()

java.l­ang.Math

Meth­ods
Usage
Math.m­ax­(<v­alu­e1>, <va­lue­2>)
Return maximum value
Math.m­in­(<v­alu­e1>, <va­lue­2>)
Return minimum value
Math.a­bs­(<v­alu­e>)
Return unsigned value
Math.p­ow­(<n­umb­er>, <ex­pon­ent­>
Return value of a number­ex­ponent
Math.s­qr­t(<­val­ue>)
Return square root of a value

java.l­ang.String

Find the length -> int
msg.l­eng­th()
To lower/­upp­erc­ase -> String
msg.t­oLo­wer­Case()
msg.t­oUp­per­Case()
Replace a string -> String
msg.r­epl­ace­All­(String a, String b)
Split string between delime­ter -> array
msg.s­pli­t(S­tring delime­ter)
Star­t/end with -> boolean
msg.s­tar­tsW­ith­(String pre)
msg.e­nds­Wit­h(S­tring post)
String format -> String
Strin­g.f­orm­at(­String format, Object... args)

java.l­ang.String

Meth­ods
Desc­rip­tion
charAt(int index)
Returns the char value at the specified index
compar­eTo­(String otherS­tring)
Compare 2 strings lexico­gra­phi­cally
concat­(String str)
Concat­enate specified string
endsWi­th(­String suffix)
Test if the string ends with specified suffix
equals­(String andObject)
Test if strings values are the same
toChar­Array()
Convert string to character array
toLowe­rCase()
Convert string to lowercase
toUppe­rCase()
Convert string to uppercase
toString()
Convert things to string
valueO­f(<­val­ue>)
Return the repres­ent­ation of argument
length()
Return length of the string
replac­eAl­l(S­tring a, String b)
Replace string a to string b
split(­String delimeter)
Split string between delimeter
starts­Wit­h(S­tring prefix)
Test if string starts with specified prefix
format­(String format, Object arg)
Format strings to the format given

java.u­til.Co­lle­ction (Colle­cti­onAPI)

Provides ways to keep variables and access it faster

Ways to keep data
1. Set - Care about duplicity, not queue (eg. HashSet)
2. List - Care about queue, not duplicity (eg. Linked­List)
3. Map - Care about both queue and key duplicity (eg.Ha­shMap)

Methods that will be included
boolean add(Object element);
boolean remove­(Object element);
int size();
boolean isEmpt­y();
boolean contai­ns(­Object element);
Iterator Iterat­or();

HashList - Collec­tionAPI

Method
Usability
void add (int index, Object element)
Add value to list
Object remove(int index)
Remove item #index from list
Object get(int index)
Retrieve item #index from list
void set(int index, Object element)
Set data to correspond #index
int indexO­f(O­bject element)
Find the #index from element
ListIt­erator listIt­era­tor()
It also includes all Collec­tionAPI methods

Create new HashList by using
List x = new HashLi­st();

HashMap - Collec­tionAPI

Method
Usability

Collec­tions

Create List of 1, 2, 3 on-the­-fly
Array­s.a­sLi­st(1, 2, 3)
Convert primitive array to Stream
Array­s.s­tre­am(­pri­mit­ive­Array)
Convert ArrayList to Stream
array­Lis­t.s­tre­am()

LinkedList - Collec­tionAPI

Create empty LinkedList of Integer
Linke­dList myList = new Linked­Lis­t<I­nte­ger­>t()
Create LinkedList with values in it
new Linked­Lis­t<>­(Ar­ray­s.a­sLi­st(1, 2, 3)))
Add an object to Linked­List
myLis­t.a­dd(50)

Download the Java + OOP concept Cheat Sheet

4 Pages
//media.cheatography.com/storage/thumb/son9912_java-oop-concept.750.jpg

PDF (recommended)

Alternative Downloads

Share This Cheat Sheet!

Like this cheat sheet? Check out our sponsors!

Readable.io is a collection of tools to make your writing better. More readable content means higher conversion rates and better reader engagement. Measure website and document readability, measure keyword density and more!

Click Here To Get Started!

 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          OO_Java Cheat Sheet
          C Reference Cheat Sheet
          Selenium WebDriver Cheat Sheet Cheat Sheet