Showing posts with label personal notes. Show all posts
Showing posts with label personal notes. Show all posts

Sunday, May 16, 2021

JAVA Notes

 My JAVA Notes

JRE :

Java Runtime Environment.

JVM :

Java Virtual Machine, is part of JRE.

JDK :

Java Development Kit, is responsible for executing codes. it includes JRE + JVM. JDK Version is Java version on a machine.

JAVA SE :

Java Standard Edition, is the minimum requirements for JAVA to work 'run an application' on a machine.

WORA :

Write Once, Run Anywhere, is to describe Java Applications.

Byte Code :

Java Code gets converted to bytecode which was interpreted by JVM. Compiled Bytecode is understood by all machines, that is why they call it WORA.

Java Program → Javac 'Compile' → Bytecode → Any machine.

Case sensitive :

👍 System.out.println();

👎  system.out.printLn();

JAVA Code example :

My Environment : I've installed JDK16-.0.1 in C:\Program Files. I have registered Environment Variables 'System Variables' to add "bin\".

The Code :

My Code will print the sentence Hello Java!, I'm using Command Line from start to end.

public class Welcome {

public static void main(String[] args) {

System.out.println("Hello Java!");

}

}

Command Line Prompt :

  1. Open command line from Start menu 'With or without Admin previliges'
  2. Create Directory in C:\ → C:\cd JavaCode 'Enter'
  3. Create Text File in JavaCode called Welcome.java → C:\JavaCode>md Welcome.java
  4. Type my Code into Welcome.java file → C:\JavaCode>echo public class Welcome { public static void main(String[] args) { System.out.println("Hello Java!"); } }> Welcome.java 'Enter'
  5. Compile Welcome.java file using javac → C:\JavaCode>javac Welcome.java 'Enter', notice a file called 'Welcome.class' is created in the same directory 'JavaCode', this file is bytecode file.
  6. Execute Welcome.java file → C:\JavaCode>java Welcome 'Enter'
  7. the resule 'Hello Java!' appears right after the previous command in Command Line Prompt.

Video :


Variables : 

  • Use lower Camel Case, because it is more easier to read. I.e.:
String driverFirstName;
  • Are case sensitive like all Java instructions.
String driverFirstName; is different from String driverfirstname;
  • Must start with an alphabet letter [a to z] except Dollar Sign [$] and Underscore Sign [_] but not recommended.
String 2ndCase; is not accepted.
  • No spaces allow.
String driver FirstName; is not accepted.

Variable Types : 

Numbers

    1. Integers : 10 digits max long. int ThisNum = 1234567890;  but doesn't allow fractions although it accepts negative values.
    2. Long : Bigger integer. long BigInt = 1234567890 * 10000000;
    3. Double : Allow fractions, negative and pretty much anything. double ThisAny = -654.221;
The more your variable type length is, the slower your program will be 'benefits come with a price'. Don't use Double when you can use Integers.

Text

    1. String. String MyName="Jave"; Allows many characters 'phrases' with 2 double quotations surrounding.
    2. Character. Char OpnLine='A'; Allows only one character with 2 single quotations surrounding.

        Decision

    1. Boolean. boolean Agreed=true; and boolean NotAgreed=false;
Note : In Math Multiplication and Division comes 1st, then Addition and Subtraction.

The following code shows the difference between using Integers and Doubles, and how you need to Convert a Type to get a correct more accurate result.

public class SomeMath {
public static void main(String[] args) {
String Phrase1="Output Decimal";
String Phrase2="Output Integer";
String Equation="33 Div 10";
double FirstNum=33;
int SecondNum=10;
double DblRslt=FirstNum/SecondNum;
int IntRslt=(int)FirstNum/SecondNum;
System.out.println(Phrase1 + " from equation like " + Equation + " , we use Double. The result is : " + DblRslt);
System.out.println(Phrase2 + " from equation like " + Equation + " , we use Integer. The result is : " + IntRslt);
}
}
The Output is :
Output Decimal from equation like 33 Div 10 , we use Double. The result is : 3.3
Output Integer from equation like 33 Div 10 , we use Integer. The result is : 3

 Note : Truncation is when you divide two integers ( 5 / 2 ) it will be by default 2 not 2.5. Also when multiplying a double and integer, the result is Double (2.5 * 5) will equal 5.0 as double not 5 as integer.

Making Decisions, Options 'if-else statement':

    Example :
Museum ticket equals to 15$, except for :

  1. Students.
  2. People over 60 years old.
  3. Kids less than or equal to 15 years old.
The tickets is only 5$. To write a program to help making a decision about the ticket price, I wrote this code:

public class Decisions2 {
public static void main(String[] args) {
boolean isStudent=true;
int ticketPrice=10;
int age=15;
if(isStudent){
System.out.println("Ticket Price = 5");
}
else if (age<=15) {
System.out.println("Ticket Price = 5");
}
else if (age>60) {
System.out.println("Ticket Price = 5");
}
}
}
Output → Ticket Price = 5

→ How to reduce the repetitive code above ?

