Академический Документы
Профессиональный Документы
Культура Документы
Java program.When you run the Java program, Java compiler first compiles your Java
code to bytecode. Then, the JVM translates bytecode into native machine code (set of
instructions that a computer's CPU executes directly).Java is a platform-independent
language. It's because when you write Java code, it's ultimately written for JVM but not
your physical machine (computer). Since, JVM executes the Java bytecode which is
.What is JRE?
JRE (Java Runtime Environment) is a software package that provides Java class
libraries, along with Java Virtual Machine (JVM), and other components to run
applications written in Java programming. JRE is the superset of JVM.
If you need to run Java programs, but not develop them, JRE is what you need.
What is JDK?
JDK (Java Development Kit) is a software development kit to develop applications in
Java. When you download JDK, JRE is also downloaded, and don't need to download it
separately. In addition to JRE, JDK also contains number of development tools
(compilers, JavaDoc, Java Debugger etc).
Here's the relationship between JVM, JRE, and JDK.
VM Architecture Diagram
Comments in Java
In programming, comments are portion of the program intended for you and your fellow
programmers to understand the code. They are completely ignored by Java compilers.
In Java programming language, there are two types of comments:
/* ... */
// ....
and
Java Variables
A variable is a location in memory (storage area) to hold data.
To indicate the storage area, each variable should be given a unique name (identifier)..
Java is a statically-typed language. It means that all variables must be declared before
they can be used.
Also, you cannot change the data type of a variable in Java within the same scope.
int speed;
There are 8 data types predefined in Java programming language, known as primitive
data types.In addition to primitive data types, there are also referenced data types in
Java.
8 Primitive Data Types
boolean
The boolean data type has two possible values, either true or false.
Default value: false.
They are usually used for true/false conditions.
Example:
1. class BooleanExample {
2. public static void main(String[] args) {
3. boolean flag = true;
4. System.out.println(flag);
5. }
6. }
Output: true
byte
The byte data type can have values from -128 to 127 (8-bit signed two's complement integer).
It's used instead of int or other integer data types to save memory if it's certain that the value of
a variable will be within [-128, 127].
Default value: 0
Example:
1. class ByteExample {
2. public static void main(String[] args) {
3.
4. byte range;
5. range = 124;
6. System.out.println(range);
7.
8. // Error code below. Why?
9. // range = 200
10. }
11. }
Output: 124
short
The short data type can have values from -32768 to 32767 (16-bit signed two's complement
integer).
It's used instead of other integer data types to save memory if it's certain that the value of the
variable will be within [-32768, 32767].
Default value: 0
Example:
1. class ShortExample {
2. public static void main(String[] args) {
3.
4. short temperature;
5.
6. temperature = -200;
7. System.out.println(temperature);
8.
9. }
10. }
Output: -200
int
The int data type can have values from -231 to 231-1 (32-bit signed two's complement integer).
If you are using Java 8 or later, you can use unsigned 32-bit integer with minimum value of 0
and maximum value of 232-1. If you are interested in learning more about it, visit: How to use the
unsigned integer in java 8?
Default value: 0
Example:
1. class IntExample {
2. public static void main(String[] args) {
3.
4. int range = -4250000;
5. System.out.println(range);
6. }
7. }
Output: -4250000
long
The long data type can have values from -263 to 263-1 (64-bit signed two's complement integer).
If you are using Java 8 or later, you can use unsigned 64-bit integer with minimum value of 0
and maximum value of 264-1.
Default value: 0
Example:
1. class LongExample {
2. public static void main(String[] args) {
3.
4. long range = -42332200000L;
5. System.out.println(range);
6. }
7. }
Output: -42332200000
Notice, the use of L at the end of -42332200000. This represents that it's an integral literal
of long type. You will learn about integral literals later in this article.
double
The double data type is a double-precision 64-bit floating point.
It should never be used for precise values such as currency.
Default value: 0.0 (0.0d)
Example:
1. class DoubleExample {
2. public static void main(String[] args) {
3.
4. double number = -42.3;
5. System.out.println(number);
6. }
7. }
Output: -42.3
float
The float data type is a single-precision 32-bit floating point. Learn more about single precision
and double precision floating point if you are interested.
It should never be used for precise values such as currency.
Default value: 0.0 (0.0f)
Example:
1. class FloatExample {
2. public static void main(String[] args) {
3.
4. float number = -42.3f;
5. System.out.println(number);
6. }
7. }
Output: -42.3
Notice that, we have used -42.3f instead of -42.3in the above program. It's because -
42.3 is a double literal. To tell compiler to treat -42.3 as float rather than double, you
need to use f or F.
char
It's a 16-bit Unicode character.
The minimum value of char data type is '\u0000' (0). The maximum value of char data type
is '\uffff'.
Default value: '\u0000'
Example:
1. class CharExample {
2. public static void main(String[] args) {
3.
4. char letter = '\u0051';
5. System.out.println(letter);
6. }
7. }
Output: Q
Output: 9
A
When you print letter1, you will get 9 because letter1 is assigned character '9'.
When you print letter2, you get A because the ASCII value of 'A' is 65. It's because
java compiler treats character as integral type. Learn more about ASCII.
Java also provides support for character strings via java.lang.String class. Here's how
you can create a String object in Java:
Java String is an important topic which you will learn in detail in later chapters.
However, if you are not a newbie in programming and want to learn it now, visit Java
String.
Java literals
To understand literals, let's take an example to assign value to a variable.
Integer literals can be expressed in decimal, hexadecimal and binary number systems.
The numbers starting with prefix 0x represents hexadecimal. Similarly, numbers starting with
prefix 0b represents binary.
// decimal
int decNumber = 34;
// 0x represents hexadecimal
int hexNumber = 0x2F;
// 0b represents binary
Floating-point Literals
Floating-point literals are used to initialize variables of data type float and double.
If a floating-point literal ends with f or F, it's of type float. Otherwise, it's of type double. A double
type can optionally end with D or d. However, it's not necessary.
They can also be expressed in scientific notation using E or e.
1.
2. class DoubleExample {
3. public static void main(String[] args) {
4.
5. double myDouble = 3.4;
6. float myFloat = 3.4F;
7.
8. // 3.445*10^2
9. double myDoubleScientific = 3.445e2;
10.
11. System.out.println(myDouble);
12. System.out.println(myFloat);
13. System.out.println(myDoubleScientific);
14. }
15. }
Output:
1. 3.4
2. 3.4
3. 344.5
Character and String Literals
They contain Unicode (UTF-16) characters.
For char literals, single quotation is used. For example, 'a', '\u0111' etc.
For String literals, double quotation is used. For example, "programming", "Java 8"
Java also supports a few special escape sequences. For
example, \b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \" (double
quote), \' (single quote), and \\ (backslash).
1. class DoubleExample {
2. public static void main(String[] args) {
3.
4. char myChar = 'g';
5. char newLine = '\n';
6. String myString = "Java 8";
7.
8. System.out.println(myChar);
9. System.out.println(newLine);
10. System.out.println(myString);
11. }
12. }
Output: g
Java 8
Operators are special symbols (characters) that carry out operations on operands
(variables and values). For example, + is an operator that performs addition.
In Java variables article, you learned to declare variables and assign values to
variables. Now, you will learn to use operators to manipulate variables.
Assignment Operator
Assignment operators are used in Java to assign values to variables. For example,
int age;
age = 5;
The assignment operator assigns the value on its right to the variable on its left.
Here, 5 is assigned to the variable age using = operator.
There are other assignment operators too. However, to keep things simple, we will learn
other assignment operators later in this article.
5
5
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication etc.
Operator Meaning
- Subtraction Operator
* Multiplication Operator
/ Division Operator
% Remainder Operator
In above example, all operands used are variables. However, it's not necessary at all.
Operands used in arithmetic operators can be literals as well. For example,
Unary Operators
Unary operator performs operation on only one operand.
Operator Meaning
+ Unary plus (not necessary to use since numbers are positive without using it)
You can also use ++ and -- operator as both prefix and postfix in Java. The ++operator
increases value by 1 and -- operator decreases value by 1.
int myInt = 5;
++myInt // myInt becomes 6
myInt++ // myInt becomes 7
--myInt // myInt becomes 6
myInt-- // myInt becomes 5
Simple enough till now. However, there is a crucial difference while using increment and
decrement operator as prefix and postfix. Consider this example,
Equality and relational operators are used in decision making and loops (which will be
discussed later). For now, check this simple example.
Here, we have used > operator to check if number1 is greater than number2 or not.
Since, number2 is greater than number1, the expression number1 > number2 is evaluated
to false.
Hence, the block of code inside else is executed and the block of code inside ifis
skipped.
If you didn't understand the above code, don't worry. You will learn it in detail in Java
if...else article.
For now, just remember that the equality and relational operators compares two
operands and is evaluated to either true or false.
instanceof Operator
Here's an example of instanceof operator.
1. class instanceofOperator {
2. public static void main(String[] args) {
3.
4. String test = "asdf";
5. boolean result;
6.
7. result = test instanceof String;
8. System.out.println(result);
9. }
10. }
When you run the program, the output will be true. It's because test is the instance
of String class.
You will learn more about instanceof operator works once you understand Java
Classes and Objects.
Logical Operators
The logical operators || (conditional-OR) and && (conditional-AND) operates on boolean
expressions. Here's how they work.
Ternary Operator
The conditional operator or ternary operator ?: is shorthand for if-then-elsestatement.
The syntax of conditional operator is:
~ Bitwise Complement
^ Bitwise exclusive OR
| Bitwise inclusive OR
These operators are not commonly used. Visit this page to learn more about bitwise and
bit shift operators.
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x/5
^= x ^= 5 x=x^5
|= x |= 5 x=x|5
Now you know about Java operators, it's time to learn precedence of Java
operators; the order in which the operators in an expression are evaluated when two
operators share a common operand.
Java Output
You can simply
use System.out.println(), System.out.print() or System.out.printf() to send output
to standard output (screen).
System is a class and out is a public static field which accepts output data. Don't worry
if you don't understand it. Classes, public, and static will be discussed in later
chapters.
Let's take an example to output a line.
1. class AssignmentOperator {
2. public static void main(String[] args) {
3.
4. System.out.println("Java programming is interesting.");
5. }
6. }
When you run the program, the output will be:
Java programming is interesting.
import java.util.Scanner;
Here, input object of Scanner class is created. Then, the nextInt() method of
the Scanner class is used to get integer input from the user.
To get long, float, double and String input from the user, you can
use nextLong(), nextFloat(), nextDouble() and next() methods respectively.
You can use any of the following options based on the requirements.
Scanner class
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();
DataInputStream class
import java.io.DataInputStream;
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();
The readLine method from the DataInputStream class has been deprecated. To get String value,
you should use the previous solution with BufferedReader
Console class
import java.io.Console;
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
Apparently, this method does not work well in some IDEs.
1. System.in
2. InputStreamReader
3. BufferedReader
InputStreamReader and BufferedReader are classes in java.io package.
The data is received in the form of bytes from the keyboard by System.in which is an
InputStream object.
Then the InputStreamReader reads bytes and decodes them into characters.
Then finally BufferedReader object reads text from a character-input stream, buffering
characters so as to provide for the efficient reading of characters, arrays, and lines.
InputStreamReader inp = new InputStreamReader(system.in);
BufferedReader br = new BufferedReader(inp);
advantages of Using Scanner
Easy to use the Scanner class
Easy input of numbers (int, short, byte, float, long and double)
Exceptions are unchecked which is more convenient. It is up to the programmer to be civilized,
and specify or catch the exceptions.
Is able to read lines, white spaces, and regex-delimited tokens
Advantages of BufferedInputStream
BufferedInputStream is about reading in blocks of data rather than a single byte at a time
Can read chars, char arrays, and lines
Throws checked exceptions
Fast performance
Synchronized (you cannot share Scanner between threads)
Java Expressions
Expressions consist of variables, operators, literals and method calls that evaluates to a
single value. To learn about method calls, visit Java methods.
Let's take an example,
int score;
score = 90;
if (number1 == number2)
System.out.println("Number 1 is larger than number 2");
Java Statements
Statements are everything that make up a complete unit of execution. For example,
Here, 9*5 is an expression that returns 45, and int score = 9*5; is a statement.
Expressions are part of statements.
Expression statements
Some expressions can be made into statement by terminating the expression with a ;.
These are known as expression statements. For example:
number = 10;
++number;
Also, there are control flow statements that are used in decision making and looping in
Java. You will learn about control flow statements in later chapters.
Java Blocks
A block is a group of statements (zero or more) that is enclosed in curly braces { }. For
example,
1. class AssignmentOperator {
2. public static void main(String[] args) {
3.
4. String band = "Beatles";
5.
6. if (band == "Beatles") { // start of block
7. System.out.print("Hey ");
8. System.out.print("Jude!");
9. } // end of block
10. }
11. }
There are two statements System.out.print("Hey
"); and System.out.print("Jude!"); inside the mentioned block above.
A block may not have any statements. Consider these examples:
class AssignmentOperator {
public static void main(String[] args) {
} // end of block
}
}
class AssignmentOperator {
public static void main(String[] args) { // start of block
} // end of block
}