Java Hello World Program
Java Hello World Program
1
[Pick the date] [ Type the document title ]
Note: You can use our online Java compiler to run Java programs.
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Output
Hello, World!
2
[Pick the date] [ Type the document title ]
In Java, any line starting with // is a comment. Comments are intended for
users reading the code to understand the intent and functionality of the
program. It is completely ignored by the Java compiler (an application that
translates Java program to Java bytecode that computer can execute). To
learn more, visit Java comments.
3. class HelloWorld {
4. ... .. ...
For now, just remember that every Java application has a class definition,
and the name of the class should match the filename in Java.
5. public static void main(String[] args) { ... }
This is the main method. Every application in Java must contain the main
method. The Java compiler starts executing the code from the main method.
3
[Pick the date] [ Type the document title ]
How does it work? Good question. However, we will not discuss it in this
article. After all, it's a basic program to introduce Java programming
language to a newbie.
We will learn the meaning of public, static, void, and how methods work? in
later chapters.
For now, just remember that the main function is the entry point of your
Java application, and it's mandatory in a Java program. The signature of the
main method in Java is:
7. ... .. ...
8. System.out.println("Hello, World!");
The code above is a print statement. It prints the text Hello, World! to
standard output (your screen). The text inside the quotation marks is
called String in Java.
Notice the print statement is inside the main function, which is inside the
class definition.
4
[Pick the date] [ Type the document title ]
Every valid Java Application must have a class definition that matches the
filename (class name and file name should be same).
The compiler executes the codes starting from the main function.
Don't worry if you don't understand the meaning of class, static, methods,
and so on for now. We will discuss it in detail in later chapters.
5
[Pick the date] [ Type the document title ]
What is JVM?
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).
If you are interested in learning about JVM Architecture, visit The JVM
Architecture Explained.
What is JRE?
6
[Pick the date] [ Type the document title ]
If you need to run Java programs, but not develop them, JRE is what you
need. You can download JRE from Java SE Runtime Environment 8
Downloads page.
What is JDK?
7
[Pick the date] [ Type the document title ]
8
[Pick the date] [ Type the document title ]
Java Variables
To indicate the storage area, each variable should be given a unique name
(identifier). Learn more about Java identifiers.
Create Variables in Java
You can declare variables and assign variables separately. For example,
int speedLimit;
speedLimit = 80;
9
[Pick the date] [ Type the document title ]
... .. ...
speedLimit = 90;
Don't worry about it for now. Just remember that we can't do something like
this:
... .. ...
float speedLimit;
To learn more, visit: Can I change declaration type for a variable in Java?
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:
Java is case sensitive. Hence, age and AGE are two different variables. For
example,
10
[Pick the date] [ Type the document title ]
Here, is we need to use variable names having more than one word, use all
lowercase letters for the first word and capitalize the first letter of each
subsequent word. For example, myAge.
When creating variables, choose a name that makes sense. For
example, score, number, level makes more sense than variable names
such as s, n, and l.
If you choose one-word variable names, use all lowercase letters. For
example, it's better to use speed rather than SPEED, or sPEED.
11
[Pick the date] [ Type the document title ]
Local Variables
Parameters
If you are interested to learn more about it now, visit Java Variable Types.
Java literals
Literals are data used for representing fixed values. They can be used directly
in the code. For example,
int a = 1;
float b = 2.5;
char c = 'F';
1. Boolean Literals
In Java, boolean literals are used to initialize boolean data types. They can
store two values: true and false. For example,
12
[Pick the date] [ Type the document title ]
2. Integer Literals
1. binary (base 2)
3. octal (base 8)
For example:
// binary
int binaryNumber = 0b10010;
// octal
int octalNumber = 027;
// decimal
int decNumber = 34;
// hexadecimal
int hexNumber = 0x2F; // 0x represents hexadecimal
// binary
int binNumber = 0b10010; // 0b represents binary
In Java, binary starts with 0b, octal starts with 0, and hexadecimal starts
with 0x.
13
[Pick the date] [ Type the document title ]
3. Floating-point Literals
class Main {
public static void main(String[] args) {
// 3.445*10^2
double myDoubleScientific = 3.445e2;
Note: The floating-point literals are used to initialize float and double type
variables.
4. Character Literals
Character literals are unicode character enclosed inside single quotes. For
example,
14
[Pick the date] [ Type the document title ]
As the name suggests, data types specify the type of data that can be stored
inside variables in Java.
Java is a statically-typed language. This means that all variables must be
declared before they can be used.
int speed;
Here, speed is a variable, and the data type of the variable is int.
15
[Pick the date] [ Type the document title ]
The int data type determines that the speed variable can only contain
integers.
There are 8 data types predefined in Java, known as primitive data types.
Note: In addition to primitive data types, there are also referenced types
(object type).
1. boolean type
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: Java boolean data type
class Main {
public static void main(String[] args) {
The byte data type can have values from -128 to 127 (8-bit signed two's
complement integer).
If it's certain that the value of a variable will be within -128 to 127, then it is
used instead of int to save memory.
Default value: 0
Example 2: Java byte data type
class Main {
public static void main(String[] args) {
16
[Pick the date] [ Type the document title ]
byte range;
range = 124;
System.out.println(range); // prints 124
}
}
3. Short type
The short data type in Java can have values from -32768 to 32767 (16-bit
signed two's complement integer).
If it's certain that the value of a variable will be within -32768 and 32767,
then it is used instead of other integer data types (int, long).
Default value: 0
short temperature;
temperature = -200;
System.out.println(temperature); // prints -200
}
}
4. int type
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 an unsigned 32-bit integer. This
will have a minimum value of 0 and a maximum value of 2 32-1. To learn more,
visit How to use the unsigned integer in java 8?
Default value: 0
17
[Pick the date] [ Type the document title ]
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 an unsigned 64-bit integer with a
minimum value of 0 and a maximum value of 264-1.
Default value: 0
18
[Pick the date] [ Type the document title ]
19
[Pick the date] [ Type the document title ]
8. char type
The minimum value of the char data type is '\u0000' (0) and the maximum
value of the is '\uffff'.
Default value: '\u0000'
Example 8: Java char data type
class Main {
public static void main(String[] args) {
class Main {
public static void main(String[] args) {
}
}
Here, we have assigned 9 as a character (specified by single quotes) to
the letter1 variable. However, the letter2 variable is assigned 65 as an integer
number (no single quotes).
20
[Pick the date] [ Type the document title ]
Java also provides support for character strings via java.lang.String class.
Strings in Java are not primitive types. Instead, they are objects. For example,
Here, myString is an object of the String class. To learn more, visit Java
Strings.
Java Operators
Operators are symbols that perform operations on variables and values. For
example, + is an operator used for addition, while * is also an operator used
for multiplication.
Operators in Java can be classified into 5 types:
1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Logical Operators
5. Unary Operators
6. Bitwise Operators
21
[Pick the date] [ Type the document title ]
a + b;
Here, the + operator is used to add two variables a and b. Similarly, there
are various other arithmetic operators in Java.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
// declare variables
int a = 12, b = 5;
// addition operator
System.out.println("a + b = " + (a + b));
// subtraction operator
System.out.println("a - b = " + (a - b));
// multiplication operator
22
[Pick the date] [ Type the document title ]
// modulo operator
System.out.println("a % b = " + (a % b));
}
}
Run Code
Output
a + b = 17
a-b=7
a * b = 60
a/b=2
a%b=2
If we use the division operator with two integers, then the resulting quotient
will also be an integer. And, if one of the operands is a floating-point
number, we will get the result will also be in floating-point.
In Java,
(9 / 2) is 4
(9.0 / 2) is 4.5
(9 / 2.0) is 4.5
(9.0 / 2.0) is 4.5
% Modulo Operator
23
[Pick the date] [ Type the document title ]
int age;
age = 5;
Here, = is the assignment operator. It assigns the value on its right to the
variable on its left. That is, 5 is assigned to the variable age.
Let's see some more assignment operators available in Java.
= a = b; a = b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;
24
[Pick the date] [ Type the document title ]
// create variables
int a = 4;
int var;
var using =: 4
var using +=: 8
var using *=: 32
Here, < operator is the relational operator. It checks if a is less than b or not.
25
[Pick the date] [ Type the document title ]
// create variables
int a = 7, b = 11;
// value of a and b
System.out.println("a is " + a + " and b is " + b);
// == operator
System.out.println(a == b); // false
// != operator
System.out.println(a != b); // true
// > operator
System.out.println(a > b); // false
// < operator
26
[Pick the date] [ Type the document title ]
// >= operator
System.out.println(a >= b); // false
// <= operator
System.out.println(a <= b); // true
}
}
27
[Pick the date] [ Type the document title ]
// && operator
System.out.println((5 > 3) && (8 > 5)); // true
System.out.println((5 > 3) && (8 < 5)); // false
// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false
// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}
Run Code
Working of Program
(5 > 3) && (8 > 5) returns true because both (5 > 3) and (8 > 5) are true.
(5 > 3) && (8 < 5) returns false because the expression (8 < 5) is false.
(5 < 3) || (8 > 5) returns true because the expression (8 > 5) is true.
(5 > 3) || (8 < 5) returns true because the expression (5 > 3) is true.
(5 < 3) || (8 < 5) returns false because both (5 < 3) and (8 < 5) are false.
!(5 == 3) returns true because 5 == 3 is false.
!(5 > 3) returns false because 5 > 3 is true.
28
[Pick the date] [ Type the document title ]
Unary operators are used with only one operand. For example, ++ is a unary
operator that increases the value of a variable by 1. That is, ++5 will return 6.
Different types of unary operators are:
Operator Meaning
int num = 5;
// increase num by 1
++num;
Here, the value of num gets increased to 6 from its initial value of 5.
29
[Pick the date] [ Type the document title ]
// declare variables
int a = 12, b = 12;
int result1, result2;
// original value
System.out.println("Value of a: " + a);
// increment operator
result1 = ++a;
System.out.println("After increment: " + result1);
// decrement operator
result2 = --b;
System.out.println("After decrement: " + result2);
}
}
Run Code
Output
Value of a: 12
After increment: 13
Value of b: 12
After decrement: 11
In the above program, we have used the ++ and -- operator as prefixes (++a,
--b). We can also use these operators as postfix (a++, b++).
There is a slight difference when these operators are used as prefix versus
when they are used as a postfix.
30
[Pick the date] [ Type the document title ]
a=5
++a; // a becomes 6
a++; // a becomes 7
--a; // a becomes 6
a--; // a becomes 5
If you use the ++ operator as a prefix like: ++var, the value of var is
incremented by 1; then it returns the value.
If you use the ++ operator as a postfix like: var++, the original value of var is
returned first; then var is incremented by 1.
Let's see the use of ++ as prefixes and postfixes in C, C++, Java and
JavaScript.
31
[Pick the date] [ Type the document title ]
Example 1: C Programming
#include <stdio.h>
int main() {
int var1 = 5, var2 = 5;
// 5 is displayed
// Then, var1 is increased to 6.
printf("%d\n", var1++);
// var2 is increased to 6
// Then, it is displayed.
printf("%d\n", ++var2);
return 0;
}
Example 2: C++
#include <iostream>
int main() {
int var1 = 5, var2 = 5;
// 5 is displayed
// Then, var1 is increased to 6.
cout << var1++ << endl;
// var2 is increased to 6
// Then, it is displayed.
cout << ++var2 << endl;
return 0;
32
[Pick the date] [ Type the document title ]
class Operator {
public static void main(String[] args) {
// var2 is increased to 6
// Then, var2 is displayed
System.out.println(++var2);
}
}
Example 4: JavaScript
// 5 is displayed
// Then, var1 is increased to 6
console.log(var1++)
// var2 is increased to 6
// Then, var2 is displayed
console.log(++var2)
33
[Pick the date] [ Type the document title ]
Output
5
6
Operator Description
~ Bitwise Complement
^ Bitwise exclusive OR
34
[Pick the date] [ Type the document title ]
These operators are not generally used in Java. To learn more, visit Java
Bitwise and Bit Shift Operators.
Operator Description
| Bitwise OR
^ Bitwise XOR
~ Bitwise Complement
35
[Pick the date] [ Type the document title ]
a b a|b
0 0 0
0 1 1
1 0 1
1 1 1
The above table is known as the "Truth Table" for the bitwise OR operator.
36
[Pick the date] [ Type the document title ]
Example 1: Bitwise OR
class Main {
public static void main(String[] args) {
The bitwise AND & operator returns 1 if and only if both the operands are 1.
Otherwise, it returns 0.
The following table demonstrates the working of the bitwise AND operator.
Let a and b be two operands that can only take binary values i.e. 1 and 0.
a b a&b
0 0 0
0 1 0
1 0 0
1 1 1
37
[Pick the date] [ Type the document title ]
Let's take a look at the bitwise AND operation of two integers 12 and 25.
The bitwise XOR ^ operator returns 1 if and only if one of the operands is 1.
However, if both the operands are 0 or if both are 1, then the result is 0.
The following truth table demonstrates the working of the bitwise XOR
operator. Let a and b be two operands that can only take binary values i.e. 1
or 0.
38
[Pick the date] [ Type the document title ]
a b a^b
0 0 0
0 1 1
1 0 1
1 1 0
Let's look at the bitwise XOR operation of two integers 12 and 25.
39
[Pick the date] [ Type the document title ]
The bitwise complement operator is a unary operator (works with only one
operand). It is denoted by ~.
It changes binary digits 1 to 0 and 0 to 1.
In the above example, we get that the bitwise complement of 00100011 (35)
is 11011100. Here, if we convert the result into decimal we get 220.
However, it is important to note that we cannot directly convert the result
into decimal and get the desired output. This is because the binary
result 11011100 is also equivalent to -36.
40
[Pick the date] [ Type the document title ]
2's complement:
11011011
+ 1
_________
11011100
Here, we can see the 2's complement of 36 (i.e. -36) is 11011100. This value is
equivalent to the bitwise complement of 35.
Hence, we can say that the bitwise complement of 35 is -(35 + 1) = -36.
Example 4: Bitwise Complement
class Main {
public static void main(String[] args) {
// bitwise complement of 35
result = ~number;
System.out.println(result); // prints -36
41
[Pick the date] [ Type the document title ]
}
}
Java Shift Operators
The left shift operator shifts all bits towards the left by a certain number of
specified bits. It is denoted by <<.
J
ava 1 bit Left Shift Operator
As we can see from the image above, we have a 4-digit number. When we
perform a 1 bit left shift operation on it, each individual bit is shifted to the
left by 1 bit.
As a result, the left-most bit (most-significant) is discarded and the right-
most position (least-significant) remains vacant. This vacancy is filled
with 0s.
42
[Pick the date] [ Type the document title ]
class Main {
public static void main(String[] args) {
int number = 2;
The signed right shift operator shifts all bits towards the right by a certain
number of specified bits. It is denoted by >>.
When we shift any number to the right, the least significant bits (rightmost)
are discarded and the most significant position (leftmost) is filled with the
sign bit. For example,
// right shift of 8
8 = 1000 (In Binary)
Here, we are performing the right shift of 8 (i.e. sign is positive). Hence,
there no sign bit. So the leftmost bits are filled with 0 (represents positive
sign).
// right shift of -8
8 = 1000 (In Binary)
43
[Pick the date] [ Type the document title ]
2's complement:
0111
+1
_______
1000
Signed bit = 1
Here, we have used the signed bit 1 to fill the leftmost bits.
Example 6: Signed Right Shift Operator
class Main {
public static void main(String[] args) {
int number1 = 8;
int number2 = -8;
44
[Pick the date] [ Type the document title ]
8 >>> 2 = 0010
-8 >>> 2 = 0010
int number1 = 8;
int number2 = -8;
As we can see the signed and unsigned right shift operator returns different
results for negative bits.
Other operators
45
[Pick the date] [ Type the document title ]
Output
Here, str is an instance of the String class. Hence, the instanceof operator
returns true. To learn more, visit Java instanceof.
Java Ternary Operator
class Java {
public static void main(String[] args) {
46
[Pick the date] [ Type the document title ]
// ternary operator
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
}
}
Run Code
Output
Leap year
In the above example, we have used the ternary operator to check if the year
is a leap year or not. To learn more, visit the Java ternary operator.
Now that you know about Java operators, it's time to know about the order
in which operators are evaluated. To learn more, visit Java Operator
Precedence.
47
[Pick the date] [ Type the document title ]
Java Output
System.out.println(); or
System.out.print(); or
System.out.printf();
Here,
System is a class
out is a public static field: it accepts output data.
Don't worry if you don't understand it. We will discuss class, public,
and static in later chapters.
Let's take an example to output a line.
class AssignmentOperator {
public static void main(String[] args) {
Output:
Output:
1. println
2. println
1. print 2. print
49
[Pick the date] [ Type the document title ]
System.out.println(5);
System.out.println(number);
}
}
Run Code
5
-10.6
Here, you can see that we have not used the quotation marks. It is because to
display integers, variables and so on, we don't use quotation marks.
Output:
I am awesome.
Number = -10.6
Here, we have used the + operator to concatenate (join) the two strings: "I
am " and "awesome.".
And also, the line,
Here, first the value of variable number is evaluated. Then, the value is
concatenated to the string: "Number = ".
Java Input
51
[Pick the date] [ Type the document title ]
Java provides different ways to get input from the user. However, in this
tutorial, you will learn to get input from user using the object
of Scanner class.
In order to use the object of Scanner, we need to
import java.util.Scanner package.
import java.util.Scanner;
To learn more about importing packages in Java, visit Java Import Packages.
Then, we need to create an object of the Scanner class. We can use the
object to take input from the user.
class Input {
public static void main(String[] args) {
52
[Pick the date] [ Type the document title ]
Output:
Enter an integer: 23
You entered 23
class Input {
public static void main(String[] args) {
53
[Pick the date] [ Type the document title ]
Output:
As mentioned, there are other several ways to get input from the user. To
learn more about Scanner, visit Java Scanner.
54
[Pick the date] [ Type the document title ]
Java Expressions
int score;
score = 90;
if (number1 == number2)
System.out.println("Number 1 is larger than number 2");
Java Statements
55
[Pick the date] [ Type the document title ]
Expression statements
// expression
number = 10
// statement
number = 10;
// expression
++number
// statement
++number;
56
[Pick the date] [ Type the document title ]
Declaration Statements
In Java, declaration statements are used for declaring variables. For example,
Note: 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
57
[Pick the date] [ Type the document title ]
} // end of block
}
}
Run Code
Output:
Hey Jude!
System.out.print("Hey ");
System.out.print("Jude!");
However, a block may not have any statements. Consider the following
examples,
class Main {
public static void main(String[] args) {
} // end of block
}
}
Run Code
This is a valid Java program. Here, we have a block if {...}. However, there is
no any statement inside this block.
class AssignmentOperator {
public static void main(String[] args) { // start of block
} // end of block
}
Run Code
58
[Pick the date] [ Type the document title ]
Here, we have block public static void main() {...}. However, similar to the
above example, this block does not have any statement.
Java Comments
single-line comment
59
[Pick the date] [ Type the document title ]
multi-line comment
Single-line Comment
A single-line comment starts and ends in the same line. To write a single-line
comment, we can use the // symbol. For example,
// "Hello, World!" program example
class Main {
public static void main(String[] args) {
// prints "Hello, World!"
System.out.println("Hello, World!");
}
}
Run Code
Output:
Hello, World!
60
[Pick the date] [ Type the document title ]
Multi-line Comment
When we want to write comments in multiple lines, we can use the multi-
line comment. To write multi-line comments, we can use the /*....*/ symbol.
For example,
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Run Code
Output:
Hello, World!
One thing you should always consider that comments shouldn't be the
substitute for a way to explain poorly written code in English. You should
always write well structured and self explaining code. And, then use
comments.
Note: In most cases, always use comments to explain 'why' rather than 'how'
and you are good to go.
62