Java
The purpose of this page is to serve as a reference for the Java-curious user, to provide code to those interested, and to shameless reference our Java GitHub repository. This page contains a basic description of the general and technical aspects of the Java programming language, all the links an interested beginner would need, and a selection of more advanced Java snippets:
Java 101
We recognize that the Java resources available online are much better than what we can provide, therefore, we will simply outline the general and technical aspects of the Java programming language and then provide links to, what we consider are the better Java resources. The facts of Java:
Uses: | Application, Mobile, Web, Business |
Website: | java.com |
Get Started: | Setting Up and Getting Started in Java Programming |
Download: | java.com/download |
Documents: | docs.oracle.com/java |
Creator: | James Gosling |
First Released: |
January 23, 1996
|
Implementation: | Mostly Compiled with some Interpreted |
Type Safety: | Strong |
Type System: | Explicit |
Type Checking: | Static |
Imperative: | Yes |
Aspect Oriented: | Yes |
Object Oriented: | Yes |
Functional: | Yes |
Procedural: | Yes |
Generic: | Yes |
Reflective: | Yes |
Event Driven: | Yes |
Standardized: | Yes (Java Language Specification) |
Failsafe I/O: | Yes |
Garbage Collected: | Yes |
As programmers, we are obligated to refer to the official documentation; and we suggest that new users try Oracle’s documentation. In the cases where the documentation is well formatted, written, and maintained (we’re looking at you Python), this usually works. If, for whatever reason, you are unable to stomach the Oracle documentation, or for those whom identify as the “visual” type, there is an abundance of online video and learning platforms that also provide proven Java content. Several resources we recommend, and occasionally utilize, are YouTube and the online courses at Udemy. YouTubers, such as Derek Banas, are great for a very fast overviews of a language or technology, where online courses like Udemy can have classes spanning dozens of hours. Finally, if new Java users want to develop in more than a text editor, then hunting for a Java Integrated Development Environment (IDE) may cause overchoice due to the large number of IDEs available. Java IDEs contains a lengthy list of possibilities; in the past we have used Eclipse and NetBeans, although currently we use IntelliJ CE (and are very satisfied with all it has to offer).
Java Review
As briefly outlined on the Projects page, mpettersson has a Java repository, named JavaReview publicly available on GitHub. The two main components of this repo are; first, a thorough review of basic Java syntax, and second, a series of programming questions and corresponding answers implemented in Java. The present majority of the programming questions are from the Cracking the Coding Interview book by Gayle Laakmann McDowell, however, more will be included from different sources in the future.
For the full repository, specifically the programming interview questions see github.com/mpettersson/JavaReview, or for the review component, continue reading below.
Java.java
This monstrous file, packed full of classes, is our Java review. Some of the code and topics demonstrated include:
- Types
- Control Flow
- I/O
- Provided Data Structures
- Exception Handeling
- Classes
- Generics
- Lambda Expressions
- Streams
- And Concurrency
In addition to being a simple Java language review, Java.java can be used as a concise tutorial for experienced programmers in other languages that are new to Java. The majority of the time, we simply use it as a single source of reference when we experience brain flatulence. Honestly, it ain’t pretty, but it works for us.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 |
package com.mpettersson.review; import org.junit.jupiter.api.*; import org.junit.jupiter.api.Test; import java.io.*; import java.net.InetAddress; import java.nio.file.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.*; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.*; public class Java { // Enums public enum Day {Monday, Tuesday, Wednesday}; public static void main(String[] args) { // Single line comment /** * Multi line comment, used by javadocs (documentation) */ /* Multi line comment */ //////////////////////// // NAMING CONVENTIONS // //////////////////////// /** * PACKAGES * - Always lowercase * - Should be unique * - Use your internet domain name reversed as prefix for package. * - Replace invalid characters with underscore (_), i.e., experts-exchange.com --> com.experts_exchange * - Domain name components starting with a number should start with an underscore (_), i.e., 1world.com --> com._1world * - Domain name components that are java key words should start with an underscore (_), i.e., switch.supplier.com --> com.supplier._switch * * CLASSES * - CamelCase * - Should start with a capital letter * - Each word in the name should also start with a capital letter. * - Should be a nouns. * * INTERFACES * - CamelCase * - Should start with a capital letter. * - Each word in the name should also start with a capital letter. * - Can start with I (old convention) * * METHODS * - MixedCase * - Should start with a lowercase letter. * - Each word in the name should start with a capital letter. * - Often Verbs * * CONSTANTS * - All upper case. * - Separate words with an underscore (_) * - Declare using the final keyword. * * VARIABLES * - MixedCase * - Should start with a lowercase letter. * - Each word in the name should start with a capital letter. * - No underscores (_). * * TYPE PARAMETERS * - Single Capital Letter. * - examples: * E - Element * K - Key * V - Value * S, U, V, etc. - 2nd, 3rd, 4th types. * ? - Is the Unknown Type. * */ //////////////////////////// // 8 PRIMITIVE DATA TYPES // //////////////////////////// // null is case sensitive in java, i.e., you CAN'T use NULL! // final variables can't be changed once initialized (can declare and define/initalize in two different lines). // Multiple variables of the same type can declared and assigned at once: int a = 10, b = 11, c = 12; // BYTE - 8 bits final byte myMinByte = -128; byte myMaxByte = 127; byte byteCastExample = (byte) (myMinByte / 2); // How to cast. // SHORT - 16 bits short myMinShort = -32768; short myMaxShort = 32767; // INT - 32 bits int myMinInt = -2_147_483_648; // You can use underscores now... int myMaxInt = 2_147_483_647; // LONG - 64 bits long myMinLong = -9_223_372_036_854_775_808L; // Need to put a 'L' or 'l' behind it. long myMaxLong = 9_223_372_036_854_775_807L; // NOTE there isn't anything for short or byte. // FLOAT - 32 BITS - 7 decial digit percision float myFloatValue = 5F / 3f; // Should cast or use either 'F' or 'f' for float System.out.println("myFloatValue: " + myFloatValue); // DOUBLE - 64 BITS - has 16 decial digit percision // NOTE: USE DOUBLE OVER FLOAT, double is usually faster on modern computers and many of java's functions use it double myDoubleValue = 5d / 3D; // Should cast or use either 'D' or 'd' for double double pi = 3.141_592_7d; // can use literals in numbers in java 7 or greater System.out.println("myDoubleValue: " + myDoubleValue); // CHAR - 16 bits, can be unicode or ASCII, remember there is only 128 ASCII... char myChar = '#'; // has to use single quotes. char copyrightChar = '\u00a9'; // can be unicode System.out.println("Unicode copyright char: '\\u00a9' = " + copyrightChar); System.out.println("ASCII to char: (char)42 = " + (char)42); System.out.println("Char to ASCII: (int)'*' = " + (int)'*'); // BOOLEAN - No defined size boolean myBoolean = true; // boolean from string: boolean trueFlag = Boolean.valueOf("true"); boolean falseFlag = Boolean.valueOf("false"); // Primitive Type Values: System.out.println("Byte.TYPE: " + Byte.TYPE); System.out.println("Byte.SIZE: " + Byte.SIZE); System.out.println("Byte.MIN_VALUE: " + Byte.MIN_VALUE); System.out.println("Byte.MAX_VALUE: " + Byte.MAX_VALUE); System.out.println("Short.TYPE: " + Short.TYPE); System.out.println("Short.SIZE: " + Short.SIZE); System.out.println("Short.MIN_VALUE: " + Short.MIN_VALUE); System.out.println("Short.MAX_VALUE: " + Short.MAX_VALUE); System.out.println("Integer.TYPE: " + Integer.TYPE); System.out.println("Integer.SIZE: " + Integer.SIZE); System.out.println("Integer.MIN_VALUE: "+ Integer.MIN_VALUE); System.out.println("Integer.MAX_VALUE: "+ Integer.MAX_VALUE); System.out.println("Long.TYPE: " + Long.TYPE); System.out.println("Long.SIZE: " + Long.SIZE); System.out.println("Long.MIN_VALUE: " + Long.MIN_VALUE); System.out.println("Long.MAX_VALUE: " + Long.MAX_VALUE); System.out.println("Float.TYPE: " + Float.TYPE); System.out.println("Float.SIZE: " + Float.SIZE); System.out.println("Float.MIN_VALUE: " + Float.MIN_VALUE); System.out.println("Float.MAX_VALUE: " + Float.MAX_VALUE); System.out.println("Double.TYPE: " + Double.TYPE); System.out.println("Double.SIZE: " + Double.SIZE); System.out.println("Double.MIN_VALUE: " + Double.MIN_VALUE); System.out.println("Double.MAX_VALUE: " + Double.MAX_VALUE); System.out.println("Boolean.TYPE: " + Boolean.TYPE); System.out.println("Character.TYPE: " + Character.TYPE); System.out.println("Character.SIZE: " + Character.SIZE); System.out.println("(int) Character.MIN_VALUE): " + (int) Character.MIN_VALUE); System.out.println("(int) Character.MAX_VALUE): " + (int) Character.MAX_VALUE); // Common Math Functions int x = 10, y = 100; double d = 1.0 / 3.0; System.out.println("Math.max(" + x + ", " + y + "): " + Math.max(x, y)); System.out.println("Math.min(" + x + ", " + y + "): " + Math.min(x, y)); System.out.println("Math.pow(" + x + ", " + y + "): " + Math.pow(x, y)); System.out.println("Math.floorDiv(" + x + ", " + y + "): " + Math.floorDiv(x, y)); System.out.println("Math.floorMod(" + x + ", " + y + "): " + Math.floorMod(x, y)); System.out.println("Math.sqrt(" + x + "): " + Math.sqrt(x)); System.out.println("Math.log(" + x + "): " + Math.log(x)); System.out.println("Math.floor(" + d + "): " + Math.floor(d)); System.out.println("Math.ceil(" + d + "): " + Math.ceil(d)); System.out.println("Math.abs(" + x + "): " + Math.abs(x)); System.out.println("Math.random():" + Math.random()); // Returns double >= 0.0 and < 1.0 // How to get random values: System.out.println("Math.random():" + Math.random()); // Returns double >= 0.0 and < 1.0 int bound = 10; int seed = 100; byte[] bytes = new byte[10]; Random random = new Random(); random.nextInt(); // Returns int >= Integer.MIN_VALUE and <= Integer.MAX_VALUE random.nextInt(bound); // Returns int >=0 < bound, ONLY int can have bound. random.nextDouble(); // Returns double >= 0.0 and < 1.0 random.nextBytes(bytes); // Puts random bytes into each index of supplied array. random.nextBoolean(); random.setSeed(seed); System.out.println("random.nextInt(): " + random.nextInt()); System.out.println("random.nextInt(" + bound + "): " + random.nextInt(bound)); System.out.println("random.nextDouble(): " + random.nextDouble()); System.out.println("random.nextBytes(bytes): " + Arrays.toString(bytes)); System.out.println("random.nextBoolean(): " + random.nextBoolean()); System.out.println("random.setSeed(" + seed + ")"); // COMPARETO // // NOTE: The object type must extend Comparable, i.e., class MyObject<T extends Comparable> // Can't be primitive types (so use Integer for int, Double for double, etc...) // // Usage: // myObjectLeft<T>.compareTo(myObjectRight<T>) // // Results: // 0 if myObjectLeft == myObjectRight // -1 if myObjectLeft < myObjectRight (it's -1 no matter size i.e., 1 < 2 or 1 < 2222) // 1 if myObjectLeft > myObjectRight (it's 1 no matter size i.e., 2 > 1 or 2222 > 1) Integer one = 1; Integer negOne = -1; Integer six = 6; System.out.println(one + ".compareTo(" + one + ")" + one.compareTo(one)); // 1.compareTo(1) == 0 (1 == 1) System.out.println(one + ".compareTo(" + six + ")" + one.compareTo(six)); // 1.compareTo(6) == -1 (1 < 6) System.out.println(six + ".compareTo(" + one + ")" + six.compareTo(one)); // 6.compareTo(1) == 1 (6 > 1) System.out.println(one + ".compareTo(" + negOne + ")" + six.compareTo(negOne)); // 6.compareTo(-1) == 1 (6 > -1) ///////////// // STRINGS // ///////////// // Strings are a class/Object and not a primitive type. String myString = "This is my string!"; String strHello = "Hello"; String strWorld = "World"; String eol = System.lineSeparator(); // Concat with System.out.println(strHello + strWorld); // This will automatically convert to string System.out.println(strHello.concat(strWorld)); // This WILL NOT automatically convert to string!!! // NOTE: You can assign null to a string, BUT, it'll cause exceptions with many of the common string ops. String nullString = null; System.out.println(nullString); String emptyString = ""; // Find string length with <stringVar>.length(); System.out.println("emptyString.length() = " + emptyString.length()); // Find if string is empty (i.e., length == 0) with <stringVar>.isEmpty(); System.out.println("emptyString.isEmpty() = " + emptyString.isEmpty()); String example = "This should be complicated enough to show some things we should show"; // Find the characters at the indexes given System.out.println(example.charAt(0)); System.out.println(example.charAt(5)); // An StringIndexOutOfBoundsException is thrown in both these cases: // System.out.println(example.charAt(-1)); // System.out.println(example.charAt(200)); // Find the index of characters or substrings System.out.println(example.indexOf('s')); // returns the first occurence of 's' System.out.println(example.indexOf('s', 4)); // the first 's' after index 4 System.out.println(example.indexOf("should")); // the index of the first "should" in our string System.out.println(example.indexOf("should", 15)); // the index of the first "should" in our // Find the last index of characters or substrings System.out.println(example.lastIndexOf('s')); // returns the first occurence of 's' when we look backwards from the end of the string System.out.println(example.lastIndexOf('s', 45)); // searches for 's' backwards from the position 45 System.out.println(example.lastIndexOf("should")); // returns the position at which the substring 'should' appears, looking backwards from the end of the string System.out.println(example.lastIndexOf("should", 20)); // finds substring 'should' from position 20 backwards, and returns the position at which it begins // The compareTo() method compares the Unicode value of two strings and returns a NUMBER. System.out.println("a".compareTo("a")); System.out.println("a".compareTo("b")); System.out.println("1".compareTo("12345678")); // Get substrings with substring() method. System.out.println(example.substring(2)); System.out.println(example.substring(5,11)); // Trim off the leading and trailing whitespace with .trim() String ourString = " Any non-leading and non-trailing whitespace is \n preserved "; System.out.println(ourString.trim()); // Printf: formatted output // %s : strings // %d : Integers // %f : Floats/Doubles // %c : Characters // %e : Scientific Notation // %t : Dates // %b : Booleans // %o : Octal // %h : Hex // The format syntax is: %[argument_index$][flags][width][.precision]conversion double ourDouble = 1123.9303; System.out.println(String.format("%f", ourDouble)); System.out.println(String.format("%.3f", ourDouble)); // specifies that we only want 3 digits after decimal point System.out.println(String.format("%e", ourDouble)); String formatString = "what does precision do with strings?"; System.out.println(String.format("%.8s", formatString)); // prints the first 8 characters of our string int ourInt = 123456789; // System.out.println(String.format("%.4d", ourInt)); // precision can't be used on ints // If our number has less than 6 digits, this will add extra 0s to the beginning until it does System.out.println(String.format("%06d", 12)); // If our number has more than 6 digits, it will just print it out System.out.println(String.format("%06d", 1234567)); // We can specify output width, with the output being aligned to the right if it's shorter than the given space. If it's // longer, everything gets printed. The || are added for demonstration purposes only System.out.println(String.format("|%20d|", 12)); // Or we can align the output to the left System.out.println(String.format("|%-20d|", 12)); // We can also easily print an octal/hexadecimal value of an integer System.out.println(String.format("Octal: %o, Hex: %x", 10, 10)); String replaceString = "We really don't like the letter e here"; System.out.println(replaceString.replace('e', 'a')); System.out.println(replaceString.replace("here", "there")); System.out.println(replaceString.replaceAll("e(r+)", "a")); System.out.println(replaceString.replaceFirst("e(r+)", "a")); // How to split a string using regex: String[] fruits = "apples, oranges, pears, pineapples".split(","); System.out.println(Arrays.toString(fruits)); // Using trim() to clean up some of the items. for(int i = 0; i < fruits.length; i++) { fruits[i] = fruits[i].trim(); } System.out.println(Arrays.toString(fruits)); // Arrays.toString() formats the output array on its own // This returns then prints an empty array, since every character is interpreted as something to be split at and ignored System.out.println(Arrays.toString("apples.oranges.pears.pineapples".split("."))); // The "regex safe" way of doing this would be System.out.println(Arrays.toString("apples.oranges.pears.pineapples".split(Pattern.quote(".")))); // Splits our string to two substrings at most, completely ignoring all other occurrences of "." System.out.println(Arrays.toString("apples.oranges.pears.pineapples".split(Pattern.quote("."), 2))); // Split strings at new lines: String lines[] = myString.split("[\\r\\n]+"); // Split strings at spaces: String spaces[] = myString.split("\\s+"); // examples of String.join() String arrayOfStrings[] = {"1","2","3","4","5"}; System.out.println(String.join("-", arrayOfStrings)); System.out.println(String.join("-", Arrays.asList(arrayOfStrings))); // Works just fine with lists as well System.out.println(String.join("", arrayOfStrings)); // How to convert a string to a char aray: System.out.println(Arrays.toString("How to convert a string to a Char Array".toCharArray())); // SORT STRING - No method to sort a string, but can do this: String stringToSort = "Hahaha, Sort ME!"; char[] chars = stringToSort.toCharArray(); Arrays.sort(chars); String sortedString = new String(chars); System.out.println(sortedString); // How to remove all whitespaces (and newlines) from a string: String strWithWhiteSpaces = " S\ttring wit h white spa\n c e s !!! "; System.out.println(strWithWhiteSpaces); System.out.println(strWithWhiteSpaces.replaceAll("\\s+", "")); ////////////////////////////////// // STRINGBUILDER & STRINGBUFFER // ////////////////////////////////// // StringBuffer - First, Thread Safe/Synchronized // StringBuilder - Second, NOT Thread Safe, Several times FASTER StringBuilder strBuilder = new StringBuilder("A Random Value"); // How to check the current capacity System.out.println(strBuilder.capacity()); // Get the length of the used string with .length() System.out.println(strBuilder.length()); // Append // NOTE: It will automatically add to the capacity if needed. System.out.println(strBuilder.append(" Again And Again And Again And Again And Again And Again And Again")); // Replace System.out.println(strBuilder.replace(2, 7,"NONRANDOM")); // Delete: System.out.println(strBuilder.delete(15, 21)); // Insert: System.out.println(strBuilder.insert(30, "String To Insert")); // Reverse: System.out.println(strBuilder.reverse()); // Print: System.out.println(strBuilder); // Use this to assign to a string System.out.println(strBuilder.toString()); /////////// // INPUT // /////////// // // Scanner Example: // Scanner sc = new Scanner(System.in); // System.out.print("Enter name: "); // if(sc.hasNextLine()){ // String userName = sc.nextLine(); // System.out.println("Hello " + userName); // } // // // Scanner Example with different types: // Scanner scanner = new Scanner(System.in); // System.out.println("Enter your name: "); // String name = scanner.nextLine(); // System.out.println("Your name is: " + name); // System.out.println("Enter your year of birth: "); // int year = scanner.nextInt(); // NOTE YOU HAVE TO CALL scanner.nextLine() to handle the newline (enter) if you want to do nextLine() for a string. // scanner.nextLine(); // System.out.println("Your age is: " + (2018 - year)); // scanner.close(); // // // JOPtion Pane Dialog Box Example: // String jopName = JOptionPane.showInputDialog("Enter name"); // System.out.println("Hello " + jopName); ///////////////////////////// // CONTROL FLOW STATEMENTS // ///////////////////////////// int someVar = 4; // Remember that assignment returns the value assigned, so it has some weird cases... if((someVar = 10) == 10){ System.out.println("what"); } boolean blah; if(blah = true){ System.out.println("this is the 'if' with an assignment."); } // NOTE: Unlike other languages (python, C/C++, etc.) numbers cannot be used in place of booleans. // The following (commented out code), has an error ('Incompatible Types'): // if(1){ System.out.println("True"); } // Whitespace and indenting stuff... int anothervar=5; System.out.println(anothervar); int anotherMessedUp = 5 ; System.out.println(anotherMessedUp); String mySwitchString = "matt"; switch(mySwitchString){ case "matt": System.out.println("input was matt"); break; case "no": System.out.println("input was no"); break; default: System.out.println("blah"); } // Can use byte, short, char, int, and Strings with switch statements. int switchValue = 1; switch(switchValue){ case 1: System.out.println("Value was 1"); break; case 2: System.out.println("Value was 2"); break; case 3: case 4: case 5: // How to have multiple values in a case. System.out.println("Value was 3, 4, or 5."); default: System.out.println("In default case..."); break; // Don't really need a break here, but it's probably good to add it. } int count = 1; while(count != 6){ System.out.println("count value is " + count); count++; } for(int i = 6; i !=6; i++){ System.out.println("count value is " + count); } count = 1; do{ System.out.println("count value is " + count); if(count > 100){ break; } count++; }while(count != 6); String numberAsString = "2018"; int intNumber = Integer.parseInt(numberAsString); double doubleNumber = Double.parseDouble(numberAsString); System.out.printf("This is the value for intNumber: %d and this is the value for doubleNumber: %f.\n", intNumber, doubleNumber); //////////// // ARRAYS // //////////// System.out.println("\nArrays Examples"); // PRIMITIVE ARRAYS: int[] myIntArray1 = new int[3]; int[] myIntArray2 = {1, 2, 3}; int[] myIntArray3 = new int[]{1, 2, 3}; // CLASS/STRING ARRAYS: String[] myStringArray1 = new String[3]; String[] myStringArray2 = {"a", "b", "c"}; String[] myStringArray3 = new String[]{"a", "b", "c"}; //Declare and Initialize in separate statements: String[] myStringArray4; myStringArray4 = new String[]{"a", "b", "c"}; // The cast is necessary. // Multidimentional int[][] multiDimArray = {{1,2}, {1,2}, {1,2}, {1,2}, {1,2}}; // How to copy arrays: // NOTE: Anything other than primitive data types will have shallow copies. int a1[] = {1,2,3}; int a2[] = Arrays.copyOf(a1, 3); System.out.println(a2[0] + " " + a2[1] + " " + a2[2]); // How to sort an Array: int a3[] = {8, 7, 5, 2, 1}; Arrays.sort(a3); // How to print an Array: System.out.println("Arrays.toString(a3): " + Arrays.toString(a3)); //////////////////////////// // COLLECTION (INTERFACE) // //////////////////////////// // A collection represents a group of objects, known as its elements. The Collection interface is the root // interface in the collection hierarchy, that is, List Set and Queue interfaces extend the Collection interface. // Although the Map interface does not extend/implement the Collection interface (because Map hash key value // paris), it is considered part of the Collections Framework. // // The Collection interface is in the java.util package, some of it's more important methods include size(), // isEmpty(), contains(), iterator(), toArray(), add(E e) , remove(), clear(), equals(), and hashCode(). // // The four major data structure types in the Collections Framework are List, Set, Queue, and Map. // // LIST // Lists are ordered collections (sequences) of items that are accessed via an integer index, and typically // allow duplicate values. The following are implemented List classes: // Vector - Synchronized, growable array of objects accessed via an int index. // Stack - Synchronized, Last-In-First-Out (LIFO) stack of objects (extends Vector). // ArrayList - NOT synchronized, resizeable array implementation of List, allows nulls. // LinkedList - NOT synchronized, doubly-linked list implementation (extends AbstractSequentialList). // // SET // Sets are collections that do not allow duplicate elements, and model the mathematical set abstraction. The // following are implemented Set classes: // HashSet - NOT synchronized, Set implementation by HashMap, allows one null, NOT ordered. // LinkedHashSet - NOT synchronized, Hashtable & LinkedList imp of Set, ordered via doubly-linked list. // TreeSet - Not synchronized, NavigableSet implementation based on HashMap, allows one null, NOT ordered. // // QUEUE // Queues are "a collection designed for holding elements prior to processing". Queues typically, but do not // necessarily, order elements in a FIFO (first-in-first-out) manner. Among the exceptions are priority queues, // which order elements according to a supplied comparator, or the elements' natural ordering, and LIFO queues // (or stacks) which order the elements LIFO (last-in-first-out). The implemented Queue classes are: // ArrayDequeue - NOT synchronized, resizable-array imp of the Deque interface, nulls NOT allowed. // PriorityQueue - NOT synchronized, unbounded priority queue (First-In-First-Out) based on a priority heap. // NOTE: LinkedList implements Dequeue. // // MAP // A Map is an object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most // one value. The Map interface is interesting in that it does not implement or extend any other class. // Implemented Map classes include: // HashMap - NOT synchronized, Hashtable based imp of Map, allows null vals and 1 null key, no order guarantees. // Hashtable - Synchronized, Hashtable imp of Map, null NOT allowed, NOT ordered. // TreeMap - NOT synchronized, Red-Black tree based NavigableMap imp; (ordered) SORTED by keys. // LinkedHashMap - NOT synchronized, HashTable & LinkedList imp of the Map interface, ordered via dlinkedlist. // IdentityHashMap - NOT synchronized, HashTable based Map imp using reference-equality when comparing keys. // // To iterate over a collection, without modifying it, use the for-each loop (for(Element e: collection)...). // To iterate over and access collection elements use; Enumeration, Iterator, and ListIterator. // // ENUMERATION // The Enumeration Interface was the first iterator, present in JDK 1.0, and only works on legacy collections // (Vector and Hashtable). Only three methods were provided; hasMoreElements(), nextElement(), and asIterator(). // It can only iterate in a forward direction (and can't Remove/Add/Set elements). // // ITERATOR // Added in Java 1.2, "Iterator takes the place of Enumeration in the Java Collections Framework". Iterators can // read and remove elements on ALL Collection objects. Iterator methods include: hasNext(), next(), remove, and // forEachRemaining(). // // LISTITERATOR // ListIterator extends Iterator, is ONLY available to lists (only AbstractList implements it), allows for // Bi-Directional movement, and can add/remove/set elements. ListIterator has hasNext(), next(), hasPrevious(), // previous(), nextIndex(), previousIndex(), remove(), set(E e) and add(E e) methods. // // NOTE: ListIterator has no "current" element, that it always lies between the element that would be returned // by a previous() call and the element that would be returned by a next() call, furthermore, the remove() and // set(E e) methods act on the last element returned by next()/previous(). /////////////////// // VECTOR (LIST) // /////////////////// // IS Synchronized System.out.println("\nVector Example"); // NOTE: You have to use Uppercase Integer here BC it needs classes not primitives. Vector<Integer> vector = new Vector<>(); vector.add(0); // Add 0 (at END) -- Autoboxing will auto-convert int to Integer vector.add(Integer.valueOf(1)); // Add 1 (at END) -- So don't have to do Integer.valueOf()... vector.add(2); // Add 1 (at END) vector.add(2, 99); // Add 99 at index 2 vector.add(0, -0); // Add -0 at index 0 vector.addAll(Arrays.asList(5,6,7,8)); // Add all elements of a collection. vector.set(2, 22); // Set value at index 2 to 22 vector.get(2); // Return value at index 2 -- Autoboxing will convert Integer to int. vector.get(0).intValue(); // Return value at index 0 -- So don't need to use intValue(). for(Integer i: vector){/* do stuff */} // Iterate Via Enhanced For Loop Iterator vectorIt = vector.iterator(); // Iterate Via ITERATOR while (vectorIt.hasNext()){vectorIt.next();} // And hasNext() method. Object[] vectorObjArray = vector.toArray(); // How to convert a Vector to an Object Array: System.out.println("vector.toString(): " + vector.toString()); System.out.println("vector.get(2): " + vector.get(2)); System.out.println("vector.indexOf(0): " + vector.indexOf(0)); System.out.println("vector.lastIndexOf(0): " + vector.lastIndexOf(0)); System.out.println("vector.lastElement(): " + vector.lastElement()); System.out.println("vector.isEmpty(): " + vector.isEmpty()); System.out.println("vector.contains(2): " + vector.contains(2)); System.out.println("vector.capacity(): " + vector.capacity()); System.out.println("vector.size(): " + vector.size()); vector.remove(0); // Remove and return item in index 0 vector.remove((Object) 2); // Remove object matching 2 (no exception if no match). vector.clear(); ////////////////// // STACK (LIST) // ////////////////// // Extends Vector. System.out.println("\nStack Example"); Stack<Integer> stack = new Stack<>(); stack.push(0); // Push 0 on stack (or end if viewed as list). for(int i = 1; i < 5; i++) { stack.push(i); } stack.add(99); // Add 99 to top of stack (or end if viewed as list). stack.addAll(Arrays.asList(5,6,7,8)); // Add all of a collection to stack. stack.set(2, 22); // Set value at index 2 to 22 stack.get(2); // Return value at index 2 for(Integer i: stack){/* do stuff */} // Iterate Via Enhanced For Loop Iterator stackIt = stack.iterator(); // Iterate Via ITERATOR while (stackIt.hasNext()){stackIt.next();} // And hasNext() method. Object[] stackObjArray = stack.toArray(); // How to convert to an Object Array: System.out.println("stack.get(2): " + stack.toString()); System.out.println("stack.get(2): " + stack.get(2)); System.out.println("stack.size(): " + stack.size()); System.out.println("stack.search(2): " + stack.search(2)); System.out.println("stack.peek(): " + stack.peek()); System.out.println("stack.empty(): " + stack.empty()); System.out.println("stack.pop(): " + stack.pop()); stack.pop(); stack.remove(0); // Remove and return item in index 0 stack.remove((Object) 2); // Remove object matching 2 (no exception if no match). stack.clear(); ////////////////////// // ARRAYLIST (LIST) // ////////////////////// System.out.println("\nArrayList Example"); ArrayList<Integer> arrayList = new ArrayList<>(); arrayList.add(0); // Add 0 (at tail) arrayList.add(Integer.valueOf(1)); // Add 1 (at tail) arrayList.add(2); // Add 1 (at tail) arrayList.add(2, 99); // Add 99 at index 2 arrayList.add(0, -0); // Add -0 at index 0 arrayList.addAll(Arrays.asList(5,6,7,8)); // Add all of a collection. arrayList.set(2, 22); // Set value at index 2 to 22 arrayList.get(2); // Return value at index 2 arrayList.get(0).intValue(); // Return value at index 0 for(Integer i: arrayList){/* do stuff */} // Iterate Via Enhanced For Loop Iterator arrayListIt = arrayList.iterator(); // Iterate Via ITERATOR while (arrayListIt.hasNext()){arrayListIt.next();} // And hasNext() method. Object[] arrayListObjArray = arrayList.toArray(); // How to convert to an Object Array: System.out.println("arrayList.toString(): " + arrayList.toString()); System.out.println("arrayList.get(2): " + arrayList.get(2)); System.out.println("arrayList.indexOf(0): " + arrayList.indexOf(0)); System.out.println("arrayList.lastIndexOf(0): " + arrayList.lastIndexOf(0)); System.out.println("arrayList.isEmpty(): " + arrayList.isEmpty()); System.out.println("arrayList.contains(2): " + arrayList.contains(2)); System.out.println("arrayList.size(): " + arrayList.size()); arrayList.remove(0); // Remove and return item in index 0 arrayList.remove((Object) 2); // Remove object matching 2 (no exception if no match). arrayList.clear(); /////////////////////////////// // LINKEDLIST (LIST & QUEUE) // /////////////////////////////// System.out.println("\nLinkedList Example"); LinkedList<Integer> linkedList = new LinkedList<>(); linkedList.add(0); // Add 0 (at tail) linkedList.add(Integer.valueOf(1)); // Add 1 (at tail) linkedList.add(2); // Add 1 (at tail) linkedList.add(2, 99); // Add 99 at index 2 linkedList.add(0, -0); // Add -0 at index 0 linkedList.addFirst(0); // Add 0 to head of linkedList linkedList.addLast(99); // Add 99 to tail of linkedList linkedList.addAll(Arrays.asList(5,6,7,8)); // Add all of a collection to stack. linkedList.set(2, 22); // Set value at index 2 to 22 linkedList.get(2); // Return value at index 2. linkedList.get(0).intValue(); // Return value at index 0. linkedList.getFirst(); // Return value at index 0. linkedList.getLast(); // Return value at last index. for(Integer i: linkedList){/* do stuff */} // Iterate Via Enhanced For Loop Iterator linkedListIt = linkedList.iterator(); // Iterate Via ITERATOR while (linkedListIt.hasNext()){linkedListIt.next();} // And hasNext() method. Object[] linkedListObjArray = linkedList.toArray(); // How to convert to an Object Array: System.out.println("linkedList.toString(): " + linkedList.toString()); System.out.println("linkedList.get(2): " + linkedList.get(2)); System.out.println("linkedList.getFirst(): " + linkedList.getFirst()); System.out.println("linkedList.getLast(): " + linkedList.getLast()); System.out.println("linkedList.indexOf(0): " + linkedList.indexOf(0)); System.out.println("linkedList.lastIndexOf(0): " + linkedList.lastIndexOf(0)); System.out.println("linkedList.isEmpty(): " + linkedList.isEmpty()); System.out.println("linkedList.contains(2): " + linkedList.contains(2)); System.out.println("linkedList.size(): " + linkedList.size()); linkedList.remove(0); // Remove and return item in index 0 linkedList.remove((Object) 2); // Remove object matching 2 (no exception if no match). linkedList.removeFirst(); linkedList.removeFirstOccurrence(0); linkedList.removeLast(); linkedList.removeLastOccurrence(0); linkedList.clear(); ////////////////////////// // ARRAYDEQUEUE (QUEUE) // ////////////////////////// // Poll/Element/Offer are the same as // Remove/Peek/Add except Remove/Peek throw Exceptions if there is no object. System.out.println("\nArrayDeque Example"); ArrayDeque<Integer> arrayDeque = new ArrayDeque<>(); arrayDeque.push(0); // Push 0 to head arrayDeque.add(0); // Add 0 (to tail) arrayDeque.add(2); // Add 1 (to tail) arrayDeque.addFirst(0); // Add 0 to head arrayDeque.addLast(99); // Add 99 to tail arrayDeque.addAll(Arrays.asList(5,6,7,8)); // Add all of a collection. arrayDeque.offer(99); // Add 99 to end. arrayDeque.offerFirst(-0); // Add -0 at head arrayDeque.offerLast(-9); // Add -0 at tail arrayDeque.getFirst(); // Return value at index 0. arrayDeque.getLast(); // Return value at last index. arrayDeque.peek(); // Return (but doesn't remove) head. arrayDeque.element(); // Return (but doesn't remove) head. for(Integer i: arrayDeque){/* do stuff */} // Iterate Via Enhanced For Loop Iterator arrayDequeueIt = arrayDeque.iterator(); // Iterate Via ITERATOR while (arrayDequeueIt.hasNext()){arrayDequeueIt.next();} // And hasNext() method. Object[] ArrayDequeueObjArray = arrayDeque.toArray(); // How to convert to an Object Array: System.out.println("arrayDeque.toString(): " + arrayDeque.toString()); System.out.println("arrayDeque.peek(): " + arrayDeque.peek()); System.out.println("arrayDeque.element(): " + arrayDeque.element()); System.out.println("arrayDeque.getFirst(): " + arrayDeque.getFirst()); System.out.println("arrayDeque.getLast(): " + arrayDeque.getLast()); System.out.println("arrayDeque.lastIndexOf(0): " + arrayDeque.pollFirst()); System.out.println("arrayDeque.isEmpty(): " + arrayDeque.isEmpty()); System.out.println("arrayDeque.contains(2): " + arrayDeque.contains(2)); System.out.println("arrayDeque.size(): " + arrayDeque.size()); arrayDeque.pop(); arrayDeque.remove(0); // Remove and return item in index 0 arrayDeque.remove((Object) 2); // Remove object matching 2 (no exception if no match). arrayDeque.removeFirst(); arrayDeque.removeFirstOccurrence(0); arrayDeque.removeLast(); arrayDeque.removeLastOccurrence(0); arrayDeque.clear(); /////////////////////////// // PRIORITYQUEUE (QUEUE) // /////////////////////////// // null values are NOT allowed. // Objects must be comparable. // Head of the queue is has lowest priority. // // PriorityQueue Constructor Options: // PriorityQueue() Uses default initial capacity (11) and natural ordering. // PriorityQueue(Collection<E> c) Creates PriorityQueue with elements in the specified collection. // PriorityQueue(int initialCapacity) Uses specified initial capacity and natural ordering. // PriorityQueue(int i, Comparator<E> c) Uses specified init capacity (i) and uses comparator (c) for order. // PriorityQueue(PriorityQueue<E> c) Creates a PriorityQueue with ele in the specified priority queue. // PriorityQueue(SortedSet<E> c) Creates a PriorityQueue with elements in the specified sorted set. // // Poll/Element/Offer are the same as // Remove/Peek/Add except Remove/Peek throw Exceptions if there is no object. System.out.println("\nPriorityQueue Example"); PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(); priorityQueue.add(2); // Add 0 (at END) -- Autoboxing will auto-convert int to Integer priorityQueue.add(Integer.valueOf(98)); // Add 1 (at END) -- So don't have to do Integer.valueOf()... priorityQueue.add(1); // Add 1 (at END) priorityQueue.addAll(Arrays.asList(56,8,7)); // Add all of a collection. priorityQueue.offer(0); // Add 99 priorityQueue.peek(); // Returns (doesn't remove) head element (or ele at zero index) priorityQueue.element(); for(Integer i: priorityQueue){/* do stuff */} // Iterate Via Enhanced For Loop Iterator priorityQueueIt = priorityQueue.iterator(); // Iterate Via ITERATOR while (priorityQueueIt.hasNext()){priorityQueueIt.next();} // And hasNext() method. Object[] priorityQueueObjArray = priorityQueue.toArray(); // How to convert to an Object Array: System.out.println("priorityQueue.toString(): " + priorityQueue.toString()); System.out.println("priorityQueue.peek(): " + priorityQueue.peek()); System.out.println("priorityQueue.isEmpty(): " + priorityQueue.isEmpty()); System.out.println("priorityQueue.contains(2): " + priorityQueue.contains(2)); System.out.println("priorityQueue.size(): " + priorityQueue.size()); priorityQueue.poll(); // Remove and return the lowest value element. priorityQueue.remove((Object) 51); // Remove object matching 2 (no exception if no match). priorityQueue.clear(); /////////////////// // HASHSET (SET) // /////////////////// // Uses HashMap. // NO Order. System.out.println("\nHashSet Example"); HashSet<Integer> hashSet = new HashSet<>(); hashSet.add(1); // Add 1 hashSet.add(1); // Doesn't do anything; already there. hashSet.addAll(Arrays.asList(56,8,7)); // Add all of a collection. for(Integer i: hashSet){/* do stuff */} // Iterate Via Enhanced For Loop Iterator hashSetIt = hashSet.iterator(); // Iterate Via ITERATOR while (hashSetIt.hasNext()){hashSetIt.next();} // And hasNext() method. Object[] hashSetObjArray = hashSet.toArray(); // How to convert to an Object Array: System.out.println("hashSet.toString(): " + hashSet.toString()); System.out.println("hashSet.isEmpty(): " + hashSet.isEmpty()); System.out.println("hashSet.contains(2): " + hashSet.contains(2)); System.out.println("hashSet.size(): " + hashSet.size()); hashSet.remove((Object) 51); // Remove object matching 2 (no exception if no match). hashSet.clear(); ///////////////////////// // LINKEDHASHSET (SET) // ///////////////////////// // Uses HashMap & LinkedList. // IS ORDERED. System.out.println("\nLinkedHashSet Example"); LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>(); linkedHashSet.add(1); // Add 1 (at tail). linkedHashSet.add(1); // Doesn't do anything; already there. linkedHashSet.addAll(Arrays.asList(56,8,7)); // Add all of a collection. for(Integer i: linkedHashSet){/* do stuff */} // Iterate Via Enhanced For Loop Iterator linkedHashSetIt = linkedHashSet.iterator(); // Iterate Via ITERATOR while (linkedHashSetIt.hasNext()){linkedHashSetIt.next();} // And hasNext() method. Object[] linkedHashSetObjArray = linkedHashSet.toArray(); // How to convert to an Object Array: System.out.println("linkedHashSet.toString(): " + linkedHashSet.toString()); System.out.println("linkedHashSet.isEmpty(): " + linkedHashSet.isEmpty()); System.out.println("linkedHashSet.contains(2): " + linkedHashSet.contains(2)); System.out.println("linkedHashSet.size(): " + linkedHashSet.size()); linkedHashSet.remove((Object) 51); // Remove object matching 2 (no exception if no match). linkedHashSet.remove(999); // Removing nonexistent item is OK. linkedHashSet.clear(); /////////////////// // TREESET (SET) // /////////////////// // IS ORDERED // Implemented as self balancing binary tree (Red Black Tree). // Elements must be homogeneous and comparable. System.out.println("\nTreeSet Example"); TreeSet<Integer> treeSet = new TreeSet<>(); treeSet.add(1); // Add 1. treeSet.add(1); // Doesn't do anything; already there. treeSet.addAll(Arrays.asList(5,6,8,7,9)); // Add all of a collection. treeSet.first(); // Return first element (raises exception if none). treeSet.last(); // Return last element (raises exception if none). treeSet.floor(10); // Returns highest valued element <= than supplied element (10). treeSet.ceiling(10); // Returns lowest valued element >= than than supplied ele (10). treeSet.lower(10); // Returns highest valued element < than than supplied ele (10) or null. treeSet.higher(10); // Returns lowest valued element > than supplied element (10) or null. for(Integer i: treeSet){/* do stuff */} // Iterate Via Enhanced For Loop Iterator treeSetIt = treeSet.iterator(); // Iterate Via ITERATOR while (treeSetIt.hasNext()){treeSetIt.next();} // And hasNext() method. Object[] treeSetObjArray = treeSet.toArray(); // How to convert to an Object Array: System.out.println("treeSet.toString(): " + treeSet.toString()); System.out.println("treeSet.first(): " + treeSet.first()); System.out.println("treeSet.last(): " + treeSet.last()); System.out.println("treeSet.pollFirst(): " + treeSet.pollFirst()); System.out.println("treeSet.pollLast(): " + treeSet.pollLast()); System.out.println("treeSet.lower(10): " + treeSet.lower(10)); System.out.println("treeSet.higher(10): " + treeSet.higher(10)); System.out.println("treeSet.floor(10): " + treeSet.floor(10)); System.out.println("treeSet.ceiling(10): " + treeSet.ceiling(10)); System.out.println("treeSet.isEmpty(): " + treeSet.isEmpty()); System.out.println("treeSet.contains(2): " + treeSet.contains(2)); System.out.println("treeSet.size(): " + treeSet.size()); treeSet.pollFirst(); // Remove and Return first element. treeSet.pollLast(); // Remove and Return last element. treeSet.remove((Object) 51); // Remove object matching 2 (no exception if no match). treeSet.remove(999); treeSet.clear(); /////////////////////////////// // HASHMAP & HASHTABLE (MAP) // /////////////////////////////// // HashMap ISN'T thread safe and allows ONE null key value. // Hashtable IS thread safe, just use synchronized blocks, but DOES NOT allow any null key values. // Another threadsafe possibility is Collections.synchronizedMap: // Example: Map<String, Integer> syncHashMap = Collections.synchronizedMap(new HashMap<>()); System.out.println("\nHashMap/Hashtable Example"); Map<String, Integer> hash = new HashMap<>(); // Adding key-value pairs to a HashMap hash.put("One", 1); hash.put("Two", 2); hash.put("Three", 3); hash.put("Five", 5); hash.put("Six", 6); // Add a new key-value pair only if the key does not exist in the HashMap, or is mapped to `null` hash.putIfAbsent("Four", 8); // put() - How to modify a value. hash.put("Four", 4); // get() System.out.println("hash.get(\"Four\"): " + hash.get("Four")); // isEmpty() System.out.println("hash.isEmpty(): " + hash.isEmpty()); // size() System.out.println("hash.size(): " + hash.size()); // containsKey() System.out.println("hash.containsKey(\"One\"): " + hash.containsKey("One")); // containsValue() System.out.println("hash.containsValue(1): " + hash.containsValue(1)); // remove(Key) - One arg System.out.println("hash.remove(\"Six\"): " + hash.remove("Six")); // remove(Key, Value) - Only removes if the Key is mapped to the Value, returns true or false. System.out.println("hash.remove(\"Five\", 5): " + hash.remove("Five", 5)); // remove(<NonExistantKey>) returns null System.out.println("hash.remove(\"Nine\"): " + hash.remove("Nine")); Set<Map.Entry<String, Integer>> keysAndValueSet = hash.entrySet(); System.out.println("hash.entrySet(): " + keysAndValueSet); // keySet() Set<String> keySet = hash.keySet(); System.out.println("hash.keySet(): " + keySet); // values() Collection<Integer> valueSet = hash.values(); System.out.println("hash.values(): " + valueSet); // Iterating using Java 8 forEach and lambda System.out.print("Iterate with forEach and lambda: "); hash.forEach((key, value) -> { System.out.print(key + "=>" + value + ", "); }); // Iterating with entrySet using iterator() System.out.print("\nIterate with entrySet and iterator(): "); Set<Map.Entry<String, Integer>> hashMapEntries = hash.entrySet(); Iterator<Map.Entry<String, Integer>> hashMapIterator = hashMapEntries.iterator(); while (hashMapIterator.hasNext()) { Map.Entry<String, Integer> entry = hashMapIterator.next(); System.out.print(entry.getKey() + "=>" + entry.getValue() + ", "); } // Iterating with entrySet using Java 8 forEach and lambda System.out.print("\nIterate with entrySety(), forEach, and lambda: "); hash.entrySet().forEach(entry -> { System.out.print(entry.getKey() + "=>" + entry.getValue() + ", "); }); // Iterating with entrySet using simple for-each loop System.out.print("\nIterate with entrySet() and for-each loop: "); for(Map.Entry<String, Integer> entry: hash.entrySet()) { System.out.print(entry.getKey() + "=>" + entry.getValue() + ", "); } // Iterating with keySet System.out.print("\nIterate with keySet(): "); hash.keySet().forEach(key -> { System.out.print(key + "=>" + hash.get(key) + ", "); }); System.out.println(); ///////////////////////// // EXCEPTIONS & ERRORS // ///////////////////////// // The Exceptions and Errors are subclasses of Throwable and can be found in the java.lang package. // // ERRORS // A represent a serious problem that should not be caught, are often related to environment, and are // unrecoverable. All Errors are "unchecked", or are not checked at compile time. // Examples include StackOverflowError, OutOfMemoryError, AssertionError, and VirtualMachineError. // // EXCEPTIONS // Are a "condition that a reasonable application might want to catch", and are often more related to the // application. RuntimeException and all of it's subclasses are "unchecked" exceptions, all other Exceptions // are "checked" exceptions, or are checked at compile time, and must be added to a classes/methods throw clause. // Examples include IOException, ArrayIndexOutOfBoundsException, NullPointerException, and ClassCastException. System.out.println("\nExceptions Example"); try{ int badInt = 10/0; }catch (ArithmeticException ex){ System.out.println("Can't divide by zero"); System.out.println(ex.getMessage()); System.out.println(ex.toString()); // Catch two exceptions in one catch block } catch( NullPointerException | ArrayIndexOutOfBoundsException e) { System.out.println(e.getMessage()); // Generic catch all: }catch (Exception ex){ System.out.println(ex.getMessage()); // Finally always executes (unless thread is killed), even if a return statement is in try body. }finally { System.out.println("Clean up here, Close DBs, Etc..."); } // THROW A CUSTOM EXCEPTION try{ throw new Exception("BAD STUFF"); }catch (ArithmeticException ex){ System.out.println("Can't divide by zero"); System.out.println(ex.getMessage()); System.out.println(ex.toString()); }catch (Exception ex){ System.out.println(ex.getMessage()); }finally { System.out.println("Clean up here, Close DBs, Etc..."); } /////////// // FILES // /////////// System.out.println("\nFile IO Examples"); // How to CREATE and RENAME a file: File f1 = new File("f1.log"); File f1NewName = new File("F1BU.log"); try{ if(f1.createNewFile()){ System.out.println("File created"); f1.renameTo(f1NewName); // NOTE: Delete DOES NOT work if you changed the name of the file: f1.delete(); }else{ System.out.println("File not created"); } }catch (IOException e){ e.printStackTrace(); } // How to WRITE to a File: File f2 = new File("f2.txt"); try{ PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(f2))); pw.println("This is sample text"); pw.close(); }catch (IOException e){ e.printStackTrace(); } // How to READ from a File: f2 = new File("f2.txt"); try{ BufferedReader br = new BufferedReader(new FileReader(f2)); String text = br.readLine(); while(text != null){ System.out.println(text); text = br.readLine(); } br.close(); }catch (IOException e){ e.printStackTrace(); } // How to write BINARY DATA: File f3 = new File("f3.dat"); FileOutputStream fos; try{ fos = new FileOutputStream(f3); BufferedOutputStream bos = new BufferedOutputStream(fos); // NOTE: To write primitives you need DataOutputStream DataOutputStream dos = new DataOutputStream(bos); String name = "Matt"; int age = 37; double bal = 1234.56; dos.writeUTF(name); dos.writeInt(age); dos.writeDouble(bal); dos.close(); } catch (IOException e){ e.printStackTrace(); } // How to READ BINARY files f3 = new File("f3.dat"); FileInputStream fis; try{ fis = new FileInputStream(f3); BufferedInputStream bis = new BufferedInputStream(fis); DataInputStream dis = new DataInputStream(bis); System.out.println(dis.readUTF()); System.out.println(dis.readInt()); System.out.println(dis.readDouble()); fis.close(); } catch (IOException e){ e.printStackTrace(); } // How to get the Absolute and Canonical PATHS of FILES. try { System.out.println("Absolute Path: " + f3.getAbsolutePath()); System.out.println("Canonical Path: " + f3.getCanonicalPath()); System.out.println("Path: " + f3.getPath()); }catch(IOException e){ e.printStackTrace(); } // How to get the PATH of the current working DIR: Path currentRelativePath = Paths.get(""); String s = currentRelativePath.toAbsolutePath().toString(); System.out.println("Current relative path is: " + s); // How to READ files from a DIRECTORY: File d1 = new File(s); System.out.print(s + ": "); if(d1.isDirectory()){ File[] files = d1.listFiles(); for(File f : files) System.out.print(f.getName() + " "); } System.out.println(); // Check if a DELETE worked using java.io.File.delete() if(f1NewName.delete()) { System.out.println("File " + f1NewName.getName() + " deleted successfully"); } else { System.out.println("Failed to delete the file " + f1NewName.getName() + "."); } // How to DELETE if a file exists using java.nio.file.files.deleteifexists(Path p): try { Files.deleteIfExists(Paths.get(f2.getAbsolutePath())); Files.deleteIfExists(Paths.get(f3.getAbsolutePath())); } catch(NoSuchFileException e) { System.out.println("No such file/directory exists"); } catch(DirectoryNotEmptyException e) { System.out.println("Directory is not empty."); } catch(IOException e) { System.out.println("Invalid permissions."); } ///////////// // CLASSES // ///////////// // INTERFACE VS EXTENDS // If the end class "IS" something (but WITHOUT additional functionality) then use EXTENDS // If the end class "CAN" do something (but HAS additional functionality) then use INTERFACE. // Interfaces are more flexible than abstract classes, abstracting the 'what' from the 'how'. // Use interfaces on UNRELATED classes. // COMPOSITION VS INHERITANCE // Composition (HAS A relation) is accomplished by including an INSTANCE of another class as a FIELD of your class // Inheritance (IS A relation) is accomplished by by EXTENDING another class in your class // MISC. CLASS STUFF // super. - used to access/call the parent class members. // super() - Only way to call parent constructor, must be first statement in constructor. // this. - used to call the current class members (fields and methods), can't use in static context. // this() - Only way to call a constructor (used for CONSTRUCTOR CHAINING). Must be first statement. // Constructor can't have call to both super() and this(). // If a class is final or has a private constructor it can't be subclassed. // 4 TYPES OF NESTED CLASS // static nested class // non-static nested class (inner class) // local class (inner class in a scope block/method) -- not used often, in theory, helps with encapsulation. // anonymous nested class (no class name) -- used only once, used a lot with attaching event handlers to // buttons (for example, in android apps). // How to instantiate classes. Rectangle rectangle = new Rectangle(0,0, true, 10, 10); Circle circle = new Circle(0, 0 , true, 1); // How to determine if something is an instance of a specific class: if(rectangle instanceof Rectangle){ System.out.println("(rectangle instanceof Rectangle) :" + (rectangle instanceof Rectangle)); } SerializationReview.examples(); LambdaReview.examples(); StreamReview.examples(); ConcurrentReview.examples(); GCReview.examples(); // How to exit; this terminates the currently running Java Virtual Machine. The argument serves as a status // code; by convention, a nonzero status code indicates abnormal termination. System.exit(0); } // END OF MAIN } class Shape{ // STATIC MEMBER VARIABLE // SHARED by all instances of the class. i.e., scanners or loggers. private static int numberOfShapes = 0; // Instance Variables aka Fields aka Member Variables. private double xLocation; private double yLocation; private boolean visible; // Constructor public Shape(double xLocation, double yLocation, boolean visible){ this.xLocation = xLocation; this.yLocation = yLocation; this.visible = visible; numberOfShapes++; } // INSTANCE METHOD // This method is created when the class is instantiated with the "new" keyword. public void instanceMethod(){ } // STATIC METHODS // CAN'T access instance methods and instance variables directly (NO this.<whatev>..). // Are not made when class is instantiated. public static void staticMethod(){ } // MULTIPLE METHOD ARGS public static void multipleArgsMethod(int ... vals){ for(int x : vals){ // Do something... } } // See child class for Method Overriding. public void methodOverridingExample(){ } // Deprecated! // A method called before object is garbage collected (Not a destructor, but often compared to a destructor). // Only use for logging. public void finalize(){ } } // EXTENDS SHAPE class Rectangle extends Shape{ private double width; private double heigth; // CONSTRUCTOR CHAINING public Rectangle(double x, double y, boolean visible){ this(x, y, visible, 0, 0); } public Rectangle(double xLocation, double yLocation, boolean visible, double width, double heigth){ super(xLocation, yLocation, visible); this.width = width; this.heigth = heigth; } // METHOD OVERLOADING // Must have same name, must have different parameters, CAN have different return types, CAN have different // modifiers, CAN throw different checked or unchecked exceptions. public void methodOverloadExample(){ } private boolean methodOverloadExample(int x){ return true; } // METHOD OVERRIDING // JVM will determine what method will be called at RUNTIME. SHOULD (but don't have to) annotate with @Override. // CAN'T override static methods (only instance methods). // Only inherited methods can be overridden, constructors and private and final methods CAN'T be overridden. // Use: super.methodName() to call the superclass version of an overridden method. // MUST have same name and args, return type CAN be a subclass of the return type in the parent class, // it CAN'T have a lower access modifier (if parent is protected then private child ISN'T allowed, can be public) @Override public void methodOverridingExample(){ } } class Circle extends Shape{ private double radius; public Circle(double x, double y, boolean visible, double radius){ super(x, y, visible); this.radius = radius; } } ////////////////////// // ABSTRACT CLASSES // ////////////////////// abstract class AbstractClassEmpty { } // CAN EXTENDS or IMPLEMENT in an abstract class. abstract class AbstractClass extends AbstractClassEmpty implements InterfaceClassEmpty { // Can have member variables that are inherited (can't in interface unless static). private String name; // Can have a constructor (interfaces can't) public AbstractClass(String name){ this.name = name; } // Can have non-abstract methods (that have bodies) in an abstract class public String getName() { return name; } // Remember that any class that implements (extends) this class must implement ALL of the things defined in this, // Where if they extended a base class, they can choose what they want to implement. // Only methods (and class) are allowed to be abstract. // Methods that are abstract don't have bodies (but you can have non-abstract methods that must have bodies in an abstract class). public abstract void doSomething(); public abstract void doSomethingElse(int someInt); } class Teeest extends AbstractClass{ public Teeest(){ super("blah"); } public void doSomething(){ return; } public void doSomethingElse(int someInt){ return; } } //////////////// // INTERFACES // //////////////// interface InterfaceClassEmpty { } interface IAnotherEmptyClass{ } // An interface can ONLY extend an interface (can't implement an interface, can't extend an abstract class). interface InterfaceClass extends InterfaceClassEmpty, IAnotherEmptyClass{ // Can ONLY have public static variables. public static String staticString = "Only static variables are allowed."; public static final int STATIC_INT = 838; // Pre-Java9, Can ONLY have public methods (no private or protected). public void interfaceMethod(); public boolean interfaceMethodWithArg(int i); // SINCE JAVA 9, Interfaces can have private methods. //private void privateMethod(); // SINCE JAVA 8, Interfaces can contain default methods (with implementation). default void defaultMethod(int defaultArg){ System.out.println("Can actually implement something (have a body of a method in an Interface)."); } } ////////////// // GENERICS // ////////////// // Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. // Added to Java5 // Benefits include code reuse, type safety, elimination of casts, and ability for generic algorithms. interface InterfaceGenericClass<T>{ } abstract class AbstractGenericClass<T>{ } // Can have multiple types: class ClassWithGenerics<T extends Comparable, U>{ T val; public void setVal(T val){ this.val = val; } // Static generic method: // Static keyword must have matching Generic type if generic type used anywhere in method. // Static generic methods can be used in non-generic classes. public static<T extends Object> void staticMethod(T[] arr){ System.out.println("I'm staticMethod in ClassWithGenerics..."); } public T getVal(){ return val; } public void usingRawAndGenerics() { // List using raw types:. ArrayList rawTypesList = new ArrayList(); rawTypesList.add(1); rawTypesList.add("hi"); rawTypesList.add(1.2); // List using generics: ArrayList<Integer> intList = new ArrayList<>(); intList.add(144); } // Must typecast when referencing; prone to run time errors. public static void printArrayList(ArrayList<?> aL){ for(Object x : aL) System.out.println(x); } } //////////////// // COMPARATOR // //////////////// // Comparator interface is used to order the objects of user-defined classes. // A comparator object is capable of comparing two objects of two different classes. // Usage Example: // String[] stringArray = new String[]{"they", "fun", "race", "fights", "care", "listens", "silent", "acre"}; // Arrays.sort(stringArray, new AnagramComparator()); // This example would sort each string in a string array so that anagrams would be ordered next to each other. class AnagramComparator implements Comparator<String>{ public String sortChars(String s){ char[] content = s.toCharArray(); Arrays.sort(content); return new String(content); } // Must implement compare when implementing Comparator. public int compare(String s1, String s2){ return sortChars(s1).compareTo(sortChars(s2)); } // How to implement a Comparator as an Anonymous Class (Say if you wanted to do this in main()): public void howToImplementComparatorViaAnonymousClass(){ String[] stringArray = new String[]{"they", "fun", "race", "fights", "care", "listens", "silent", "acre"}; Arrays.sort(stringArray, new Comparator<String>() { @Override public int compare(String s1, String s2) { char[] content1 = s1.toCharArray(); Arrays.sort(content1); char[] content2 = s2.toCharArray(); Arrays.sort(content2); return (new String(content1)).compareTo(new String(content2)); } }); } } /////////////////////////////////////////////////// // SERIALIZATION (SERIALIZABLE & EXTERNALIZABLE) // /////////////////////////////////////////////////// // Serialization, in Java, is the process which is used to serialize object in java by storing object’s state into a // file and recreating object's state from that file (the reverse process is called deserialization). The file (byte // stream) created is platform independent, therefore, an object serialized on one platform can be deserialized on a // different platform. This is useful for network communication and to save objects states. // // NOTE: Any object being serialized (from an serialized object) MUST ALSO be serialized or a // java.io.NotSerializableException will be thrown. // // The Java Serialization API provides the Serializable interface and the Externalizable interface as object // serialization mechanisms. // // SERIALIZABLE INTERFACE // Serializable is a MARKER INTERFACE, or, an interface that has no methods or constants inside it, and is intended to // provide information to the compiler and JVM. Therefore, to make a class Serializable, add "implements // java.io.Serializable", then the JVM will provide default serialization. The default serialization is serialization // of all non-static and non-transient data members. Variables defined with transient keyword are initialized with the // default value (NOT current value) during deserialization. Variables defined with static keyword are loaded with the // current value of the variable during deserialization. // // EXTERNALIZABLE INTERFACE // The Externalizable interface, which extends Serializable, allows for flexibility and control of object serialization // via writeExternal() and readExternal() methods. When overriding these two methods, the user can specify/customize // the items that are read and written, thus, allowing for better control and backwards compatibility. Contrary to the // Serializable interface, the Externalizable interface CAN write/read transient and static variables. // // NOTE: The same items and order must be used during writing (writeExternal()) and reading (readExternal()). // NOTE: There must be a public default no-arg constructor to use readObject() on an object that implemented // Externalizable, or a java.io.InvalidClassException will be thrown. // // SERIALVERSIONUID // The Serialization runtime associates a version number with each Serializable class called, this number is the // serialVersionUID. This is used during Deserialization to verify that the sender and receiver of a serialized object // have loaded compatible classes (w.r.t. serialization). If the serialVersionUID differ during Deserialization, then a // InvalidClassException will be thrown. If no serialVersionUID is defined, Java will automatically create one based on // the class'es attributes (note that small changes in the class can cause a different ID). It is considered good // practice to define your own serialVersionUID; to do this, define "static final long serialVersionUID" and assign it // to a type of long value. // // SERIALVER // serialver is a tool that comes with JDK. It is used to get serialVersionUID number for Java classes. The tool is used // via the following command: // serialver [-classpath classpath] [-show] [classname…] class SerializationReview{ public static void examples(){ SerializableClass serializableClass = new SerializableClass(); SerializableClass readSerializableClass = null; serializableClass.transientInt = 8008; serializableClass.staticInt = 6; serializableClass.string = "Hello World!"; serializableClass.i = 42; ExternalizableClass externalizableClass = new ExternalizableClass(); ExternalizableClass readExternalizableClass = null; externalizableClass.transientInt = 80085; externalizableClass.staticInt = 69; externalizableClass.string = "Hello World!!!"; externalizableClass.i = 420; System.out.println(serializableClass.toString()); System.out.println(externalizableClass.toString()); try { // Serialize serializableClass: ObjectOutputStream so = new ObjectOutputStream(new FileOutputStream("serializableClass.txt")); so.writeObject(serializableClass); so.flush(); so.close(); // Serialize externalizableClass: so = new ObjectOutputStream(new FileOutputStream("externalizableClass.txt")); so.writeObject(externalizableClass); so.flush(); so.close(); serializableClass.transientInt = 800; serializableClass.staticInt = -6; serializableClass.string = "Hello!"; serializableClass.i = 4; externalizableClass.transientInt = 800850; externalizableClass.staticInt = 690; externalizableClass.string = "Hello World!!!!!!!!!!!"; externalizableClass.i = 4200; // Deserialize serializableClass: ObjectInputStream si = new ObjectInputStream(new FileInputStream("serializableClass.txt")); readSerializableClass = (SerializableClass)si.readObject(); si.close(); // Deserialize externalizableClass: si = new ObjectInputStream(new FileInputStream("externalizableClass.txt")); readExternalizableClass = (ExternalizableClass)si.readObject(); si.close(); // Delete files: File f = new File("serializableClass.txt"); f.delete(); f = new File("externalizableClass.txt"); f.delete(); } catch (Exception e) { System.out.println(e); |