Advertisement
wingman007

Java2018IntroCheatSheet

Oct 21st, 2018 (edited)
1,047
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 20.30 KB | None | 0 0
  1. // Да програмираш значи да описваш алгоритъм с формален език за програмиране. Алгоритми + данни = програми.
  2. // HelloWorld.java
  3. // javac HelloWorld.java
  4. // java HelloWorld
  5. // javac -d . HelloWorldPackage.java
  6. // java com.coolcsn.HelloWorldPackage
  7. // "C:\Program Files (x86)\Java\jdk1.8.0_192\bin\javac" HelloWorld.java
  8. // "C:\Program Files (x86)\Java\jdk1.8.0_192\bin\java" HelloWorld
  9. // sout + tab - prints System.out.println; Alt + Enter; Enter brak point, Start Debug, look down on the left step into
  10. // Ctrl + / - comment out, uncomment
  11. // ⌥ ⌘ / macOS or Ctrl + Shift + / - Block comments. Comment Uncomment
  12. // Refactor This using ⌃T (MacOS) or Shift+Ctrl+Alt+T (Windows)
  13. // Shift + F6 rename
  14. // Shift + F9 - Debug
  15. // Shoft + F10 - Rub
  16. // You can use ⌘N (macOS), or Alt+Insert (Windows/Linux) for the Generate menu and then select Constructor, Getter, Setter or Getter and Setter
  17.  
  18. package com.coolcsn;
  19. import java.util.*;
  20.  
  21. public class HelloWorld {
  22.  
  23.  
  24.     public static final String ANSI_RED_BACKGROUND = "\u001B[41m";
  25.     public static final String ANSI_RESET = "\u001B[0m";
  26.     public static final String ANSI_RED = "\u001B[31m";
  27.     public static final String ANSI_GREEN_BACKGROUND = "\u001B[42m";
  28.  
  29.  
  30.     public static void main(String[] args) throws java.io.IOException
  31.     {
  32.          // 1. Hello World
  33.          System.out.println("Hello World!");
  34.  
  35.         // 2. Primitive types. Strictly typed, static language
  36.         // 2.1. Integer. Default 0
  37.         byte myByte = -128; // 8 bits signed -128 to 127
  38.         short myShort = 23456; // 16 bits signed -2^15 to 2^15 -1
  39.         int myInt = 432423423; // 32 bits signed -2^31 to 2^31 -1
  40.         long myLong = 4321432423L; // 64 bits signed -2^63 to 2^63 -1
  41.         long maxLong = Long.MAX_VALUE;
  42.         System.out.println(maxLong);
  43.  
  44.  
  45.         // Literal
  46.         myShort = 034; // octal radix
  47.         System.out.println(myShort);
  48.  
  49.         // Hex Literal
  50.         myInt = 0xffab;
  51.         System.out.println(myInt);
  52.  
  53.  
  54.         // 2.2. Real
  55.         float myFloat = 2.3454324234324F; // 32 bits signed  7 symbols
  56.         double myDouble = 2.3454324234324D; // 64 bits signed 14 symbols
  57.  
  58.         System.out.println(myFloat);
  59.         System.out.println(myDouble);
  60.  
  61.         // 1.3 * 10^3
  62.         myDouble = 1.2e-1;
  63.         System.out.println(myDouble);
  64.  
  65.         // 2.3. Char
  66.         char myChar = 'S';
  67.  
  68.  
  69.         System.out.println((int)myChar);
  70.         System.out.println((char)84);
  71.  
  72.         myChar = '\u0041'; // A
  73.         myChar = '\u004E';
  74.         myChar = '\'';
  75.         System.out.println(myChar);
  76.  
  77.         System.out.println("\'Stoyancho\\Sharo\' \t 45 & | ");
  78.  
  79.         // 2.4.  String
  80.         String myString = "Stoyan"; // null
  81.  
  82.         // 2.5. Bool
  83.         boolean myBool = true; //
  84.  
  85.         // 2.6. Object
  86.         Object myObject = 5;
  87.  
  88.         Object obj = 5;
  89.         // obj = "Stoyancho";
  90.         System.out.println(obj);
  91.  
  92.         // Object n = 4;
  93.  
  94.         // System.out.println(obj + n);
  95.  
  96.         System.out.println("Hello World IDE");
  97.         System.out.println( 2 + 2);
  98.  
  99.         // 3. Operators
  100.         // 3.1 Arithmetics
  101.         int n = 25;
  102.         int m = 32;
  103.  
  104.         System.out.println(m + n); //57
  105.         System.out.println(m - n); // 7
  106.         System.out.println(m * n); // 800
  107.         System.out.println(m / n); // 1
  108.         System.out.println((double)m / n); // 1.28
  109.         System.out.println(m % n); // 7
  110.         // System.out.println(m++ + n); // 57
  111.         System.out.println(++m + n); // 58
  112.         // System.out.println(m-- + n); // 58
  113.         System.out.println(--m + n); // 57
  114.  
  115.  
  116.         // 3.2. Comparison
  117.         System.out.println(m > n); // true
  118.         System.out.println(m < n); // false
  119.         System.out.println(m <= n); // false
  120.         System.out.println(m >= n); // true
  121.         System.out.println(m != n); // true
  122.         System.out.println(m == n); // false
  123.  
  124.         // 3.3. Logical
  125.         boolean x = true;
  126.         boolean y = false;
  127.         System.out.println(x && y); // false
  128.         // | x     | y     | &&    | ||   | !X     |  X^Y  |
  129.         // | true  | true  | true  | true |  false | false |
  130.         // | true  | false | false | true |  false | true  |
  131.         // | false | true  | false | true |  true  | true  |
  132.         // | false | false | false | flase|  true  | flase |
  133.         System.out.println(x || y); // true
  134.         System.out.println(!x); // fasle
  135.         System.out.println(x ^ y); // true
  136.  
  137.         byte m1 = 3; //
  138.         byte n1 = 2;
  139.         System.out.println(m1 & n1); // 2
  140.         System.out.println(m1 | n1); // 3
  141.         System.out.println(~n1); // -1
  142.         System.out.println(n1 << 1); // 4
  143.         System.out.println(n1 >> 1); // 1
  144.         System.out.println(n1 >>> 1); // 1
  145.  
  146.         // 3.4. Asignment
  147.         m1 = 4;
  148.         m1 += 3; // m1 = m1 + 3;
  149.  
  150.         int t = 4;
  151.         t += 5; // t = t + 5;
  152.         t *= 2; // t = t * 2;
  153.         // =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, >>>=
  154.  
  155.         System.out.println(myString + myByte);
  156.  
  157.         System.out.println("Bojidare " + "Dineva " + 1);
  158.  
  159.         System.out.println((n1 > m1)? "Stoyan" : "Bojidara" );
  160.  
  161.         // Oreder of operations change with ()
  162.         System.out.println(((n1 + m1) * (n1 - m1++)) + --m1 / ( 5 + 2));
  163.  
  164.         System.out.println(obj.toString());
  165.  
  166.         // 4. Console
  167.         // %[argument_index$][flags][width][.precision]conversion
  168.         // argument_index - целочислен тип показващ позицията на аргумента от "аргументния списък".
  169.         // Първият аргумент се индикира с "1$", втория с "2$" и т.н.
  170.         // flags - поредица от символи които модифицират изходния формат.
  171.         // (Примерни ефекти са, показването на числото да бъде винаги със знак, слагането
  172.         // на скоби на отрицателните числа и т.н.) - Резултатът ще бъде ляво ориентиран;
  173.         // + Резултатът винаги ще включва знак (+, -); 0 Резултатът ще се отмести с нули;
  174.         // ( Резултатът ще затвори в скоби отрицателните числа
  175.         // width - неотрицателен целочислен тип показващ минималния брой символи, които трябва да се отпечатат.
  176.         // precision - неотрицателен целочислен тип ограничаващ броя на показваните символи.
  177.         // Този атрибут си променя поведението според conversion спецификатора. В случай на float определя броя цифри след запетаята.
  178.         // b, o, x, c, s, S, f, e, h, n
  179.         System.out.print("Enter your name: ");
  180.         System.out.print("Stoyan \n");
  181.  
  182.         String str = "Teodora";
  183.         String str1 = "Jivko";
  184.         System.out.printf("My name is %2$S and my name is %1$s . And I am a student! \n", str, str1);
  185.  
  186.         System.out.printf("%s \n", myInt);
  187.         System.out.printf("%12d \n", myInt);
  188.         System.out.printf("%12x \n", myInt);
  189.         System.out.printf("%12o \n", myInt);
  190.         System.out.printf("%+12.4f \n", -myFloat);
  191.  
  192.         // java.util.Date date = new java.util.Date();
  193.         Date date = new Date();
  194.         System.out.printf("%tY \n", date);
  195.         System.out.printf("%tm \n", date);
  196.         System.out.printf("%tB \n", date);
  197.         System.out.printf("%tA \n", date);
  198.         // System.out.printf("$tY, $tM \n", date);
  199.  
  200.         // Date myDate = new Date(2014, 02, 11); // deprecated
  201.         Date myDate1 = new GregorianCalendar(2014, Calendar.FEBRUARY, 11).getTime();
  202.  
  203.         java.util.Locale.setDefault(new java.util.Locale("bg", "BG"));
  204.         System.out.printf("%tA \n", date);
  205.         System.out.printf("Денят, в който бяхме съсипани: %1$tA %1$tH:%1$tM %1$tB-%1$tY.\n", new java.util.Date());
  206.  
  207.         // 4.2. System.in
  208.  
  209.         // Only one character
  210.         // System.out.print("Please enter your name: ");
  211.         // int ch = System.in.read();
  212.         // System.out.println("The first letter of your name has ASCII code: " + ch); // 83 System.out.println((char)ch);
  213.  
  214.         /* Uncomment to see System.in
  215.         // Old way of reading
  216.         int ch;
  217.         System.out.print("Please enter your name: ");
  218.         while ((ch = System.in.read()) != '\n') {
  219.              System.out.print((char) ch);
  220.         }
  221.  
  222.  
  223.         // !!!!!!!!!!! Use this Scanner !!!!!!!!!!!!!!!!!!!!
  224.         Scanner input = new java.util.Scanner(System.in);
  225.         // String
  226.         System.out.print("Please enter your name: ");
  227.         String firstName = input.nextLine();
  228.         // int
  229.         System.out.print("Please enter your Age: ");
  230.         int age = input.nextInt();
  231.         // Double
  232.         System.out.print("Please enter your Balance: ");
  233.         double balance = input.nextDouble();
  234.  
  235.         input.close();
  236.  
  237.         // Non formatted output
  238.         System.out.print("Your favorite number is " + (age * balance) + "\n");
  239.  
  240.         //
  241.         System.out.printf("Your favorite number is %f", (age * balance));
  242.  
  243.         System.out.println(ANSI_GREEN_BACKGROUND + ANSI_RED + "This text has a green background and red text!" + ANSI_RESET ); // + "\u001B[41m"
  244.         */
  245.  
  246.         // 5. Conditional logic. Условни конструкции
  247.         // 5.1.
  248.         if (n < m) {
  249.             System.out.print("n < m");
  250.         }
  251.  
  252.         // 5.2.
  253.         if (n > m ){
  254.             System.out.println("n > m");
  255.         }
  256.         else {
  257.             System.out.println("n < m");
  258.         }
  259.  
  260.  
  261.         // 5.3.
  262.         int testscore = 7;
  263.         char grade;
  264.  
  265.         if (testscore >= 90) {
  266.             grade = 'A';
  267.         } else if (testscore >= 80) {
  268.             grade = 'B';
  269.         } else if (testscore >= 70) {
  270.             grade = 'C';
  271.         } else if (testscore >= 60) {
  272.             grade = 'D';
  273.         } else {
  274.             grade = 'F';
  275.         }
  276.  
  277.         // switch
  278.         switch (m) {
  279.             case 3:
  280.             case 4 :
  281.                 System.out.println("m = 4 || m = 3");
  282.                 break;
  283.             case 5 :
  284.                 System.out.println("m = 5");
  285.                 break;
  286.             default:
  287.                 System.out.println("Deafult I couldn't guess!");
  288.                 break;
  289.         }
  290.  
  291.         // 6. Loops Цикли
  292.         // 6.1. While
  293.         int i = 0;
  294.         while (i < n){
  295.             System.out.println(i);
  296.             i++;
  297.         }
  298.  
  299.         // 6.2.
  300.         Scanner input = new java.util.Scanner(System.in);
  301.         int age = 0;
  302.         do {
  303.             System.out.print("Please, enter your age (0 to 120): ");
  304.             age = input.nextInt();
  305.         } while( age < 0 || age >= 120);
  306.  
  307.         // 5.3. for
  308.         for ( i = 0; i < 10; i++) {
  309.             System.out.print(i);
  310.         }
  311.  
  312.         // continue
  313.         System.out.println("------- odd ---------");
  314.         for ( i = 0; i < 10; i++) {
  315.             if (i % 2 == 0) continue;
  316.             System.out.println(i);
  317.         }
  318.  
  319.  
  320.         // break
  321.         int prime = 46;
  322.  
  323.         for ( i = 2; i < prime; i++) {
  324.             if (prime % i == 0 ) {
  325.                 System.out.println("The number is NOT prime");
  326.                 break;
  327.             }
  328.             // System.out.println(i);
  329.         }
  330.  
  331.         System.out.println();
  332.         // 5.4. Foreach. Douglas Addams
  333.         int[] myArray = {23, 42, 324, 65, 76};
  334.         for (int j : myArray) {
  335.             System.out.println(j);
  336.         }
  337.  
  338.         // 7. Arrays. Нареда/индексирана последователност от еднотипни елементи
  339.         // 7.1. Single dimension
  340.         int[] myIntArray = new int[5];
  341.         myIntArray[0] = 0;
  342.         myIntArray[3] = 3;
  343.  
  344.         for (i = 0; i < myIntArray.length; i++){
  345.             System.out.printf("myIntArray[%1$d] = %2$d \n", i, myIntArray[i]);
  346.         }
  347.  
  348.         String[] students = {"Iliya", "Jivko", "Nasko", "Teodora"};
  349.  
  350.         // 7.2. Multi dimension
  351.         int[][] twoDimentionalArray;
  352.         int[][][] threeDimentionalArray;
  353.  
  354.         int[][] matrix = {
  355.                 {1, 2, 3, 4}, // row 0 values
  356.                 {5, 6, 7, 8}, // row 1 values
  357.         };
  358.         // The matrix size is 2 x 4 (2 rows, 4 cols)
  359.  
  360.         for (int row = 0; row < matrix.length; row++) {
  361.             for (int col = 0; col < matrix[0].length; col++) {
  362.                 System.out.printf("matrix[%1$d][%2$d] = %3$d \n", row, col, matrix[row][col]);
  363.             }
  364.             System.out.println();
  365.         }
  366.  
  367.         int[][] matrixDefined = new int[2][3];
  368.  
  369.         String[] myStringArray = new String[5];
  370.         for (i = 0; i < myStringArray.length; i++){
  371.             System.out.println(myStringArray[i]);
  372.         }
  373.  
  374.         boolean[] myBoolArray = new boolean[5];
  375.         for (i = 0; i < myBoolArray.length; i++){
  376.             System.out.println(myBoolArray[i]);
  377.         }
  378.  
  379.         // 8. Numbering Systems
  380.         // IV VI X XI XII
  381.         // 10 01
  382.         // base radix основа
  383.         // 0-9 основате се определя от броя на цифрите
  384.         // 234
  385.         // 2*10^2 + 3*10^1 + 4*10^0 = 2*100 + 3*10 + 4*1 = 200 + 30 + 4 = 234
  386.  
  387.         // from binary to decimal
  388.         // 10101010
  389.         // 1*2^7 + 0*2^6 + 1*2^5 + 0*2^4 + 1*2^3 + 0*2^2 + 1*2^1 + 0*2^0 = 128 + 32 + 8 + 2 = 170
  390.  
  391.         // from decimal to binary
  392.         // 170 / 2 = 85  0
  393.         // 85 / 2 = 42  1
  394.         // 42 / 2 = 21 0
  395.         // 21 / 2 = 10 1
  396.         // 10 / 2 = 5 0
  397.         // 5 / 2 = 2  1
  398.         // 2 / 2 = 1 0
  399.         //           1
  400.         // 10101010
  401.  
  402.         // 9. Methods
  403.         greet(); // greet("Stoyan");
  404.         int[] ages = new int[3];
  405.         // inputArray(ages);
  406.         /*
  407.         Scanner input1 = new java.util.Scanner(System.in);
  408.         for (i = 0; i < ages.length; i++) {
  409.             System.out.printf("Please enter the value of element : %d", i);
  410.             ages[i] = input.nextInt();
  411.         }
  412.         */
  413.  
  414.  
  415.         int[] fNumbers = new int[4];
  416.         // inputArray(fNumbers);
  417.         /*
  418.         Scanner fNUmbers = new java.util.Scanner(System.in);
  419.         for (i = 0; i < fNumbers.length; i++) {
  420.             System.out.printf("Please enter the value of element : %d", i);
  421.             fNumbers[i] = input.nextInt();
  422.         }
  423.         */
  424.         /*
  425.         for (i = 0; i < 10; i++) {
  426.         System.out.println(i);
  427.         }
  428.  
  429.         for (i = 20; i <=30; i++) {
  430.             System.out.println(i);
  431.         }
  432.         */
  433.  
  434.         printInterval(0, 10);
  435.         printInterval(20, 30);
  436.  
  437.         System.out.println(calculateInterest(35.0));
  438.  
  439.  
  440.         printMenu();
  441.  
  442.         // 9.1. Java doesn't have default values for the formal parameters. Use overloading instead
  443.         // Java does not support default arguments in the same way that languages like C++ or Python do. However, you can achieve similar behavior in Java using method overloading.
  444.  
  445.         // 9.2. Variable number of parameters
  446.         welcomePerson("Stoyan", "Ivan", "Petko");
  447.  
  448.  
  449.         // 10. Recursion
  450.         // 0! = 1;
  451.         // n! = (n-1)!*n
  452.  
  453.         // 3! = 1*2*3 = 6
  454.  
  455.  
  456.         int mul = 1;
  457.         for (i = 1; i <= 4; i++) {
  458.             mul *= i;
  459.         }
  460.         System.out.println("Factorial = " + mul);
  461.  
  462.         System.out.println(calculateFactorIterations(4));
  463.  
  464.         System.out.println(calculateFactorialRecursion(4));
  465.  
  466.  
  467.         // 11. Data Structures
  468.         //slow on add and remove fast on access indexes/elements
  469.         java.util.ArrayList<Integer> myArrayList = new java.util.ArrayList<Integer>();
  470.         myArrayList.add(10);
  471.         myArrayList.get(0);
  472.         System.out.println(myArrayList.get(0));
  473.  
  474.         // fast on add and remove slow on access indexes
  475.         java.util.LinkedList<Integer> myLinkedList = new java.util.LinkedList<Integer>();
  476.         myLinkedList.add(5);
  477.         myLinkedList.get(0);
  478.  
  479.  
  480.         String text = "Stoyan";
  481.         Map<String, Integer> words = new TreeMap<String, Integer>();
  482.         Scanner textScanner = new Scanner(text);
  483.         while (textScanner.hasNext()) {
  484.             String word = textScanner.next();
  485.             Integer count = words.get(word);
  486.             if (count == null) {
  487.                 count = 0;
  488.             }
  489.             words.put(word, count + 1);
  490.         }
  491.  
  492.         for (Map.Entry<String, Integer> wordEntry
  493.                 : words.entrySet()) {
  494.             System.out.printf(
  495.                     "word '%s' is seen %d times in the text%n",
  496.                     wordEntry.getKey(), wordEntry.getValue());
  497.         }
  498.     }
  499.  
  500.     // Recursion
  501.     public static int calculateFactorialRecursion(int number) {
  502.         if (number == 0) return 1;
  503.         return calculateFactorialRecursion(number -1) * number;
  504.     }
  505.  
  506.     public static int calculateFactorIterations(int number) {
  507.         int mul = 1;
  508.         for (int i = 1; i <= number; i++) {
  509.             mul *= i;
  510.         }
  511.         return mul;
  512.     }
  513.  
  514.     static void greet(String name){ // static void greet()
  515.         System.out.println("Hello " + name);
  516.     }
  517.  
  518.     public static void inputArray(int[] myArray) {
  519.         Scanner input = new java.util.Scanner(System.in);
  520.         for (int i = 0; i < myArray.length; i++) {
  521.             System.out.printf("Please enter the value of element : %d : ", i);
  522.             myArray[i] = input.nextInt();
  523.         }
  524.     }
  525.  
  526.     public static void printInterval(int from, int to){
  527.         for (int i = from; i <=to; i++) {
  528.             System.out.println(i);
  529.         }
  530.     }
  531.  
  532.     public static double calculateInterest(double amount) {
  533.         double interest = (1/4.0) * amount;
  534.         return  interest;
  535.     }
  536.  
  537.     public static double calculateCompoundInterest(double amount, double interest, int period) {
  538.         double totalAmount = amount * Math.pow((1 + interest/100), period);
  539.         return  totalAmount;
  540.     }
  541.  
  542.     public static void printMenu()
  543.     {
  544.         System.out.println("File");
  545.         System.out.println("Edit");
  546.     }
  547.  
  548.     public static boolean isPrime(int prime) {
  549.         for (int i = 2; i < prime; i++) {
  550.             if (prime % i == 0 ) {
  551.                 return false; // System.out.println("The number is NOT prime");
  552.                 // break;
  553.             }
  554.         }
  555.         return true;
  556.     }
  557.  
  558.     public static int inputNumber(int min, int max) { // String question, String question,
  559.         int age = 0;
  560.         Scanner input = new java.util.Scanner(System.in);
  561.         do {
  562.             // System.out.print("Please, enter a number between (5 to 25): ");
  563.             System.out.printf("Please, enter a number between (%1$s to %2$s): ", min, max );
  564.             age = input.nextInt();
  565.         } while( age < min || age >= max);
  566.         return age;
  567.     }
  568.  
  569.     public static void  welcomePerson(String ... people) {
  570.         for (String person : people) {
  571.             System.out.println("Welcome " + person);
  572.         }
  573.     }
  574. }
  575.  
  576. // OOP
  577. // 1. История 1967 Алан Кай
  578. // 2. Класове и обекти
  579. // 3. Елементи на класа
  580. // 4. Статични елементи на класа
  581. // 5. Inheritance - Вьзможността да се преизползват дефинираните елементите на друг клас
  582. // 6. Abstraction - Вьзможността обект от даден клас да се третира като обект от родителски клас или интерфейс
  583. // 7. Encapsulation - Вьзможността да се скриват/енкапсулират вътрешните елементи на обектите от даден клас и да се излагат само важните за потребиеля. Обикновено това са методите от интерфейсите
  584. // 8. Polymorphism - Вьзможността обектите да запазват специфичната си функционалност (методи) и да се проявяват полиморфно, въпреки прилагането на абстракция.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement