Вы находитесь на странице: 1из 27

JVM (Java Virtual Machine) is an abstract machine that enables your computer to run a

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

platform independent, Java is platform-independent.

.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

How Does the JVM Work?


As shown in the above architecture diagram, the JVM is divided into three
main subsystems:
1. Class Loader Subsystem
2. Runtime Data Area
3. Execution Engine
1. Class Loader Subsystem
Java's dynamic class loading functionality is handled by the class loader
subsystem. It loads, links. and initializes the class file when it refers to a
class for the first time at runtime, not compile time.
1.1 Loading
Classes will be loaded by this component. BootStrap class Loader,
Extension class Loader, and Application class Loader are the three class
loader which will help in achieving it.
1. Boot Strap ClassLoader – Responsible for loading classes from the
bootstrap classpath, nothing but rt.jar. Highest priority will be given
to this loader.
2. Extension ClassLoader – Responsible for loading classes which are
inside the ext folder (jre\lib).
3. Application ClassLoader –Responsible for loading Application Level
Classpath, path mentioned Environment Variable etc.
The above Class Loaders will follow Delegation Hierarchy Algorithm while
loading the class files.
1.2 Linking
1. Verify – Bytecode verifier will verify whether the generated bytecode
is proper or not if verification fails we will get the verification error.
2. Prepare – For all static variables memory will be allocated and
assigned with default values.
3. Resolve – All symbolic memory references are replaced with the
original references from Method Area.
1.3 Initialization
This is the final phase of Class Loading, here all static variables will be
assigned with the original values, and the static block will be executed.
2. Runtime Data Area
The Runtime Data Area is divided into 5 major components:
1. Method Area – All the class level data will be stored here, including
static variables. There is only one method area per JVM, and it is a
shared resource.
2. Heap Area – All the Objects and their corresponding instance
variables and arrays will be stored here. There is also one Heap Area
per JVM. Since the Method and Heap areas share memory for multiple
threads, the data stored is not thread-safe.
3. Stack Area – For every thread, a separate runtime stack will be
created. For every method call, one entry will be made in the stack
memory which is called as Stack Frame. All local variables will be
created in the stack memory. The stack area is thread-safe since it is
not a shared resource. The Stack Frame is divided into three
subentities:
1. Local Variable Array – Related to the method how many local
variables are involved and the corresponding values will be
stored here.
2. Operand stack – If any intermediate operation is required to
perform, operand stack acts as runtime workspace to perform
the operation.
3. Frame data – All symbols corresponding to the method is
stored here. In the case of any exception, the catch block
information will be maintained in the frame data.
4. PC Registers – Each thread will have separate PC Registers, to hold
the address of current executing instruction once the instruction is
executed the PC register will be updated with the next instruction.
5. Native Method stacks – Native Method Stack holds native method
information. For every thread, a separate native method stack will be
created.
3. Execution Engine
The bytecode which is assigned to the Runtime Data Area will be executed
by the Execution Engine. The Execution Engine reads the bytecode and
executes it piece by piece.
1. Interpreter – The interpreter interprets the bytecode faster, but
executes slowly. The disadvantage of the interpreter is that when one
method is called multiple times, every time a new interpretation is
required.
2. JIT Compiler – The JIT Compiler neutralizes the disadvantage of the
interpreter. The Execution Engine will be using the help of the
interpreter in converting byte code, but when it finds repeated code it
uses the JIT compiler, which compiles the entire bytecode and
changes it to native code. This native code will be used directly for
repeated method calls, which improve the performance of the system.
1. Intermediate Code generator – Produces intermediate code
2. Code Optimizer – Responsible for optimizing the intermediate
code generated above
3. Target Code Generator – Responsible for Generating Machine
Code or Native Code
4. Profiler – A special component, responsible for finding
hotspots, i.e. whether the method is called multiple times or
not.
3. Garbage Collector: Collects and removes unreferenced objects.
Garbage Collection can be triggered by calling System.gc(), but the
execution is not guaranteed. Garbage collection of the JVM collects the
objects that are created.
Java Native Interface (JNI): JNI will be interacting with the Native Method
Libraries and provides the Native Libraries required for the Execution
Engine.
Native Method Libraries: This is a collection of the Native Libraries which
is required for the Execution Engine.

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:
 /* ... */
 // ....

