• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

in28minutes/java-cheat-sheet: Java Tutorial For Beginners - Companion Reference

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

in28minutes/java-cheat-sheet

开源软件地址:

https://github.com/in28minutes/java-cheat-sheet

开源编程语言:


开源软件介绍:

Java Tutorial For Beginners - A Cheat Sheet

Review Java 9 Concepts at Jet Speed.

Complete Java Course

Image

Image

Image

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 alt text
  • 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.
System.out.println(10 % 4);//2
System.out.println(15 % 4);//3
System.out.println(-15 % 4);//-3

Conditional Operator

  • Conditional Operator is a Ternary Operator (3 Operands)
  • syntax : booleanCondition ? ResultIfTrue: ResultIfFalse;
int age = 18;

System.out.println(
age >= 18 ? "Can Vote": "Cannot Vote");//Can Vote

age = 15;

System.out.println(
age >= 18 ? "Can Vote": "Cannot Vote");//Cannot Vote

Bitwise Operators

  • You can work at bit level with these operators.
  • & is bitwise AND, | is bitwise OR, ~ is bitwise complement (negation), ^ is bitwise XOR, << is left shift bitwise operator and >> is right shift bitwise operator.
System.out.println(25|12);//output will be 29
/*convert to binary and calculate: 
00001100 (12 in decimal)
00011001 (25 in decimal)
________
00011101 (29 in decimal) */
System.out.println(25&12);//output will be 8
System.out.println(25^12);//output will be 21

Passing Variables to Methods

  • All variables , primitives and references , in Java, are passed to functions using copy-of-variable-value.

Passing Variables to Methods : Example

  • Passing a primitive variable and modifying the value in a method
  • Passing a reference variable and modifying the value in a method

Returning a Value From Method

  • null is a valid return value for an object.
  • You can return andy type that can be implicitly coverted to return type.
  • You cannot return anything from a void method.

Types of Variables

  • Different Types of Variables: Static, Member (or instance), Local, Block

Instance Variables

  • Declared inside a class outside any method.
  • Each instance of the class would have its own values.
  • Also called member value, field or property.

Local Variables

  • Variables declared in a method
  • Local Variables can only be marked with final modifier
  • If the name of a Local Variable is same as the name of an instance variable, it results in shadowing.

Member Variables

  • Defined at class level and without keyword static.

Static Variable

  • Defined at class level and using keyword static.

Member Variable and Static Variable

  • Member Variables can be accessed only through object references.
  • Static Variables can be accessed through a. Class Name and b. Object Reference. It is NOT recommended to use object reference to refer to static variables.

Example Static and Member Variables

public class StaticAndMemberVariables {
    public static void main(String[] args) {
	Actor actor1 = new Actor();
	actor1.name = "ACTOR1";
	//Actor.name //Compiler Error

	//Below statement can be written as actor1.count++
	//But NOT recommended.
	Actor.count++;

	Actor actor2 = new Actor();
	actor2.name = "ACTOR2";

	//Below statement can be written as actor2.count++
	//But NOT recommended.
	Actor.count++;

	System.out.println(actor1.name);//ACTOR1
	System.out.println(actor2.name);//ACTOR2

	//Next 3 statements refer to same variable
	System.out.println(actor1.count);//2
	System.out.println(actor2.count);//2
	System.out.println(Actor.count);//2
    }
}

class Actor {
    //RULE 1: Member Variables can be accessed 
    //only through object references
     

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap