25244173 Java Struts Spring Hibernate Tutorial Github Com Chrishulbert Java Tutorial
Java Tutorial Java Data Type.doc
-
Upload
contactarindom -
Category
Documents
-
view
238 -
download
1
description
Transcript of Java Tutorial Java Data Type.doc
Java Tutorial Java Data Type, OperatorIntroduction
1 Learn how to use Java int type 2 Create your first Java program 3 How to define more complex Java program 4 What are Java Keywords and Identifiers 5 What are variables in a Java program
Primitive Data Types
6 What are the primitive data types in Java 7 Java boolean type 8 Java char type 9 Java char value escape 10 Java byte type 11 Java short type 12 Java long type 13 Java float type 14 Java double type 15 Java String type 16 Java String Escape 17 Java String Concatenation
Operator
18 Java Arithmetic Operators 19 Arithmetic Compound Assignment Operators 20 Java Increment and Decrement Operator 21 Java Logical Operators 22 Java Logical Operators Shortcut 23 Java Relational Operators 24 Java Bitwise Operators 25 Java Left Shift Operator 26 Java Right Shift Operator 27 Java Unsigned Right Shift 28 Java ternary operator 29 Use of instance comparisons with instanceof operator in Java
Main
30 Use of argv to get an integer value from command line in Java
Java int typeDescription
When byte and short values are used in an expression they are promoted to int when the expression is evaluated.
Size and value
int is a signed 32-bit type that has a range from -2,147,483,648 to 2,147,483,647.
octal integer(base eight)
Octal values are denoted in Java by a leading zero. valid value 09 will produce an error from the compiler, since 9 is outside of octal's 0 to 7 range.
public class Main {
public static void main(String[] args) {
int i = 010;
System.out.println(i);
}
}
The output:
hexadecimal integer(base 16)
hexadecimal matches with modulo 8 word sizes, such as 8, 16, 32, and 64 bits. You signify a hexadecimal constant with a leading zero-x, (0x or 0X).
The range of a hexadecimal digit is 0 to 15, so A through F (or a through f ) are substituted for 10 through 15.
An integer literal can always be assigned to a long variable. An integer can also be assigned to a char as long as it is within range.
public class Main{
public static void main(String[] argv){
int f = 0XFFFFF;
System.out.println(f);//1048575
}
}
The code above generates the following result.
Your first Java programCreate Java file
Let's start by compiling and running the following short sample program.
/*
This is a simple Java program. Call this file "Main.java".
*/
public class Main {
// Your program begins with a call to main().
public static void main(String args[]) {
System.out.println("Java.");
}
}
In Java, a source file is called a compilation unit. It is a text file that contains one or more class definitions. The Java compiler requires that a source file use the .java filename extension.
In Java, all code must reside inside a class. By convention, the name of the public class should match the its file name. And Java is case-sensitive.
The code above generates the following result.
Compiling the Program
To compile the program, execute the compiler, javac, specifying the name of the source file on the command line:
C:\>javac Main.java
The javac compiler creates a file called Main.class. Main.class contains the byte code version of the program.
To run the program, use the Java interpreter, called java. Pass the class name Main as a command-line argument, as shown here:
C:\>java Main
When the program is run, the following output is displayed:
When Java source code is compiled, each individual class is put into its own file named classname.class.
A Closer Look at the Main.java
The first part is a comment.
/*
This is a simple Java program. Call this file "Main.java".
*/
Comment is a remark for a program. The contents of a comment are ignored by the compiler. The next line of code in the program is shown here:
public class Main {
The keyword class declares that a new class is being defined. Main is the name of the class. The entire class definition is between the opening curly brace ({) and the closing curly brace (}). The next line in the program is the single-line comment, shown here:
// Your program begins with a call to main().
A single-line comment begins with a // and ends at the end of the line. The next line of code is shown here:
public static void main(String args[]) {
Java applications begin execution by calling main(String args[]). Java is case-sensitive. Thus, Main is different from main.
Your second Java programA Short Program with a variable
A variable is a memory location that may be assigned a value. The value of a variable is changeable.
The following code defines a variable and change its value by assigning a new value to it.
public class Main {
public static void main(String args[]) {
int num; // a variable called num
num = 100;
System.out.println("This is num: " + num);
num = num * 2;
System.out.print("The value of num * 2 is ");
System.out.println(num);
}
}
When you run this program, you will see the following output:
The following snippet declares an integer variable called num. Java requires that variables must be declared before they can be used.
int num; // this declares a variable called num
Following is the general form of a variable declaration:
type var-name;
In the program, the line assigns to num the value 100.
num = 100; // this assigns num the value 100
Define more than one variable with comma
To declare more than one variable of the specified type, you may use a comma-separated list of variable names.
public class Main {
public static void main(String args[]) {
int num, num2;
num = 100; // assigns num the value 100
num2 = 200;
System.out.println("This is num: " + num);
System.out.println("This is num2: " + num2);
}
}
When the program is run, the following output is displayed:
Using Blocks of Code
Java can group two or more statements into blocks of code. Code block is enclosing the statements between opening and closing curly braces({}).
For example, a block can be a target for Java's if and for statements. Consider this if statement:
public class Main {
public static void main(String args[]) {
int x, y;
x = 10;
y = 20;
if (x < y) { // begin a block
x = y;
y = 0;
System.out.println("x=" + x);
System.out.println("y=" + y);
} // end of block
}
}
Here is the output of the code above:
A block of code as the target of a for loop.
public class Main {
public static void main(String args[]) {
int i, y;
y = 20;
for (i = 0; i < 10; i++) { // the target of this loop is a block
System.out.println("This is i: " + i);
System.out.println("This is y: " + y);
y = y - 1;
}
}
}
Java Keywords and IdentifiersFull list of keywords in Java
A keyword is a word whose meaning is defined by the programming language. Java keywords and reserved Words:
abstract class extends implements null strictfp true
assert const false import package super try
boolean continue final instanceof private switch void
break default finally int protected synchronized volatile
byte do float interface public this while
case double for long return throw
catch else goto native short throws
char enum if new static transient
An identifier is a word used by a programmer to name a variable, method, class, or label. Keywords and reserved words may not be used as identifiers. An identifier must begin with a letter, a dollar sign ($), or an underscore (_); subsequent characters may be letters, dollar signs, underscores, or digits.
Some examples are:
foobar // legal
Myclass // legal
$a // legal
3_a // illegal: starts with a digit
!theValue // illegal: bad 1st char
Java Identifiers are case sensitive. For example, myValue and MyValue are distinct identifiers.
Using identifiers
Identifiers are used for class names, method names, and variable names. An identifier may be any sequence of uppercase and lowercase letters, numbers, or the underscore and dollar-sign characters. Identifiers must not begin with a number. Java Identifiers are case-sensitive. The following code illustrates some examples of valid identifiers:
public class Main {
public static void main(String[] argv) {
int ATEST, count, i1, $Atest, this_is_a_test;
}
}
The following code shows invalid variable names include:
public class Main {
public static void main(String[] argv){
int 2count, h-l, a/b,
}
}
If you try to compile this code, you will get the following error message:
Java VariableDeclaring a Variable
A variable is defined by an identifier, a type, and an optional initializer. The variables also have a scope(visibility / lifetime).
In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;
There are three parts in variable definition:
31 typecould be int or float.32 identifieris the variable's name.33 Initialization includes an equal sign and a value.
To declare more than one variable of the specified type, use a comma-separated list.
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing d and f.
The following variables are defined and initialized in one expression.
public class Main {
public static void main(String[] argv) {
byte z = 2; // initializes z.
double pi = 3.14; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.
}
}
Variable cannot be used prior to its declaration.
public class Main {
public static void main(String[] argv) {
count = 100; // Cannot use count before it is declared!
int count;
}
}
Compiling the code above generates the following error message:
Assignment Operator
The assignment operator is the single equal sign, =. It has this general form:
var = expression;
type of var must be compatible with the type of expression. The assignment operator allows you to create a chain of assignments.
public class Main {
public static void main(String[] argv) {
int x, y, z;
x = y = z = 100; // set x, y, and z to 100
System.out.println("x is " + x);
System.out.println("y is " + y);
System.out.println("z is " + z);
}
}
The output:
Dynamic Initialization
Java allows variables to be initialized dynamically. In the following code the Math.sqrt returns the square root of 2 * 2 and assigns the result to c directly.
public class Main {
public static void main(String args[]) {
// c is dynamically initialized
double c = Math.sqrt(2 * 2);
System.out.println("c is " + c);
}
}
The output from the code above is
Primitive Data Types
Java Primitive Data TypesJava eight primitive types
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean.
Primitive Type Reserved Word Size Min
Value Max ValueBoolean boolean N/A N/A N/ACharacter char 16-bit Unicode
0Unicode 216 - 1
Byte integer byte 8-bit -128 +127Short integer short 16-bit -215 +215 - 1Integer int 32-bit -231 +231 - 1Long integer long 64-bit -263 +263 - 1Floating-point float 32-bit 1.4e-045 3.4e+038Double precision floating-point double 64-bit 4.9e-324 1.8e+308
byte, short, int, and long are for whole-valued signed numbers. float and double are fractional precision numbers.
char represents symbols in a character set, like letters and numbers. boolean represents true/false values.
Java Integers
Java defines four integer types: byte, short, int, and long.
Integer types are signed and can have positive and negative values.
The width and ranges of these integer types vary widely:
Name
Width Range
long 64 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int 32 -2,147,483,648 to 2,147,483,647short 16 -32,768 to 32,767byte 8 -128 to 127
Floating Point Types
There are two kinds of floating-point types: float and double. float type represents single-precision numbers. double type stores double-precision numbers.
Floating-Point Types width and ranges are shown here:
Name Width in Bits
Approximate Range
double 64 4.9e-324 to
1.8e+308float 32 1.4e-045 to
3.4e+038
Java boolean typeDescription type
Java has a boolean type for logical values. This is the type returned by all relational operators.
Value
It can have only one of two possible values, true or false.
Literals
Boolean literals are only two logical values: true and false. The values of true and false do not convert into any numerical representation.
The true literal in Java does not equal 1, nor does the false literal equal 0. In Java, they can only be assigned to variables declared as
boolean.
Boolean class
The Boolean class wraps a primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean.
Boolean class has the methods for converting a boolean to a String and a String to a boolean.
Example
Here is a program that demonstrates the boolean type:
public class Main {
public static void main(String args[]) {
boolean boolVariable;
boolVariable = false;
System.out.println("b is " + boolVariable);
boolVariable = true;
System.out.println("b is " + boolVariable);
}
}
Output:
Example 2
The true literal in Java does not equal 1, nor does the false literal
equal 0. In Java, they can only be assigned to variables declared as boolean.
public class Main {
public static void main(String[] argv) {
boolean b = true;
int i = b;
}
}
If you try to compile the program, the following error message will be generated by compiler.
Java char typeDescription
In Java, char stores characters. Java uses Unicode to represent characters. Unicode can represent all of the characters found in all human languages.
Size
Java char is a 16-bit type.
Value Range
The range of a char is 0 to 65,536. There are no negative chars.
Literals
Characters in Java are indices into the Unicode character set. character is represented inside a pair of single quotes. For example, 'a', 'z', and '@'.
Example
Here is a program that demonstrates char variables:
public class Main {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);//ch1 and ch2: X Y
}
}
The code above generates the following result.
ch1 is assigned the value 88, which is the ASCII (and Unicode) value that corresponds to the letter X.
char type value can be used as an integer type and you can perform arithmetic operations.
public class Main {
public static void main(String args[]) {
char ch1;
ch1 = 'X';
System.out.println("ch1 contains " + ch1);//ch1 contains X
ch1 = (char)(ch1 + 1); // increment ch1
System.out.println("ch1 is now " + ch1);//ch1 is now Y
}
}
Example 2
public class Main {
public static void main(String[] argv) {
char ch = 'a';
System.out.println("ch is " + ch);//ch is a
ch = '@';
System.out.println("ch is " + ch);//ch is @
ch = '#';
System.out.println("ch is " + ch);//ch is #
ch = '$';
System.out.println("ch is " + ch);//ch is $
ch = '%';
System.out.println("ch is " + ch);//ch is %
}
}
The code above generates the following result.
Example 3
The following code stores unicode value into a char variable. The unicode literal uses \uxxxx format.
public class Main {
public static void main(String[] args) {
int x = 75;
char y = (char) x;
char half = '\u00AB';
System.out.println("y is " + y + " and half is " + half);
}
}
The code above generates the following result.
Java char value escapeDescription
The escape sequences are used to enter impossible-to-enter-directly characters.
Syntax
'\'' is for the single-quote character. '\n' is for the newline character.
Example
For octal notation, use the backslash followed by the three-digit number. For example, '\141' is the letter 'a'.
For hexadecimal, you enter a backslash-u (\u), then exactly four hexadecimal digits. For example, '\u0061' is the ISO-Latin-1 'a' because the top byte is zero. '\ua432' is a Japanese Katakana character.
public class Main {
public static void main(String[] argv) {
char ch = '\'';
System.out.println("ch is " + ch);//ch is '
}
}
Character is a simple wrapper around a char.
The code above generates the following result.
Escape value list
The following table shows the character escape sequences.
Escape Sequence Description
\ddd Octal character (ddd)\uxxxx Hexadecimal Unicode character
(xxxx)\' Single quote\" Double quote\\ Backslash\r Carriage return\n New line\f Form feed\t Tab\b Backspace
Java byte typeDescription
The smallest integer type is byte. byte type variables are useful when working with a stream of data from a network or file.
Byte variables are declared by use of the byte keyword. The following declares two byte variables called b and c:
byte b, c;
Size and value
byte is a signed 8-bit type that has a range from -128 to 127.
Example
The following code creates two byte type variables and assigns values.
public class Main {
public static void main(String[] args) {
byte b1 = 100;
byte b2 = 20;
System.out.println("Value of byte variable b1 is :" + b1);
System.out.println("Value of byte variable b1 is :" + b2);
}}
The code above generates the following result.
The Byte class wraps a value of primitive type byte in an object. Byte class provides several methods for converting a byte to a String and a String to a byte.
Java short typeDescription
The size of Java short type is between byte and integer.
Size and value
short is a signed 16-bit type. short type variable has a range from -
32,768 to 32,767.
Example
Here are some examples of short variable declarations:
short s;
short t;
Java long typeDescription
Java long type is used when an int type is not large enough.
Size and value
long is a signed 64-bit type and . The range of long type is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Literals
To specify a long literal, you need to tell the compiler that the literal value is of type long by appending an upper- or lowercase L to the literal. For example, 0x7ffffffffffffffL or 123123123123L.
Example
The following code creates a long type literal and assigns the value to a long type variable.
public class Main {
public static void main(String args[]) {
long l = 0x7ffffffffffffffL;
System.out.println("l is " + l);
}
}
The output generated by this program is shown here:
Example 2
Here is a program that use long type to store the result.
public class Main {
public static void main(String args[]) {
long result= (long)Integer.MAX_VALUE * (long)10;
System.out.println(result);//21474836470
}
}
The result could not have been held in an int variable.
The code above generates the following result.
Java float typefloat type
float type represents single-precision numbers.
float type variables are useful when you need a fractional component.
Here are some example float variable declarations:
float high, low;
Value and size
float is 32-bit width and its range is from 1.4e-045 to 3.4e+038 approximately.
Literals
Floating-point literals in Java default to double precision. To specify a float literal, you must append an F or f to the constant.
Example 1
The following code shows how to declare float literals.
public class Main {
public static void main(String args[]) {
float d = 3.14159F;
System.out.print(d);//3.14159
}
}
The code above generates the following result.
Java double typeDescription
Java double type represents double-precision numbers.
Size and value
double is 64-bit width and its range is from 4.9e-324 to 1.8e+308 approximately.
Example
Here is a program that uses double variables to compute the area of a circle:
public class Main {
public static void main(String args[]) {
double pi, r, a;
r = 10.8888; // radius of circle
pi = 3.1415926; // pi, approximately
a = pi * r * r;
System.out.println("Area of circle is " + a);
}
}
The output:
Literals
double type numbers have decimal values with a fractional component. They can be expressed in either standard or scientific notation. Standard notation consists of a whole number component followed by a decimal point followed by a fractional component. For example, 2.0, 3.14159, and 0.6667.
public class Main {
public static void main(String args[]) {
double d = 3.14159;
System.out.print(d);//3.14159
}
}
The code above generates the following result.
Literal Letter
You can explicitly specify a double literal by appending a D or d.
public class Main {
public static void main(String args[]) {
double d = 3.14159D;
System.out.print(d);//3.14159
}
}
The code above generates the following result.
Scientific notation
Scientific notation uses a standard-notation, floating-point number plus a suffix that specifies a power of 10 by which the number is to be multiplied. The exponent is indicated by an E or e followed by a decimal number, which can be positive or negative. For example, 6.02E23, 314159E-05, and 4e+100.
public class Main {
public static void main(String[] argv) {
double d1 = 6.022E23;
double d2 = 314159E-05;
double d3 = 2e+100;
System.out.println("d1 is " + d1);
System.out.println("d2 is " + d2);
System.out.println("d3 is " + d3);
}
}
The output generated by this program is shown here:
double value constant
Java's floating-point calculations are capable of returning +infinity, -infinity, +0.0, -0.0, and NaN
dividing a positive number by 0.0 returns +infinity. For example, System.out.println(1.0/0.0); outputs Infinity.
public class Main{
public static void main(String[] args) {
System.out.println(1.0/0.0);
}
}
The code above generates the following result.
double Infinity
Dividing a negative number by 0.0 outputs -infinity. For example, System.out.println(-1.0/0.0); outputs -Infinity.
public class Main{
public static void main(String[] args) {
System.out.println(-1.0/0.0); }
}
Output:
double NaN
Dividing 0.0 by 0.0 returns NaN. square root of a negative number is NaN. For example, System.out.println(0.0/0.0) and System.out.println(Math.sqrt(-1.0)) output NaN.
Dividing a positive number by +infinity outputs +0.0. For example, System.out.println(1.0/(1.0/0.0)); outputs +0.0.
Dividing a negative number by +infinity outputs -0.0. For example, System.out.println(-1.0/(1.0/0.0)); outputs -0.0.
public class Main {
public static void main(String[] args) {
Double d1 = new Double(+0.0);
System.out.println(d1.doubleValue());
Double d2 = new Double(-0.0);
System.out.println(d2.doubleValue());
System.out.println(d1.equals(d2));
System.out.println(+0.0 == -0.0);
}
}
The code above generates the following result.
Java String typeDescription
The String class represents character strings. A quoted string constant can be assigned to a String variable.
Literal
String literals in Java are specified by enclosing a sequence of characters between a pair of double quotes. In Java strings are actually object types.
Example
Declare String type variable.
public class Main{
public static void main(String[] argv){
String str = "this is a test from java.com";
System.out.println(str);
}
}
equals() vs ==
equals( ) method and the == operator perform two different operations. equals( ) method compares the characters inside a String
object. The == operator compares two object references to see whether they refer to the same instance.
The following program shows the differences:
public class Main {
public static void main(String args[]) {
String s1 = "demo.com";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}
Here is the output of the preceding example:
Java String EscapeDescription
The escape sequences are used to enter impossible-to-enter-directly strings.
Syntax
For example, "\"" is for the double-quote character. "\n" for the newline string.
For octal notation, use the backslash followed by the three-digit number. For example, "\141" is the letter "a".
For hexadecimal, you enter a backslash-u (\u), then exactly four hexadecimal digits. For example, "\u0061" is the ISO-Latin-1 "a" because the top byte is zero. "\ua432" is a Japanese Katakana character.
Escape List
The following table summarizes the Java String escape sequence.
Escape Sequence Description
\ddd Octal character (ddd)\uxxxx Hexadecimal Unicode character
(xxxx)\' Single quote\" Double quote\\ Backslash\r Carriage return\n New line\f Form feed\t Tab\b Backspace
Example
Examples of string literals with escape are
"Hello World"
"two\nlines"
"\"This is in quotes\""
The following example escapes the new line string and double quotation string.
public class Main {
public static void main(String[] argv) {
String s = "java.com";
System.out.println("s is " + s);
s = "two\nlines";
System.out.println("s is " + s);
s = "\"quotes\"";
System.out.println("s is " + s);
}
}
Example 2
Java String literials must be begin and end on the same line. If your string is across several lines, the Java compiler will complain about it.
public class Main {
public static void main(String[] argv){
String s = "line 1
line 2
";
}
}
Java String ConcatenationDescription
You can use + operator to concatenate strings together.
Example 1
For example, the following fragment concatenates three strings:
public class Main {
public static void main(String[] argv) {
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s); }
}
Example 2
The following code uses string concatenation to create a very long string.
public class Main {
public static void main(String args[]) {
String longStr = "A java com" +
"B j a v a .c o m " +
"C java com" +
"D java.com .";
System.out.println(longStr);
}
}
Example 3
You can concatenate strings with other types of data.
public class Main {
public static void main(String[] argv) {
int age = 1;
String s = "He is " + age + " years old.";
System.out.println(s);
}
}
The output:
Example 4
Be careful when you mix other types of operations with string concatenation. Consider the following:
public class Main {
public static void main(String[] argv) {
String s = "four: " + 2 + 2;
System.out.println(s); }
}
This fragment displays
rather than the
To complete the integer addition first, you must use parentheses, like this:
String s = "four: " + (2 + 2);
Now s contains the string "four: 4".
Operator