Traditional comment /* ... */


This is a multiline comment that can span over multiple lines. The Java compiler ignores
everything from /* to */. For example,
1. /* This is a multi-line comment.
2. * The problem prints "Hello, World!" to the standard output.
3. */
4. class HelloWorld {
5. public static void main(String[] args) {
6. {
7. System.out.println("Hello, World!");
8. }
9. }
10. }
Here, the comment is

/* This is a multi-line comment.


* The problem prints "Hello, World!" to the standard output.
*/

End of Line Comment //


The compiler ignores everything from // to the end of the line. For example,
1. // "Hello, World!" program
2.
3. class AssignmentOperator {
4. public static void main(String[] args) {
5. {
6. System.out.println("Hello, World!"); // prints "Hello, World!"
7. }
8. }
9. }
The program above contains two end of line comments:

// "Hello, World!" program

and

// prints "Hello, World!"

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)..

How to declare variables in Java?


Here's an example to declare a variable in Java.

int speedLimit = 80;

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 speedLimit = 80;


... .. ...
float speedLimit;

Rules for Naming Variables in Java


Java programming language has its own set of rules and conventions for naming
variables. Here's what you need to know:
 Variables in Java are case-sensitive.
 A variable's name is a sequence of Unicode letters and digits. It can begin with a letter, $ or _.
However, it's convention to begin a variable name with a letter. Also, variable name cannot use
whitespace in Java.

 When creating variables, choose a name that makes sense. For


example, score, number, level makes more sense than variable name such as s, n, and l.
 If you choose one word variable name, use all lowercase letters. For example, it's better to
use speed rather than SPEED, or sPEED.
 If you choose variable name having more than one word, use all lowercase letters for the first
word and capitalize the first letter of each subsequent word. For example, speedLimit.

There are 4 types of variables in Java programming language:


 Instance Variables (Non-Static Fields)
 Class Variables (Static Fields)
 Local Variables
 Parameters

Java Primitive Data Types


As mentioned above, Java is a statically-typed language. This means that, all variables
must be declared before they can be used.

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

You get the output Q because the Unicode value of Q is '\u0051'.


Here is another example:
1. class CharExample {
2. public static void main(String[] args) {
3.
4. char letter1 = '9';
5. System.out.println(letter1);
6.
7. char letter2 = 65;
8. System.out.println(letter2);
9.
10. }
11. }

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:

myString = "Programming is awesome";

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.

boolean flag = false;

 boolean - is data type.


 flag - is variable
 false - is literal.
A Literal is the source code representation of a fixed value.
Values like 1.5, 4, true, '\u0050' that appears directly in a program without requiring
computation are literals.
In the above example, flag is a variable. Since, it's a boolean type variable, it may store
either false or true. For compiler to understand it, it requires computation. However,
literals like -5, 'a', true represents fixed value.
Integer Literals
 Integer literals are used to initialize variables of integer data types byte, short, int and long.
 If an integer literal ends with l or L, it's of type long. Tip: it is better to use L instead of l.

 // Error! literal 42332200000 of type int is out of range


 long myVariable1 = 42332200000;

 // 42332200000L is of type long, and it's not out of range
 long myVariable2 = 42332200000L;

 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

int binNumber = 0b10010;

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.

Example 1: Assignment Operator


1. class AssignmentOperator {
2. public static void main(String[] args) {
3.
4. int number1, number2;
5.
6. // Assigning 5 to number1
7. number1 = 5;
8. System.out.println(number1);
9.
10. // Assigning value of variable number2 to number1
11. number2 = number1;
12. System.out.println(number2);
13. }
14. }
When you run the program, the output will be:

