0% found this document useful (0 votes)
23 views

Dominating Java 1686371898

Uploaded by

Varun Jain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
23 views

Dominating Java 1686371898

Uploaded by

Varun Jain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 22
JAVA PROGRAMMING CHEATSHEET We summarize the most commonly used Java language features and APIs in the textbook. Hello, World. tet filename Heer java | Tain meth public class/HeTioworTa) _/ ee ae public static void wain(String{ args) t ‘Systen.out Editing, compiling, and executing. seccnytectei to ype java Hel Ter java pe java HeTToborid ‘ae ear rogram ‘comply prorat "wears peur progam, feitor}--HeVioworie.java--{ compiler |--eTieborid.ctass--[JVAE]-~"Hetl0, wore | 1 t yu prog computer language ei (meh) someon regen Built-in data types. pe tof vues ramon opentirs sample tera vives ine inseges +t 798 a2 2147483647 double floating-point numbers Hot / 3.14 2.5 6.022623 boolean boolean ves wit true false char urate Ane Nn s String sequenees of characters, + "AB" "HeTTo [Eisatyaranjan Swain Declaration and assignment statements. xan sano sarcterame TER “a = 24] csigoeet 7 age [ine-€ = as Bi Z nine nition Integers. values integers between ~2" and 421 rpc tea 1234 99 © 1000000 persons | sgn add subeact ——hiply vie ops | = + - . ’ cexpresion value comment 8 99 3 ing iral +9 postive sgn “99-99 egies eT 5-3 2 subcton S* 315 mutipiton 5/32 wofrcions port 5x32 remainder 1/0 rurtine ror B*5-2 13“ haeprecdence 3B45/2 —S —shasprecdence 3-5-2 -4 Ietawacane (3-59-2 -8 — betersple B= €5=29 0 unambiguous Floating-point numbers. vas eal numbers (specifi by EE 754 standard) rel ites 3.14159 6.022023 2.0 1.4142135623730052 perations edd aubrey vide persons + - . / [Bisatyaranjan Swain exorsion due Basi + 2.0 Saat 3.41 - 2.0 au Bad / 2.0 1.5705 5.0/3.0 1.656ss66cese6667 20.0% 3.042 0.57 1.0/0.0 Infinity Math.sart(2.0) 1.4142135623730952 math. sqre(-1.0) an Booleans. values ‘rue or fale lorie | true false persion | and oe not openiors | I]t a Ja a b awe ayo true false false false false false false true false true false true true false false true ‘Comparison operators. op meaning false = pul zs ie rot egual 222 < des than 2<2 = batthanoregual = 22 3a? > graerthn = «> 2D >= gruterthan orequal <2 >=2 2d non-negative discriminant? (heb ~ &.0Fate) >= 0.0 bexiomingofaconury? (year % 100) = 0 leg mont oonth >= 1) && Caonth <= 12) Printing. void System.out.print(String s) prints Void Systen.out.printin(String 5) prints, followed bya newline void System.out.printin( printa newline [Eisatyaranjan Swain Parsing commanc/line arguments. int Integer.parsernt(String 5) convert stoan int alue double Double.parseDouble(String s) convert stoa doubTe value Tong Long.parseLong(string s) converts toa Tong alae Math library. public class Math double abs(éouble a) absolute valu of a double max(double a, double b) maximum of aand b double min(double a, double b) minimum of aand b double sin(double theta) sine of theta double cos(double theta) cosine of theta double tan(double theta) tangent of theta double toRadians(double degrees) convert angle from degrees to radians double toDegrees(double radians) convert angle from radians to degrees double exp(éouble a) exponential (e) double TogCéouble a) anual lg (og, os 2) double pon(double a, double b) mise ator nk power (at) ‘long round¢doubte a) round a tothe nearest integer double randon() random nurber in (0,1) double sqrt(éouble a) square root of double € value of costa) double Pr value of (constant) The full java.lang.Math API Java library calls. meth call ary rete ype Integer parseine("i23") Integer int STE} Double.parseDouble("2.5") Double double Ls Math.sqrt(S.0°5.0 - 4.08.0) Math double 3.0 Math. Tog(Math.£) math double 10 Wath. randox() Math double random in[0,1) Nath-round(3.14159) Math Tong 3 Nath.max(1.0, 9.0) mach double 9.0 Type conversion. —_ a Ge 2e3+H 740 double 25 Hach. sartca) cowie 2.0 "aM" + 99 Seeing "123499" 1 0.25 double 2.75 im) 1140.25 double 2.75, 11 * Cine) 0.25, int ine) aa * 0.25) int 2 (ine) 2.71828 int? Maeh.round(2.71828) Yong 3 ine) wan.rourd(2.71826) ine 3 rncegersparseTntC1234") int 1234 Anatomy of an if statement, be eesion : if (ey) Itand if-else statements. stohaewhe |i (44004 oo juliiemmaite,| {fF 8297 ier || | ine snddelge | ¥ micay | 7-8 ee tama | if er amo esas | cine 2 Sage woraed 4 Gdn == 0) Syscen.ovt.prinetn Division by zero"); evden | BE Sen out priming Qutiene © 5 mum/sens S ste out priming a sen) | double discrininane = BB = am SPalecrisinane 0.0) ‘ cenecea | SAtMANE BREN rst rates for quadratic | sas¢ ‘erm | Systen.outprintIn((-b + Hath sareéiser inne) /2.0; SPER ME Prince eb Math Serecescrtatnen 5/2203; [Bsatyaranjan swain Nested if-else statement. if Cincone < 0) rate else if Cincone < 8925) rate else if Gincone < 36250) rate else if Cincone < 87850) rate else if income < 183250) rate else if Cincone < 398350) rate else if Gincome < 400000) rate else rate Anatomy of a while loop. Anatomy of a for loop. enti wien, ee cee en, |B ee 1 [Risatyaranjan Swain Loops. compute the largest ower of2 lew than or eu to compute fit sums (e2e..98) somput fit produt Gam 12 as Xm) Print a table of urtion als comput the raler faction (Gee Pacem 121) Break statement, int factor ‘int power = 1; while (power & 9/2) powcr = Zipowert System, out.prineln(poner nt sun = 0: for Gint i sums fj System. out.prinen¢sum; fem i int produce = 1; for Gat t= 1; product *= i; System, out.printin product} 2 i for Cnt i ‘system.out.printing + + PeMath. PIM /m); String ruler for Cnt i= ruler = ruler + System, out prineinceuler): "+ mater: for (factor = 2; factor <= n/factor; factor++) if (n% factor = 0) break: if (factor > n/factor) System.out.printin(n +" is prime"); Do-while loop. 0 { // Scale x and y to be random in (-1, 1) ‘Switch statement. -0*Nath.randon() = 1.0; y = 2.0¢Math.random() - 1. 2} while ath. sartGex + y*y) > 1.0); [Risatyaranjan Swain rs) switch (day) £ case 0: System.out.printin("Sun"); break case 1: System.out.printInC'Mon"); break case 2: System.out.printinC"Tue"); break case 3: System.out.printinC"wed"); break; case 4: System-out.printin("Thu"); break; case 5: System.out.printinC"Fri"); break: case 6: System-out.printin("Sat"); break; ato aly atzi al ata ats ator at Inline array initialization, Typical array-processing code. doublet] a = new doubletn] for Cint 420; wax) wax = ah "double sue = 0. compute the werageof | For Cine 4 = the array values ‘sum = ai] sum / ni double average for (int 1 = 0; 1 < 9/2; is) t [Risatyaranjan Swain nyu | Goat) & = gem dub); toanotheraray bey = ai ‘Two-dimensional arrays. anya Inline initialization. double OO a = 4 8s. 70, 62. 94.0, 76: 58. 65. 70.5, 39. ‘Our standard output library. public class Stdout void print(String s) Print 5 tandand output void printin(string s) rit Sand a nelne wo standard ouput void printing) rin newline standard output rin! dhe arguments to standard utp void printf(String format, ... ) 2m eau ean The full StdOut API. [Bisatyaranjan swain Formatted printing. format (orn mite nt 1 i seaoue. prince {KL . Hath. FID satmias” | cron retin tion 7 pict senple comer ing mee; ele ‘eral forma siings values for output vue t sat m4 m2 ee * sae 1595.17" dowie £ asgs.sssoon0rsesss 574" 595. 368001i" idee S032e-03" string "Helo, worte™ boolean b true 0" rue ‘Our standard input library. public class Stdin rts for roading val ok from tadard put boolean istmpty( readInt© readbouble() eadBooleanQ) readString() int double boolean Sering {standard input empty (or ony whitespace)? ad ator, cnvert tint and return t rad a toe, convert it a doubted return it ad a take, convert it bootean end return it ead a token and return tava String methods for reading characes rom standard input boolean hasNextchar© char readchar() meds fr reading kines from standard input boolean hasNextLine@) String readtineQ eds for reading th res of andar input inet double] booteant] Stringl] strina{] String readAl1IntsO readAl Doubles) readA11BooTeans() readAlIStringsO readAliLines( readA10 [Eisatyaranjan Swain les standard input have any remaining characte? read a characte from suandard input and remit does standard inp have ame lin rad he ret of he iad return ta String rad al remaining tokens and return ther as a sme arsy ‘read al remaining tokens and return them ata double aay rad al remaining tobens and return them as a boolean aay ad al remaining rolens and renun them asa String ary ed al rnaivng nes and reture them asa Seringaray read the ret of the input and return it asa Seeing The fun Stain API. ‘Our standard drawing library. “public class Stddraw wing commands void TineCdouble x0, double yO, double x1, double yi) void point (double x, double y) void circle@double x, double y, double radius) void fiTledcircle(double x, double y, double radius) void square(double x, double y, double radius) void fiTledSquare(double x, double y, double radius) void rectangle(double x, double y, double rl, double r2) void fiTledRectangle(éouble x, double y, double ri, double r2) void polygon(doublel} x, doublet] y> FiNedPalygon(double(} x, doublet) text(double x, double y, String s) void void coma commands Void setXscate(double x0, double x1) setYscale(double y0, double y1) setPenRadius(double radius) setPenColor(Color color) setFont (Font. font) setCanvassizeCint w, int h) ‘enableDoublepufferina® disabledoubleBuf fering) void void void void void void void void. show void clear(Color color) pauseCint dt) save(String filename) void void The full StcDraw API. (Our standard audio library. public class StdAudio void play(String Filenane) play(double[] a) play(double x) void void void doublet] read(string Fitenane) Y riser see (40,2) reser sale (¥0, y1) erponradiustoradive set pencolort color set ex fort 0 font stra ie Wb enable double bering ible double bering py the officer amas fr omcreen ase lear the anasto olor coor paused milseconds veto -Jogor -pog ie a gen nd are ply ape fr oo znd save(String filename, double[] a) sae ia.wav fle read fom a.nav file [Eisatyaranjan Swain The full StdAudio API, Command line. public class Addints e peotic static void maintstrinat} eras) ine n ~ integer parsaine (arg ine fun SUR ne WF Gine A= 05 4 < nj Hoey Petcconmand for Gine 15 0; 4 data.txt Randonseq % java Randonseq 1000 | java Average Randonsea average Functions. [Eisatyaranjan Swain omg ine conan poem (fave Anes 8 ps 233 ant apa seams | (sun 15-2778) gander otpa rar a7 % java Average < data.txt data.tet rd Average absolute value ofan Sn value ahsoice vane of ‘doubre value armani amber ior random tng 8) rae a range public static int absCine 0 e Af (& < 0 return ~ else return x: 2 public static double abs (double 20 « 4f (x < 0.0) return - else return public static boolean isPrine(int a) if (<2) return false; for Gint 4 021 te fis 60) Gf (m7 m2 0) return False; return true; public static double hypotenuse(doubTe a, double b) return Math. sart(ata + bb); ) public static double harmonieGint n) e ‘double sum = 0.0; fer Gnt i= 4; 1 ens iH) sun ee 1.0/4; return sum; public static int uniformCint A) {Coreturn Cnt) (Math.random * m5 > public static void drantriangle(double x0, double ¥0, ouble x1, double 2 ouble 32, double y2") « StdDraw.ine(x0, 0, x1, y2) StdDraw Tine (a, 91) 32) 92 ‘SteDraw-TineGzZ) ¥2) 30, YO} ? Libraries of functions. set [Gaussian.paF0 | [causstan. cotta) | 2 roy methods an public class Ga ‘ouble pa double x) double eadube 2) e | ne res public static double cafdatle 2) eee} Jemendehat mylene ary meds ‘Our standard random library. public class Stétandom void setSeed(long seed) int uniformintGint m) aad for opredeccre Itger beac Oa 2-2 double unifornbouble(double 10, double Bi) rei! ewer Jound hi boolean bernouli (double p) ue with probabil 9 double gaussian ora mean snarl deviation double gaussian(doubTe mu, double signa) —— nara an my sda devarion s¥oma ‘int discrete(double(] probabilities) wil prabubiiy probabiTictestid void shuffle(doublet] a) der she the ars a) The full StdRandom API, Our standard statistics library. public class Stastats double max(doubTel] a) Tangs vale double min(doubte[} a) sae value double mean(double[] a) average double var(double{] a) sample variance double stddev(doublel] a) samp standard deviation double median(double[] a) median void plotPoints(double[] a) plot points at (4, 2613) void plotLines(doublet] a) lot ines connecting Ci, a1) void plotBars(double[] a) The full StdStats API. lt bars to points at C3, aC) Using an object. dare vrai same) Instance variables, public class Charge « > iasealer > Constructors. =, sn eee femme = ee ree sh ea [pabT¥e} [Charge] C[doubTe wo), [double yo), [double 0] moe : ioe fanaber Classes. public class Charge , a tnsgge [private Final double rx, yi] he vwralia—~ private final double @: suuirucur—-| PUBTi€ Charge (double x9, double yO, double a0) {mes x0; y= yi qs a0; } ‘public double potencjalAtCdouble x, double y) £ cane double k = 8.98609; xe double dx = x = rx? se double dy = y - ry; nace return k* q / Math. sqrt(dxtdx + dy*dy) makes [P \ public Sering eoStringG) 7 EC oreurng eat "Ce ee a yw esciew ——=| PUBTIE StatTe void matnGSerinal] ares) £ double x = Doubte.parseDouble(arest01) double y = Double. parseboube(args()): a ‘nfltee— Gharge e2 = nev Gharge(Os13, 0.34, - double vi = cl.potentialat(x, y) pe dass Gare GireGndle dae, le double poteniatatéoble x, ae y) iat” string sarin jaa X. fests nt dere metode ‘ONE Careanble 98, dable 0, cable ‘ible daable poerelaihsGouble % dole) ears Java's String data type. public class String String(sering §) ng eee sevingcehart] =) Secenenaiacneimniieme ‘int Tergtho ner fcc ‘char charktine 4) the cancer vines 4 String substringCint 1, int 3 haces ati § ough (F-2) boolean contains(String substring) dusting onnin subsering? boolean startsWith(String prefix) dws thisrng st wih profit boolean endsWith(String postfix) shes tsstringend wi pose Fit int indexor(string pattern) ‘nde fies cron pacer ‘int indexOF(String pattern, imt 4) _iniesfieteaurene opatcernaie String concatString t) hissing wih Capen {int compareto(string ©) sing comparison String tolowerCased issn, it ome es String. tovppercaseO hissing wih appre es String replace(string a, String 6) thissring wih as eplas ly bs String tris) ‘ising thing an aig hiepacerenoved bootean matches oye « ron Quevecnceger> shtie {ISedin sstrpey0) sacenqueve Stet esetne023 rtm srt eunee) rh ‘Our symbol table data type, public class STckey extends ConparablecKey>, Value> STO ‘atc am emp stl ale void put(Key key, Value val) avocinte val with Key Value get(key key) ele cited wih ay void reneve(Key key) remove hy (ends cited ve) boolean contains (Key key) itera vale acid with hey? int sizeO eof ya pairs Tterableckey> keys ys he sb abe The full ST API. ‘Our set data type. public class SET> inplenents IterablecKey> ETO rate anempiy set boolean istmptyO seth stomp? void add¢key key) ad key the et void renovetkey key) remove key from et boolean contains(Key key) is eyinshowi? ine sizeQ) ie of elements set The full SET API. ‘Our graph data type. public class Graph Graph ‘rsa an empty raph Graph(String Filename, String delimiter) creategaphjrom fle void addEdgedString v, String w) add edge vo int VO rare of eres int £0 rier of ees IterablesString> vertices verti in the graph Ffilsatyaranjan Swain IterablecString> adjacentTo(String v) neighbors af v int degree(String v) rune of mighborsofv boolean hasVertex(string v) fe va vertex he graph? boolean hasEdge(String v, String w) is oma edge the graph The full Graph API

You might also like