Java Tutorial for Beginners - a Cheat Sheet
Total Page:16
File Type:pdf, Size:1020Kb
Java Tutorial For Beginners - A Cheat Sheet Review Java 9 Concepts at Jet Speed. Complete Java Course Introduction Background Popularity of Java Platform Independent or Portable Object Oriented Language Security Rich API Great IDE's Omnipresent Web Applications (Java EE (JSP, Servlets), Spring, Struts..) Mobile Apps(Android) Microservices (Spring Boot) Platform Independence Build once, run anywhere Java bytecode is the instruction set of the Java virtual machine graph TD A[Java Code] -->|Compiled| B(Bytecode) B --> C{Run} C -->|bytecode| D[Windows JVM] D --> K[Windows Instructions] C -->|bytecode| E[Unix JVM] E --> L[Unix Instructions] C -->|bytecode| F[Linux JVM] F --> M[Linux Instructions] C -->|bytecode| G[Any other platform JVM] G --> N[Linux Instructions] JDK vs JVM VS JRE JVM (Java Virtual Machine) runs the Java bytecode. JRE JVM + Libraries + Other Components (to run applets and other java applications) JDK JRE + Compilers + Debuggers ClassLoader Find and Loads Java Classes! Three Types System Class Loader - Loads all application classes from CLASSPATH Extension Class Loader - Loads all classes from extension directory Bootstrap Class Loader - Loads all the Java core files Order of execution of ClassLoaders JVM needs to find a class, it starts with System Class Loader. If it is not found, it checks with Extension Class Loader. If it not found, it goes to the Bootstrap Class Loader. If a class is still not found, a ClassNotFoundException is thrown. First Java Program public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } } Notes Every line of code we write in Java is part of something called Class. We will talk about Class later. First line defines a public class called HelloWorld. All the code in a class is between { and }. When a program runs, Java should know which line of code has to be run first. public static void main(String[] args) is the first method that is run when a program is executed. Java, like any other programming language, is particular about syntax!! Using Java and JavaC There are two steps involved in running a Java Program Compilation Execution Compilation We use javac to compile java code. Open CommandPrompt/Terminal and cd to the folder where HelloWorld.java file is present execute the command below javac HelloWorld.java You should see two files HelloWorld.java and HelloWorld.class in the folder. HelloWorld.class contains the java bytecode Execution Now we can run the program using JVM execute the command below java HelloWorld You should see the output "Hello World" printed in the console. Class and Object What is a class? Definining an instance of a class - an object Invoking a method on the object Variables Value of a variable changes during the course of a program execution. int number; number = 5; System.out.println(number);//5 number = number + 2; System.out.println(number);//7 number = number + 2; System.out.println(number);//9 Declaring and Initializing Variables Declaration is give a variable a name and type TYPE variableName; Tips Two or more variables of single type can be declared together. Variable can be local or global. The local variables can be referenced (ie, are valid) only within the scope of their method (or function). All six numeric types in Java are signed. Primitive Variables Variables that store value. Java defines few types like int (numbers), float(floating point numbers), char (characters). Variables of these types store the value of the variable directly. These are not objects. These are called primitive variables. An example is shown below: Primitive Variables contains bits representing the value of the variable. int value = 5; Different primitive types in java are char, boolean, byte, short, int, long, double, or float. Because of these primitive types, Java is NOT considered to be a pure objected oriented language. Numeric Data Types Types : byte, short, int, long, float, double Number of bits : 8, 16, 32, 64, 32, 64 Range : -x to x-1 where x = Power(2, number of bits -1) char Data Type Used to store characters. Size of character is 16 bits. Examples int i = 15; long longValue = 1000000000000l; byte b = (byte)254; float f = 26.012f; double d = 123.567; boolean isDone = true; boolean isGood = false; char ch = 'a'; char ch2 = ';'; Reference Variables Animal dog = new Animal(); The instance of new Animal - Animal object - is created in memory. The memory address of the object created is stored in the dog reference variable. Reference Variables contains a reference or a guide to get to the actual object in memory. Puzzles Animal dog1 = new Animal(); dog1 = new Animal(); What will happen? Two objects of type Animal are created. Only one reference variable is created. Animal animal1 = new Animal(); Animal animal2 = new Animal(); animal1 = animal2; What will happen? What would happen if the same was done with primitive variables? Identifiers Names given to a class, method, interface, variables are called identifiers. Legal Identifier Names Combination of letters, numbers, $ and under-score(_) Cannot start with a number Cannot be a keyword No limit on length of identifier Java Keywords List of Java Keywords Primitives DataTypes : byte,short,int,long,float,double,char,boolean Flow Control : if, else,for,do, while, switch, case, default, break, continue,return Exception Handling : try, catch, finally,throw,throws,assert Modifiers : public,private,protected,final,static,native,abstract, synchronized,transient,volatile,strictfp Class Related : class,interface,package,extends,implements,import Object Related : new, instanceof,super,this Literals : true, false, null Others : void, enum Unused : goto,const Literals Any primitive data type value in source code is called Literal. There are four types of literals: Integer & Long Floating Point Boolean Double Literals Integer Literals There are 3 ways of representing an Integer Literal. Decimal. Examples: 343, 545 Octal. Digits 0 to 7. Place 0 before a number. Examples : 070,011 Hexadecimal. Digits 0 to 9 and alphabets A to F (10-15). Case insensitive. An integer literal by default is int. Long Literals All 3 integer formats: Decimal, Octal and Hexadecimal can be used to represent long by appending with L or l. Floating point Literals Numbers with decimal points. Example: double d = 123.456; To declare a float, append f. Example: float f = 123.456f; Floating point literals are double by default. Appending d or D at end of double literal is optional Example: double d = 123.456D; Boolean Literals Valid boolean values are true and false. TRUE, FALSE or True, False are invalid. Character Literals Represented by single character between single quotes Example: char a = 'a' Unicode Representation also can be used. Prefix with \u. Example: char letterA = '\u0041'; A number value can also be assigned to character. Example: char letterB = 66; Numeric value can be from 0 to 65535; Escape code can be used to represent a character that cannot be typed as literal. Example: char newLine = '\n'; Puzzles int eight = 010; int nine=011; int invalid = 089;//COMPILER ERROR! 8 and 9 are invalid in Octal int sixteen = 0x10; int fifteen = 0XF; int fourteen = 0xe; int x = 23,000; long a = 123456789l; long b = 0x9ABCDEFGHL; long c = 0123456789L; float f = 123.456;//COMPILER ERROR! A double value cannot be assigned to a float. boolean b = true; boolean b=false; boolean b = TRUE;//COMPILATION ERROR boolean b = 0; //COMPILER ERROR. This is not C Language char ch = a; char a = 97; char ch1 = 66000; //COMPILER ERROR! Tip - Assignment Operator Assignment operator evaluates the expression on the right hand side and copies the value into the variable on the left hand side. Basic Examples int value = 35;//35 is copied into 35 int squareOfValue = value * value;//value * value = 35 * 35 is stored into squareOfValue int twiceOfValue = value * 2; Puzzles int a1 = 5; int b1 = 6; b1 = a1; // value of a1 is copied into b1 a1 = 10; // If we change a1 or b1 after this, it would not change the other variable.. b1 will remain 6 Actor actor1 = new Actor(); actor1.setName("Actor1"); //This creates new reference variable actor1 of type Actor new Actor() on the heap assigns the new Actor on the heap to reference variable Actor actor2 = actor1; actor2.setName("Actor2"); System.out.println(actor1.getName());//Actor2 Casting - Implicit and Explicit Casting is used when we want to convert one data type to another. A literal integer is by default int. Operation involving int-sized or less always result in int. Floating point literals are by default double Implicit Casting Implicit Casting is done directly by the compiler. Example : Widening Conversions i.e. storing smaller values in larger variable types. byte b = 10; //byte b = (int) 10; Example below compiles because compiler introduces an implicit cast. short n1 = 5; short n2 = 6; //short sum = n1 + n2;//COMPILER ERROR short sum = (short)(n1 + n2);//Needs an explicit cast byte b = 5; b += 5; //Compiles because of implicit conversion int value = 100; long number = value; //Implicit Casting float f = 100; //Implicit Casting Explicit Casting Explicit Casting needs to be specified by programmer in code. Example: Narrowing Conversions. Storing larger values into smaller variable types; Explicit casting would cause truncation of value if the value stored is greater than the size of the variable. long number1 = 25678; int number2 = (int)number1;//Explicit Casting //int x = 35.35;//COMPILER ERROR int x = (int)35.35;//Explicit Casting int bigValue = 280; byte small = (byte) bigValue; System.out.println(small);//output 24. Only 8 bits remain. //float avg = 36.01;//COMPILER ERROR. Default Double float avg = (float) 36.01;//Explicit Casting float avg1 = 36.01f; float avg2 = 36.01F; //f or F is fine //byte large = 128; //Literal value bigger than range of variable type causes compilation error byte large = (byte) 128;//Causes Truncation! Compound Assignment Operators Examples : +=, -=, *= int a = 5; a += 5; //similar to a = a + 5; a *= 10;//similar to a = a * 10; a -= 5;//similar to a = a - 5; a /= 5;//similar to a = a / 5; Other Operators Remainder(%) Operator Remainder when one number is divided by another.