5
5

Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication etc.

Operator Meaning

+ Addition (also used for string concatenation)

- Subtraction Operator

* Multiplication Operator

/ Division Operator

% Remainder Operator

Java Arithmetic Operators

Example 2: Arithmetic Operator


1. class ArithmeticOperator {
2. public static void main(String[] args) {
3.
4. double number1 = 12.5, number2 = 3.5, result;
5.
6. // Using addition operator
7. result = number1 + number2;
8. System.out.println("number1 + number2 = " + result);
9.
10. // Using subtraction operator
11. result = number1 - number2;
12. System.out.println("number1 - number2 = " + result);
13.
14. // Using multiplication operator
15. result = number1 * number2;
16. System.out.println("number1 * number2 = " + result);
17.
18. // Using division operator
19. result = number1 / number2;
20. System.out.println("number1 / number2 = " + result);
21.
22. // Using remainder operator
23. result = number1 % number2;
24. System.out.println("number1 % number2 = " + result);
25. }
26. }
When you run the program, the output will be:
number1 + number2 = 16.0
number1 - number2 = 9.0
number1 * number2 = 43.75
number1 / number2 = 3.5714285714285716
number1 % number2 = 2.0

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,

result = number1 + 5.2;


result = 2.3 + 4.5;
number2 = number1 -2.9;

The + operator can also be used to concatenate two or more strings.

Example 3: Arithmetic Operator


1. class ArithmeticOperator {
2. public static void main(String[] args) {
3.
4. String start, middle, end, result;
5.
6. start = "Talk is cheap. ";
7. middle = "Show me the code. ";
8. end = "- Linus Torvalds";
9.
10. result = start + middle + end;
11. System.out.println(result);
12. }
13. }
When you run the program, the output will be:
Talk is cheap. Show me the code. - Linus Torvalds

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)

- Unary minus; inverts the sign of an expression

++ Increment operator; increments value by 1

-- decrement operator; decrements value by 1

! Logical complement operator; inverts the value of a boolean

Example 4: Unary Operator


1. class UnaryOperator {
2. public static void main(String[] args) {
3.
4. double number = 5.2, resultNumber;
5. boolean flag = false;
6.
7. System.out.println("+number = " + +number);
8. // number is equal to 5.2 here.
9.
10. System.out.println("-number = " + -number);
11. // number is equal to 5.2 here.
12.
13. // ++number is equivalent to number = number + 1
14. System.out.println("number = " + ++number);
15. // number is equal to 6.2 here.
16.
17. // -- number is equivalent to number = number - 1
18. System.out.println("number = " + --number);
19. // number is equal to 5.2 here.
20.
21. System.out.println("!flag = " + !flag);
22. // flag is still false.
23. }
24. }
When you run the program, the output will be:
+number = 5.2
-number = -5.2
number = 6.2
number = 5.2
!flag = true

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,

Example 5: Unary Operator


1. class UnaryOperator {
2. public static void main(String[] args) {
3.
4. double number = 5.2;
5.
6. System.out.println(number++);
7. System.out.println(number);
8.
9. System.out.println(++number);
10. System.out.println(number);
11. }
12. }
When you run the program, the output will be:
5.2
6.2
7.2
7.2

When System.out.println(number++); statement is executed, the original value is


evaluated first. The number is increased only after that. That's why you are getting 5.2 as
an output. Then, when System.out.println(number); is executed, the increased value
6.2 is displayed.
However, when System.out.println(++number); is executed, number is increased by 1
first before it's printed on the screen.
Similar is the case for decrement -- operator.

Equality and Relational Operators


The equality and relational operators determines the relationship between two
operands. It checks if an operand is greater than, less than, equal to, not equal to and
so on. Depending on the relationship, it results to either true or false.

