We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 22
Java Cheatsheet
Basics
Basic syntax and functions from the Java programming language.
Boilerplate
emo rated
Pr SeCR SCC Ren locur Bete De
("Hello World")
Showing Output
It will print something to the output console
Trobe ratennt
Pre ReCn SCR eisai Rect
Cran ss UrS tan Tet mab}
Taking Input
It will take string input from the user.SECS Benois
cS orig
CPVMGios Ee tcrdeDnt
eure N ree
String name = sc-nextLine();
arse
Scum! e)
It will take integer input from the user.
Pree?
Salle
TVR Ciosty- Rec re Dee
Dera Suse acum)
Paes ts 0
Scum ntin(x)
It will take float input from the user.
NCIS BREST
cane rating
TERY Cies ur ietc rim pee
Sueur)
crest CaO
Secunia strated)
It will take double input from the user.
TVR Cios i Reece DEE
Sudan)
nora:
ble()printin(x
Primitive Type Variables
The eight primitives defined in Java are int , byte, short , long, float , double, boolean , and char
These aren't considered objects and represent raw values.
byte
byte is a primitive data type that only takes up 8 bits of memory.
Seem Set rT in
public static void main(String args!
Eyre)
Prstranierc)
long
Long is another primitive data type related to integers, long takes up 64 bits of memory.
ecm sty ratcin(
float
We represent basic fractional numbers in Java using the float. type. This is a single-precision decimal
number, which means if we get past six decimal points, this number becomes less precise and more of an
estimate.Pesbtat ine
neues ie
ote aL
TSnNG
char
char is a 16-bit integer representing a Unicode-encoded character.
cre eiestye]
AN;
rintIn(letter)
int
int holds a wide range of non-fractional number values.
Pian rating
ent estr)
PSUTSnTec TsO
short
If we want to save memory and byte is too small, we can use
CCSbry rated
TEUeiestr]
vee)
System. out. print1n(var2)Comments
Acomment is the code that is not executed by the compiler, and the programmer uses it to keep track of the
code
gle line comment
line comment
Constants
Constants are like a variable, except that their value never changes during program execution
PT eC SECC sete tC uiet
Cee aa
Pr SECC VeCn SCR Ti Ciect mers Toe
print1n("Value of PI: " + PI)
Arithmetic Expressions
These are the collection of literals and arithmetic operators.Addition
Itcan be used to add two numbers.
Eset eC Tete a0)
Pr Seta SCRA R EAC es Ue tst]
out. print1n(x
Subtraction
Itcan be used to subtract two numbers.
ET aeCRseCM Seto al)
Prete tet
Multiplication
It can be used to multiply two numbers.
PM SeCsCCm Set at)
Crea eTeC nC RTC lect tice Dn
print1n(x
Division
Itcan be used to divide two numbers.
ET SetaLCSIeissti-E
PUN EET
Somat strated)
Modulo Remainder
Itreturns the remainder of the two numbers after division.
tee
Testers
ut .printin(x)
Augmented Operators
Addition assignment
Terai
Crvneres Bets
ScUmbat ys trante7 a)
Subtraction assignment
cr
Tee
Creeiest Bey
CUR a y= Urstte7y a)Multiplication assignment
Saleln@
creaneres ty Bey
System. out. print1n(var)
Division assignme:
1d {
Cries Beara
Modulus assignment
Tee
CES Gies tyler ep)
var = 4
rr 10;
System. out
Escape SequencesIt is a sequence of characters starting with a backslash, and it doesn't represent itself when used inside a
string literal.
Tab
It gives a tab space.
EM SeCRs etm Set oat]
Pr Sea TeCR SCR MC l ea Becca Dn
Pystraans
Backslash
Itadds a backslash.
ET seCRsCCOM Set al)
Pr Sete tet
SCM asst Tdany
Single quote
Itadds a single quotation mark.
Er SeC SECM Tel a0)
Pr Sea SCn CRTC scU rit D)
CUR asda
Question mark
Itadds a question mark.ET sbCsCCOM Set (yal)
PT SeCe MSCS SuC issu ic tr
cars Ue aea
Carriage return
Inserts a carriage return in the text at this point.
Er SeC SECM Tet a0)
Pree VeCn CRTC scUr it)
CUR a staan
Double quote
Itadds a double quotation mark
Pete Cem Sets a0)
Probe VeCn SCRA lsc Uric)
Roa Ur anu
Type Casting
Type Casting is a process of converting one data type into another.
Widening Type Casting
It means converting a lower data type into a higher.
orem Cob ta rated
Pree tec CRT Ciect rit
Paes fiNarrowing Type Casting
It means converting a higher data type into a lower.
Ese ratcint
Pree eCRSCR Cleo irc ie De
Cost ae
int var_name = (int) x
Dar ye thc eau
Decision Control Statements
Conditional statements are used to perform operations based on some condition.
if Statement
if-else Statement
if (condition) ¢Ternary Operator
It is shorthand for an if-else statement.
Syntax
ET oecmse CUS
PT Se tars String args[])
printin
Pesta
ich Statements
It allows a variable to be tested for equality against a list of values (cases)CESetes tr]
See a
Acuna y= Orst Gar ss ab
Setret@l aCe Nap)
ees Yates ab
Tanai sat CVn
Secu at susan he
Cc Umebatystla tan Vn
Iterative Statements
Iterative statements facilitate programmers to execute any block of code lines repeatedly and can be
controlled as per conditions added by the coder.
while Loop
It iterates the block of code as long as a specified condition is True,
DiSpessc ula ane
crea Inmetfor Loop
for loop is used to run a block of code several times.
Tone rating
nies iet
(CUP ee cree U Tare
System. out.printin(i)
for-each Loop
Terai
cca)
Piso lne
Citar Sst auTe8)
do-while Loop
Itis an exit-controlled loop. It is very similar to the while loop with one difference, i.e., the body of the do-
while loop is executed at least once even if the condition is False.
Treacle
TR Ciosty-Ee cep anEtem. out.printn(i)
(i < 100)
Break statement
break keyword inside the loop is used to terminate the loop.
Tone rating
nies iet
(CUP ee cree U Tare
System. out.printin(i)
(i = 50)
Continue statement
continue keyword skips the rest of the current iteration of the loop and returns to the starting point of the
loop.
Teresa
Fare HELO IES
TED)
ne
CURT Sty
Ca)Arrays are used to store multiple values in a single variable.
Declaring an array
Declaration of an array.
ET oeCse CCM Selo al]
public static void main(String args{1) {
Sect STE
Defining an array
Defining an array.
ET SeCR SECM Tet a0)
Pree eCn CRT ecu it 8D)
Seeur say Even
Accessing an array
Accessing the elements of an array.
Pr SeCRC Cee Set ot)
Pr SeCRe VeC TCR enn roc iret cee
lesa SCT s {"Harry"
Detranec ears)
Changing an element
Changing any element in an array.reset ates
Uect et Tien ine
OR ae Obes CUCU
pra
Array length
It gives the length of the array,
eee
cre eiestye]
[eC LUCE OL tes OL UCC OES
cea surrey)
Loop through ray
It allows us to iterate through each array element.
oWorld {
TVR Ciosty- Reece aEE
var_name = {"Harry", "Rohan", “Aakash"}
( Cee Ue Cur ra me
Sus sa sle Lea
imensional Arrays
can be 1-D, 2-D, or multi-dimensional.
IsiemuLvsstd eS]E3)
crsesei SCSTei OM iss eee
Methods
Methods are used to divide an extensive program into smaller pieces. It can be called multiple times to
provide reusability to the program
Declaration
Declaration of a method
Calling a method
Calling a method.
methodName (arguments)
Example
PsbS eC i rur a0 eur}
perce
Pystrany Gries
Pystrany Gries
importLeelee
Crary
CIM ys reine ae MT ea)
num = scan.nextInt();
eure Tie ar)
Method Overloading
Method overloading means having multiple methods with the same name, but different parame’
ns
Serena ety
eurst arr ee
BECK Calculate();
ee)
oon
ae
Recursion
Recursion is when a function calls a copy of itself to work on a minor problem. The function that calls itself is
known as the Recursive function.
recurse() {
cero 1)Strings
Itis a collection of characters surrounded by double quotes.
Creating String Variable
g Length
Retums the length of the string.
PSEC eC sd
PTE Cast ts SesUrietst
Re susie Cm PaCS LO DH
g Methods toUpperCase()
Convert the string into uppercase.
Teta
Prete tees
Pyotr any Creare cl Tscerts 10p)
toLowerCase()
Convert the string into lowercase.
ET oets
Pree tec CRT Ciect rit
String var_name = "Harr[Sstiel)
indexOf()
Retums the index of a specified character from the string.
ET Sete
Pr SeCae VeCTCR en iesur ite Die
Ra seurst ac acu)
concat()
Used to concatenate two strings.
PSEC CaS
public static void main(String argst])
String vari = "Harry"
oi
Tome ita Creamer te
Math Class
Math class allows you to perform mathematical operations.
Methods max() method
Itis used to find the greater number among the two
Dey
static void main(Stringl] a:Sua Cen mana