Using Logical Operator 

  • || means OR  (3<5 || 5>3), it checks if the right or left side are either true. So, if we said (3<5 || 3>5), the the statement is true because one of the sides is true.
  • && means AND (3<5 && 5>3), it checks if the right and left side are both true. So, if we said (3<5 && 3>5), then the statement is false because one of the sides is false.
  • !  means NOT (!(3<5)), it gives the opposite value, in this case it means Not True which means false.
Our example 'Museum Ticket', the code would be:
public class Decisions2 {
public static void main(String[] args) {
boolean isStudent=true;
int ticketPrice=10;
int age=15;
    if(age<=15 ||age>60 || isStudent){
    System.out.println("Ticket Price = 5");
        }
}
}
Output → Ticket Price = 5

Operators Order :

Just like how math operators (*, /, +, -) have an order, JAVA Operators have their own order, like so :
  1. Parentheses ()
  2. NOT !
  3. AND &&
  4. OR ||
For the expression: 
    !true || false && true 
This will have the NOT ! operator evaluated first, so this simplifies to: 
    false || false && true 
Then the AND && operator will be evaluated. 
The combination false && true equals false, and the whole expression becomes: 
false || false 
Finally the OR || operator will be evaluated, and the whole expression evaluates to false.

Bottom line [True || False] is True while [True && False] is False.

Another way to make a decision in JAVA, is SWITCH STATEMENT.

Switch Statement
If we want to write a code to program a coffee machine to give us either Espresso or Latte  or Coffee, we assign a passcode to each one of them, like so :
Coffee 255, Espresso 616, Latte 314

public class Switch1 {
public static void main(String[] args) {
int passCode=255;
String Coffee;
switch (passCode) {
case 314: Coffee = "Latte";
break;
case 616: Coffee="Espresso";
break;
case 255: Coffee="Coffee";
break;
default: Coffee="Unknown";
break;
}
System.out.println("Coffee type is " + Coffee);
}
}

Output → Coffee type is Coffee

 Default Case, always in the end of Switch, and it gives a value whenever all cases are not met.

Java Functions

Functions in Java like (println()) which is responsible for Print Text on Screen, functions in Java tend to organize and group code. Java executes a Function when a function is called.

Functions in Java are written like this :

Access modifiers + Function type + Function name + ( + parameters if needed + )

for example :

public int SumThis(int X, int Y) {

code

return integer value;

}

Notes :

Parameters exist when needed in defining the function, but arguments exist when calling it.

for more about Functions in Java , here is a link to the official Java SE 8 Documentations

Java For Loop :

Example : Create a Java application for Multiplication Table with the following properties :

            1) Define Number.

            2) How many times this number will be multiplied ?

            3) Which number to start from ?

Multiply (n) starting from (x) for (y) times.

/**

*Multiplication Table Development 2021

*/

//Imports

import java.util.*;

//Main Class

public class MultiTable {

//Given Input number

public static int myNum;

//Multiplication counter

public static int counter;

//Multiplication start

public static int startNum;

 //Main sub

 public static void main(String[] args) {

 if (isOK()) {

 CreatemyTable();

 System.out.println("----------------------");

     }

}

  //Function to check if a given number is negative or decimal or a character.

  public static boolean isOK() {

  Scanner myObj = new Scanner(System.in); //User input 1st number.

  System.out.println("Enter Number : ");

  if(myObj.hasNextInt()) {

    myNum = myObj.nextInt();

    return true;

    } else { System.out.println("Error: enter a valid INTEGER.");

return false; }

}

   //Function to Create the Table.

   public static void CreatemyTable() {

   int total;

   Scanner myObj = new Scanner(System.in); //User input COUNTER.

   System.out.println("How many times do you want to multiply your number?!");

   if(myObj.hasNextInt()) {

    counter = myObj.nextInt();

    } else { System.out.println("Error: enter a valid INTEGER.");

   counter=1;}

   //Define Start number.

   Scanner myObj1 = new Scanner(System.in); //User input start number.

   System.out.println("Which number do you want to start from?!");

   if(myObj1.hasNextInt()) {

    startNum = myObj1.nextInt();

    } else { System.out.println("Error: enter a valid INTEGER.");

   startNum=1;}

   for (int i=1;i<=counter;i++) {

   total = startNum*myNum;

   System.out.println("----------------------");

   System.out.println("(" + i + ")  " + myNum + " * " + startNum + " =  " + total);

   startNum++;

       }

}


}

Two Dimensional Arrays :

Definition Example :

int Iarr[][] = {{1,2},{3,4}};

Example1 :

//Two Dimensional Arrays

/*

*Our output : Two rows, Two Columns

* 1 2

* 3 4

*/

public class TwoDimArr{

public static int Iarr[][] = {{1,2},{3,4}};

public static void main(String[] args){PrintArr();}

public static void PrintArr(){

 for(int Ri=0; Ri<2; Ri++){

  for(int Cj=0; Cj<2; Cj++){

  System.out.print("R#" + (Ri+1) + "C#" + (Cj+1) + " [" + Iarr[Ri][Cj] + "]  ");

  }

System.out.println();

 }

}

}