Operator Description Example

== equal to 5 == 3 is evaluated to false

!= not equal to 5 != 3 is evaluated to true

> greater than 5 > 3 is evaluated to true

< less than 5 < 3 is evaluated to false

>= greater than or equal to 5 >= 5 is evaluated to true

<= less then or equal to 5 <= 5 is evaluated to true

Java Equality and Relational Operators

Equality and relational operators are used in decision making and loops (which will be
discussed later). For now, check this simple example.

Example 6: Equality and Relational Operators


1. class RelationalOperator {
2. public static void main(String[] args) {
3.
4. int number1 = 5, number2 = 6;
5.
6. if (number1 > number2)
7. {
8. System.out.println("number1 is greater than number2.");
9. }
10. else
11. {
12. System.out.println("number2 is greater than number1.");
13. }
14. }
15. }
When you run the program, the output will be:
number2 is greater than number1.

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.

In addition to relational operators, there is also a type comparison


operator instanceof which compares an object to a specified type. For example,

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.

Operator Description Example

conditional-OR; true if either of the boolean false || true is evaluated


|| expression is true to true

conditional-AND; true if all boolean expressions false && true is evaluated


&& are true to false

Java Logical Operators

Example 8: Logical Operators


1. class LogicalOperator {
2. public static void main(String[] args) {
3.
4. int number1 = 1, number2 = 2, number3 = 9;
5. boolean result;
6.
7. // At least one expression needs to be true for result to be true
8. result = (number1 > number2) || (number3 > number1);
9. // result will be true because (number1 > number2) is true
10. System.out.println(result);
11.
12. // All expression must be true from result to be true
13. result = (number1 > number2) && (number3 > number1);
14. // result will be false because (number3 > number1) is false
15. System.out.println(result);
16. }
17. }
When you run the program, the output will be:
true
false

Logical operators are used in decision making and looping.

Ternary Operator
The conditional operator or ternary operator ?: is shorthand for if-then-elsestatement.
The syntax of conditional operator is:

variable = Expression ? expression1 : expression2

Here's how it works.


 If the Expression is true, expression1 is assigned to variable.
 If the Expression is false, expression2 is assigned to variable.

Example 9: Ternary Operator


1. class ConditionalOperator {
2. public static void main(String[] args) {
3.
4. int februaryDays = 29;
5. String result;
6.
7. result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
8. System.out.println(result);
9. }
10. }
When you run the program, the output will be:
Leap year

To learn more, visit Java ternary operator.

Bitwise and Bit Shift Operators


To perform bitwise and bit shift operators in Java, these operators are used.
Operator Description

~ Bitwise Complement

<< Left Shift

>> Right Shift

>>> Unsigned Right Shift

& Bitwise AND

^ Bitwise exclusive OR

| Bitwise inclusive OR

Java Bitwise and Bit Shift Operators

These operators are not commonly used. Visit this page to learn more about bitwise and
bit shift operators.

More Assignment Operators


We have only discussed about one assignment operator = in the beginning of the
article. Except this operator, there are quite a few assignment operators that helps us to
write cleaner code.

Operator Example Equivalent to

+= 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

&= x &= 5 x=x&5


Operator Example Equivalent to

^= x ^= 5 x=x^5

|= x |= 5 x=x|5

Java Assignment Operators

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.

Here, println is a method that displays the string inside quotes.

What's the difference between println(), print() and printf()?


 print() - prints string inside the quotes.
 println() - prints string inside the quotes similar like print() method. Then the cursor moves
to the beginning of the next line.
 printf() - it provides string formatting (similar to printf in C/C++ programming).

Example 2: print() and println()


1. class Output {
2. public static void main(String[] args) {
3.
4. System.out.println("1. println ");
5. System.out.println("2. println ");
6.
7. System.out.print("1. print ");
8. System.out.print("2. print");
9. }
10. }
When you run the program, the output will be:
1. println
2. println
1. print 2. print

