Java Learning (c): Java basic syntax (variables, constants, data types, operators, and data type conversions)

Source: Internet
Author: User
Tags arithmetic operators bitwise bitwise operators logical operators

Java basic syntax (variables, constants, data types, operators, and data type conversions)


1. Variables


In Java, a user can declare a variable by specifying a data type and an identifier whose basic syntax is:

DataType identifier;

Or

DataType identifier = value;

Where datatype is a variable type, such as Int/string/char/double/boolean, identifier is the variable name, or identifier;

Note:
A, the identifier consists of the number 0-9, uppercase and lowercase letters, underscores, dollar signs, renminbi symbols, and all the ASCII code before the hexadecimal 0xc0;

b, a variable in a class or struct, the default initial value is 0 if no display is initialized, and the variable in the method must be initialized, otherwise an error occurs.

Variables according to the scope of the variable can be divided into: class variables, local variables, method parameter variables, exception handling parameter variables .

The sample code is as follows:

/******************************************************************************** * Example code for how to use class variables */class classvariable {int price=100;//define class variable pricestring name;//define class variable Nameint num;//Define class variable Num}public class Grammar {public static void Main (string[] args) {classvariable c = new classvariable (); System.out.println ("price=" +c.price); System.out.println ("name=" +c.name); System.out.println ("num=" +c.num);}  * * Example code for use of "local variables" */public class Grammar {public static void main (string[] args) {int a=7;if (5>3) {int s=3; System.out.println ("s=" +s); System.out.println ("a=" +a); System.out.println ("s=" +s); System.out.println ("a=" +a); }//////////////////////////////////////* * Method parameter variable Use example code */public class Grammar {public static void Testfun (int s) { System.out.println ("s=" +s); public static void Main (string[] args) {testfun (100);}} * * "Exception handling parameter variable" Method example code */public class Grammar {public static void Test () {try{ System.out.println ("hello! Exception! ");} catch (Exception e) {//exception handling block, parameter is Exception type E.printstacktrace ();}} public static void Main (String [] args) {test ();}}


2. Constants


A constant is defined with the Const keyword in c/s + +, whereas in Java Const is not a key character, but rather a reserved character, which uses the final keyword to define a constant with the following syntax:

Final DataType Constantname;

Where final is the keyword that defines the constant, datatype is the data type that indicates the constant, and Constantname is the name of the constant.

Note:

A, you need to initialize the constants when they are defined;

B, final can be used not only to modify constants of the basic data type, but also to modify the object's reference or method.

C, in the Java language, constants generally use uppercase characters in order to distinguish them from variables.

The sample code is as follows:

/******************************************************************************** * How to use the "constant" example code */public class Grammar {public static void main (String [] args) {final double pi=3.1415926;int r=10;double c=2*pi*r; System.out.println ("circumference of circle =" +c);//pi=10;}}


3. Data type


The data types of the Java language are divided into two main categories: basic data Types (byte byte, character char, BOOL Boolean, single-precision float float, double-precision floating-point double, integer int, short integer- Long) and reference data types (arrays, classes class, Interface interface).

Specific example:



Note:

A, the size of all the basic data types have been clearly defined, on a variety of platforms remain unchanged, this feature helps to improve the portability of Java programs;

b, the reference data type is user-defined, to restrict the type of other data, theJava language does not support the pointer type, struct type, union type and enumeration type in C + + ;

c, for floating-point data, the default is double, if you want to be seen as float, you need to add F or f after the data;

The character type in the Java language is represented by a two-byte Unicode encoding, and the word wildcard is commonly used in hexadecimal notation, ranging from \u0000 to \uffff, which is 0 to 65535.


The sample code is as follows:

/******************************************************************************** * Example code for use of "integer type" */public class Grammar {public static void main (String [] args) {byte a=10;short b=20;int c=30;long d=40;long sum=a+b+c+d; System.out.println ("10+20+30+40=" +sum);} /* * Use of the "floating-point Type" example code */public class Grammar {public static void main (String [] args) {double x=10.23;int a=2;float sum= (flo at) X*a; System.out.println ("sum=" +sum);} /* * "Boolean type" method Example code */public class Grammar {public static void main (String [] args) {Boolean a=true; System.out.println ("a=" +a);} /* * Use of the "character type" Sample code */public class Grammar {public static void main (String [] args) {char a= ' a '; char b= ' B '; System.out.println ("a+b=" + (A+b));}}

4. Operators


Operators include arithmetic operators, comparison operators, logical operators, assignment operators, conditional operators, self-increment decrement operators, bitwise operators, and also take into account the precedence level of operators.

Note:

A, self-increment decrement operators, such as i++ and ++i, whose rules are who to count first;

b, in the in-place operator, the bitwise XOR operator is ^, which should pay special attention;

The sample code is as follows:

/******************************************************************************** * Example code for how to use the "arithmetic operator" */import java.util.scanner;//code Input Scanner, the system automatically joins this code public class Grammar {public static void main (String [] args) {Scanner input = new Scanner (system.in);//System Input SYSTEM.OUT.PRINTLN ("Please enter first number:"); int num1=input.nextint (); System.out.println ("Please enter second number:"); int num2=input.nextint (); float add=num1+num2;float sub=num1-num2;float multi=num1* Num2;int div=num1/num2;float rem=num1%num2; System.out.println ("add=" +add+ ", sub=" +sub+ ", multi=" +multi+ ", div=" +div+ ", rem=" +rem);}} /* * Priority Usage Example code */public class Grammar {public static void main (String [] args) {int a=10;int b=5;int c=12;int result=a +b-(a++) * (b--)%c; System.out.println ("result=" +result);}

5. Data type Conversion


Data type conversions are divided into implicit conversions (automatic type conversions) and explicit conversions (coercion of type conversions).

The implementation of automatic type conversion needs to meet two conditions: first, the two data types are compatible with each other, and the second is that the range of destination types is greater than the source data type, that is, the low-level data type is converted to advanced type data.

The conversion rules are as follows:

(1), the conversion of numerical data:byte->short->int->long->float->double;

(2), character type conversion to integer type: Char->int.

Conversions of the above data types follow a left-to-right conversion order and are ultimately converted into the data type of the variable representing the largest range in the expression.

Display Transformations : When the two data types are incompatible or the value of the type is less than the source type, the automatic conversion is not possible and a forced type conversion is required.


6. Example Demo--Convert integer to binary number


The reference code is as follows:

/******************************************************************************** * "Combat-convert integers to binary"--difficulty factor: ★★★*/ public class Grammar {//First step: Define a Class static string convertinttobinary (int n)//second step: Define a Method {string binary= "";//Save binary string int i= n;//declares the I variable, assigns the value of parameter n to it int m=0;//declaration initialization Variable Mwhile (i>1) {i=n/2;m=n%2;binary =integer.tostring (m) +binary;// Add to binary string n=i;} if (i>0) binary= "1" +binary;return binary;} public static void Main (String [] args) {System.out.println ("14 is converted to binary:" +convertinttobinary (14)); System.out.println ("15 converted to binary:" +convertinttobinary (15));}}





Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Learning (c): Java basic syntax (variables, constants, data types, operators, and data type conversions)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.