Visit this page to learn about Java printf().

To display integers, variables and so on, do not use quotation marks.


Example 3: Printing Variables and Literals
1. class Variables {
2. public static void main(String[] args) {
3.
4. Double number = -10.6;
5.
6. System.out.println(5);
7. System.out.println(number);
8. }
9. }
When you run the program, the output will be:
5
-10.6

You can use + operator to concatenate strings and print it.


Example 4: Print Concatenated Strings
1. class PrintVariables {
2. public static void main(String[] args) {
3.
4. Double number = -10.6;
5.
6. System.out.println("I am " + "awesome.");
7. System.out.println("Number = " + number);
8. }
9. }
When you run the program, the output will be:
I am awesome.
Number = -10.6

Consider: System.out.println("I am " + "awesome.");


Strings "I am " and "awesome." is concatenated first before it's printed on the screen.
Consider: System.out.println("Number = " + number);
The value of variable number is evaluated first. It's value is in double which is converted
to string by the compiler. Then, the strings are concatenated and printed on the screen.
Java Input
There are several ways to get input from the user in Java. You will learn to get input by
using Scanner object in this article.
For that, you need to import Scanner class using:

import java.util.Scanner;

Learn more about Java import


Then, we will create an object of Scanner class which will be used to get input from the
user.

Scanner input = new Scanner(System.in);


int number = input.nextInt();

Example 5: Get Integer Input From the User


1. import java.util.Scanner;
2.
3. class Input {
4. public static void main(String[] args) {
5.
6. Scanner input = new Scanner(System.in);
7.
8. System.out.print("Enter an integer: ");
9. int number = input.nextInt();
10. System.out.println("You entered " + number);
11. }
12. }
When you run the program, the output will be:
Enter an integer: 23
You entered 23

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.

Example 6: Get float, double and String Input


1. import java.util.Scanner;
2.
3. class Input {
4. public static void main(String[] args) {
5.
6. Scanner input = new Scanner(System.in);
7.
8. // Getting float input
9. System.out.print("Enter float: ");
10. float myFloat = input.nextFloat();
11. System.out.println("Float entered = " + myFloat);
12.
13. // Getting double input
14. System.out.print("Enter double: ");
15. double myDouble = input.nextDouble();
16. System.out.println("Double entered = " + myDouble);
17.
18. // Getting String input
19. System.out.print("Enter text: ");
20. String myString = input.next();
21. System.out.println("Text entered = " + myString);
22. }
23. }
When you run the program, the output will be:
Enter float: 2.343
Float entered = 2.343
Enter double: -23.4
Double entered = -23.4
Enter text: Hey!
Text entered = Hey!

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();

BufferedReader and InputStreamReader classes


import java.io.BufferedReader;
import java.io.InputStreamReader;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int i = Integer.parseInt(s);

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.

How data is accepted from keyboard ?


We need three objects,

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;

Here, score = 90 is an expression that returns int.


Double a = 2.2, b = 3.4, result;
result = a + b - 3.4;

Here, a + b - 3.4 is an expression.

if (number1 == number2)
System.out.println("Number 1 is larger than number 2");

Here, number1 == number2 is an expression that returns Boolean. Similarly, "Number 1 is


larger than number 2" is a string expression.

Java Statements
Statements are everything that make up a complete unit of execution. For example,

int score = 9*5;

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;

Here, number = 10 is an expression where as number = 10; is a statement that compiler


can execute.

++number;

Here, ++number is an expression where as ++number; is a statement.


Declaration Statements
Declaration statements declares variables. For example,

Double tax = 9.5;

The statement above declares a variable tax which is initialized to 9.5.

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) {

if (10 > 5) { // start of block

} // end of block
}
}
class AssignmentOperator {
public static void main(String[] args) { // start of block

} // end of block
}

Вам также может понравиться