0% found this document useful (0 votes)
59 views

Java Hello World Program

The document discusses the Java 'Hello World' program and how it works. It explains that every Java application requires a class with a main method that is the starting point. It then shows the code for a simple Java program that prints 'Hello World' along with descriptions of what each part of the code is doing.

Uploaded by

degadisa104
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views

Java Hello World Program

The document discusses the Java 'Hello World' program and how it works. It explains that every Java application requires a class with a main method that is the starting point. It then shows the code for a simple Java program that prints 'Hello World' along with descriptions of what each part of the code is doing.

Uploaded by

degadisa104
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 62

[Pick the date] [ Type the document title ]

1
[Pick the date] [ Type the document title ]

Java Hello World Program

A "Hello, World!" is a simple program that outputs Hello, World! on the


screen. Since it's a very simple program, it's often used to introduce a new
programming language to a newbie.
Let's explore how Java "Hello, World!" program works.

Note: You can use our online Java compiler to run Java programs.

Java "Hello, World!" Program

// Your First Program

class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Output

Hello, World!

2
[Pick the date] [ Type the document title ]

How Java "Hello, World!" Program Works?

1. // Your First Program

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.

2. class HelloWorld { ... }

In Java, every application begins with a class definition. In the


program, HelloWorld is the name of the class, and the class definition is:

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:

6. public static void main(String[] args) {

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 ]

Things to take away

 Every valid Java Application must have a class definition that matches the
filename (class name and file name should be same).

 The main method must be inside the class definition.

 The compiler executes the codes starting from the main function.

This is a valid Java program that does nothing.

public class HelloWorld {


public static void main(String[] args) {
// Write your code here
}
}

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 ]

Java JDK, JRE and JVM

What is JVM?

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.

Working of Java Program

If you are interested in learning about JVM Architecture, visit The JVM
Architecture Explained.
What is JRE?

JRE (Java Runtime Environment) is a software package that provides Java


class libraries, Java Virtual Machine (JVM), and other components that are
required to run Java applications.

6
[Pick the date] [ Type the document title ]

JRE is the superset of JVM.

Java Runtime Environment

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?

JDK (Java Development Kit) is a software development kit required to


develop applications in Java. When you download JDK, JRE is also
downloaded with it.

In addition to JRE, JDK also contains a number of development tools


(compilers, JavaDoc, Java Debugger, etc).

Java Development Kit

If you want to develop Java applications, download JDK.

7
[Pick the date] [ Type the document title ]

Relationship between JVM, JRE, and JDK.

Relationship between JVM, JRE, and JDK

Java Variables and Literals

8
[Pick the date] [ Type the document title ]

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). Learn more about Java identifiers.
Create Variables in Java

Here's how we create a variable in Java,

int speedLimit = 80;

Here, speedLimit is a variable of int data type and we have assigned


value 80 to it.
The int data type suggests that the variable can only hold integers. To learn
more, visit Java data types.
In the example, we have assigned value to the variable during declaration.
However, it's not mandatory.

You can declare variables and assign variables separately. For example,

int speedLimit;
speedLimit = 80;

Note: Java is a statically-typed language. It means that all variables must be


declared before they can be used.

Change values of variables

9
[Pick the date] [ Type the document title ]

The value of a variable can be changed in the program, hence the


name variable. For example,

int speedLimit = 80;

... .. ...

speedLimit = 90;

Here, initially, the value of speedLimit is 80. Later, we changed it to 90.


However, we cannot change the data type of a variable in Java within the
same scope.

What is the variable scope?

Don't worry about it for now. Just remember that we can't do something like
this:

int speedLimit = 80;

... .. ...

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 ]

 int age = 24;


 int AGE = 25;
 System.out.println(age); // prints 24

System.out.println (AGE); // prints 25

 Variables must start with either a letter or an underscore, _ or a dollar,


$ sign. For-example,

 int age; // valid name and good practice


 int _age; // valid but bad practice

int $age; // valid but bad practice

 Variable names cannot start with numbers. For example,

int 1age; // invalid variables

 Variable names can't use whitespace. For example,

int my age; // invalid variables

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 ]

There are 4 types of variables in Java programming language:

 Instance Variables (Non-Static Fields)

 Class Variables (Static Fields)

 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';

Here, 1, 2.5, and 'F' are literals.


Here are different types of literals in Java.

1. Boolean Literals

In Java, boolean literals are used to initialize boolean data types. They can
store two values: true and false. For example,

boolean flag1 = false;


boolean flag2 = true;

Here, false and true are two boolean literals.

12
[Pick the date] [ Type the document title ]

2. Integer Literals

An integer literal is a numeric value (associated with numbers) without any


fractional or exponential part. There are 4 types of integer literals in Java:

1. binary (base 2)

2. decimal (base 10)

3. octal (base 8)

4. hexadecimal (base 16)

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.

Note: Integer literals are used to initialize variables of integer types


like byte, short, int, and long.

13
[Pick the date] [ Type the document title ]

3. Floating-point Literals

A floating-point literal is a numeric literal that has either a fractional form or


an exponential form. For example,

class Main {
public static void main(String[] args) {

double myDouble = 3.4;


float myFloat = 3.4F;

// 3.445*10^2
double myDoubleScientific = 3.445e2;

System.out.println(myDouble); // prints 3.4


System.out.println(myFloat); // prints 3.4
System.out.println(myDoubleScientific); // prints 344.5
}
}
Run Code

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 ]

char letter = 'a';

Here, a is the character literal.


We can also use escape sequences as character literals. For example, \
b (backspace), \t (tab), \n (new line), etc.
5. String literals

A string literal is a sequence of characters enclosed inside double-quotes. For


example,

String str1 = "Java Programming";


String str2 = "Programiz";

Here, Java Programming and Programiz are two string literals.

Java Data Types (Primitive)

Java Data Types

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

8 Primitive Data Types

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

boolean flag = true;


System.out.println(flag); // prints true
}
}
2. byte type

 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

Example 3: Java short data type


class Main {
public static void main(String[] args) {

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 ]

Example 4: Java int data type


class Main {
public static void main(String[] args) {

int range = -4250000;


System.out.println(range); // print -4250000
}
}
5. long type

 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

Example 5: Java long data type


class LongExample {
public static void main(String[] args) {

long range = -42332200000L;


System.out.println(range); // prints -42332200000
}
}
Notice, the use of L at the end of -42332200000. This represents that it's an
integer of the long type.
6. double type

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

18
[Pick the date] [ Type the document title ]

Example 6: Java double data type


class Main {
public static void main(String[] args) {

double number = -42.3;


System.out.println(number); // prints -42.3
}
}
7. float type

 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 7: Java float data type


class Main {
public static void main(String[] args) {

float number = -42.3f;


System.out.println(number); // prints -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 the compiler to treat -42.3 as float rather than double, you need to
use f or F.
If you want to know about single-precision and double-precision, visit Java
single-precision and double-precision floating-point.

19
[Pick the date] [ Type the document title ]

8. char type

 It's a 16-bit Unicode character.

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

char letter = '\u0051';


System.out.println(letter); // prints Q
}
}
Here, the Unicode value of Q is \u0051. Hence, we get Q as the output.
Here is another example:

class Main {
public static void main(String[] args) {

char letter1 = '9';


System.out.println(letter1); // prints 9

char letter2 = 65;


System.out.println(letter2); // prints A

}
}
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 ]

Hence, A is printed to the output. It is because Java treats characters as an


integer and the ASCII value of A is 65. To learn more about ASCII, visit What
is ASCII Code?.
String type

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,

String myString = "Java Programming";

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 ]

1. Java Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on variables


and data. For example,

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

% Modulo Operation (Remainder after division)

Example 1: Arithmetic Operators


class Main {
public static void main(String[] args) {

// 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 ]

System.out.println("a * b = " + (a * b));


// division operator
System.out.println("a / b = " + (a / b));

// 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

In the above example, we have used +, -, and * operators to compute


addition, subtraction, and multiplication operations.
/ Division Operator
Note the operation, a / b in our program. The / operator is the division
operator.
Note

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 ]

The modulo operator % computes the remainder. When a = 7 is divided


by b = 4, the remainder is 3.

Note: The % operator is mainly used with integers.

2. Java Assignment Operators

Assignment operators are used in Java to assign values to variables. For


example,

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.

Operator Example Equivalent to

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

Example 2: Assignment Operators


class Main {
public static void main(String[] args) {

// create variables
int a = 4;
int var;

// assign value using =


var = a;
System.out.println("var using =: " + var);

// assign value using =+


var += a;
System.out.println("var using +=: " + var);

// assign value using =*


var *= a;
System.out.println("var using *=: " + var);
}
}
Output

var using =: 4
var using +=: 8
var using *=: 32

3. Java Relational Operators

Relational operators are used to check the relationship between two


operands. For example,

// check if a is less than b


a < b;

Here, < operator is the relational operator. It checks if a is less than b or not.
25
[Pick the date] [ Type the document title ]

It returns either true or false.


Operator Description Example

== Is Equal To 3 == 5 returns false

!= Not Equal To 3 != 5 returns true

> Greater Than 3 > 5 returns false

< Less Than 3 < 5 returns true

>= Greater Than or Equal To 3 >= 5 returns false

<= Less Than or Equal To 3 <= 5 returns true

Example 3: Relational Operators


class Main {
public static void main(String[] args) {

// 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 ]

System.out.println(a < b); // true

// >= operator
System.out.println(a >= b); // false

// <= operator
System.out.println(a <= b); // true
}
}

Note: Relational operators are used in decision making and loops.

4. Java Logical Operators

Logical operators are used to check whether an expression is true or false.


They are used in decision making.
Operator Example Meaning

true only if both


&& (Logical expression1 &&
expression1 and
AND) expression2
expression2 are true

|| (Logical expression1 || true if either expression1


OR) expression2 or expression2 is true

! (Logical true if expression is false


!expression
NOT) and vice versa

27
[Pick the date] [ Type the document title ]

Example 4: Logical Operators


class Main {
public static void main(String[] args) {

// && 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 ]

5. Java Unary Operators

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

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

Increment and Decrement Operators

Java also provides increment and decrement operators: +


+ and -- respectively. ++ increases the value of the operand by 1,
while -- decrease it by 1. For example,

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 ]

Example 5: Increment and Decrement Operators


class Main {
public static void main(String[] args) {

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

System.out.println("Value of b: " + b);

// 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 ]

To learn more about these operators, visit increment and decrement


operators.

Increment ++ and Decrement -- Operator as Prefix and Postfix

In programming (Java, C, C++, JavaScript etc.), the increment operator +


+ increases the value of a variable by 1. Similarly, the decrement
operator -- decreases the value of a variable by 1.

a=5

++a; // a becomes 6

a++; // a becomes 7

--a; // a becomes 6

a--; // a becomes 5

Simple enough till now. However, there is an important difference when


these two operators are used as a prefix and a postfix.

++ and -- operator as prefix and postfix

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

The -- operator works in a similar way to the ++ operator except -- decreases


the value 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>

using namespace std;

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 ]

Example 3: Java Programming

class Operator {
public static void main(String[] args) {

var1 = 5, var2 = 5;int


// 5 is displayed
// Then, var1 is increased to 6.
System.out.println(var1++);

// var2 is increased to 6
// Then, var2 is displayed
System.out.println(++var2);
}
}

Example 4: JavaScript

let var1 = 5, var2 = 5;

// 5 is displayed
// Then, var1 is increased to 6
console.log(var1++)

// var2 is increased to 6
// Then, var2 is displayed
console.log(++var2)

The output of all these programs will be the same.

33
[Pick the date] [ Type the document title ]

Output

5
6

6. Java Bitwise Operators

Bitwise operators in Java are used to perform operations on individual bits.


For example,

Bitwise complement Operation of 35

35 = 00100011 (In Binary)


~ 00100011
________
11011100 = 220 (In decimal)

Here, ~ is a bitwise operator. It inverts the value of each bit


(0 to 1 and 1 to 0).
The various bitwise operators present in Java are:

Operator Description

~ Bitwise Complement

<< Left Shift

>> Right Shift

>>> Unsigned Right Shift

& Bitwise AND

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

Java Bitwise and Shift Operators

In Java, bitwise operators perform operations on integer data at the


individual bit-level. Here, the integer data includes byte, short, int,
and long types of data.
There are 7 operators to perform bit-level operations in Java.

Operator Description

| Bitwise OR

& Bitwise AND

^ Bitwise XOR

~ Bitwise Complement

<< Left Shift

>> Signed Right Shift

>>> Unsigned Right Shift

35
[Pick the date] [ Type the document title ]

1. Java Bitwise OR Operator

The bitwise OR | operator returns 1 if at least one of the operands is 1.


Otherwise, it returns 0.
The following truth table demonstrates the working of the bitwise OR
operator. Let a and b be two operands that can only take binary values i.e. 1
or 0.

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.

Let's look at the bitwise OR operation of two integers 12 and 25.

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25


00001100
| 00011001
____________
00011101 = 29 (In Decimal)

36
[Pick the date] [ Type the document title ]

Example 1: Bitwise OR
class Main {
public static void main(String[] args) {

int number1 = 12, number2 = 25, result;

// bitwise OR between 12 and 25


result = number1 | number2;
System.out.println(result); // prints 29
}
}
R

2. Java Bitwise AND Operator

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.

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

// Bitwise AND Operation of 12 and 25


00001100
& 00011001
____________
00001000 = 8 (In Decimal)

Example 2: Bitwise AND


class Main {
public static void main(String[] args) {

int number1 = 12, number2 = 25, result;

// bitwise AND between 12 and 25

result = number1 & number2;


System.out.println(result); // prints 8
}
}
3. Java Bitwise XOR Operator

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.

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

// Bitwise XOR Operation of 12 and 25


00001100
^ 00011001
____________
00010101 = 21 (In Decimal)

Example 3: Bitwise XOR


class Main {
public static void main(String[] args) {

int number1 = 12, number2 = 25, result;

// bitwise XOR between 12 and 25


result = number1 ^ number2;
System.out.println(result); // prints 21
}
}

39
[Pick the date] [ Type the document title ]

4. Java Bitwise Complement Operator

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.

Java Bitwise Complement Operator


It is important to note that the bitwise complement of any integer N is equal
to - (N + 1). For example,
Consider an integer 35. As per the rule, the bitwise complement of 35 should
be - (35 + 1) = -36. Now let's see if we get the correct answer or not.

35 = 00100011 (In Binary)

// using bitwise complement operator


~ 00100011
__________
11011100

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 ]

To understand this we first need to calculate the binary output of -36.


2's Complement

In binary arithmetic, we can calculate the binary negative of an integer using


2's complement.

1's complement changes 0 to 1 and 1 to 0. And, if we add 1 to the result of the


1's complement, we get the 2's complement of the original number. For
example,

// compute the 2's complement of 36


36 = 00100100 (In Binary)

1's complement = 11011011

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

int number = 35, result;

// bitwise complement of 35
result = ~number;
System.out.println(result); // prints -36

41
[Pick the date] [ Type the document title ]

}
}
Java Shift Operators

There are three types of shift operators in Java:

 Signed Left Shift (<<)

 Signed Right Shift (>>)

 Unsigned Right Shift (>>>)

5. Java Left Shift Operator

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.

Example 5: Left Shift Operators

42
[Pick the date] [ Type the document title ]

class Main {
public static void main(String[] args) {

int number = 2;

// 2 bit left shift operation


int result = number << 2;
System.out.println(result); // prints 8
}
}
6. Java Signed Right Shift Operator

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)

// perform 2 bit right shift


8 >> 2:
1000 >> 2 = 0010 (equivalent to 2)

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)

1's complement = 0111

43
[Pick the date] [ Type the document title ]

2's complement:

0111
+1
_______
1000

Signed bit = 1

// perform 2 bit right shift


8 >> 2:
1000 >> 2 = 1110 (equivalent to -2)

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;

// 2 bit signed right shift


System.out.println(number1 >> 2); // prints 2
System.out.println(number2 >> 2); // prints -2
}
}
7. Java Unsigned Right Shift Operator

Java also provides an unsigned right shift. It is denoted by >>>.


Here, the vacant leftmost position is filled with 0 instead of the sign bit. For
example,

// unsigned right shift of 8


8 = 1000

44
[Pick the date] [ Type the document title ]

8 >>> 2 = 0010

// unsigned right shift of -8


-8 = 1000 (see calculation above)

-8 >>> 2 = 0010

Example 7: UnSigned Right Shift


class Main {
public static void main(String[] args) {

int number1 = 8;
int number2 = -8;

// 2 bit signed right shift


System.out.println(number1 >>> 2); // prints 2
System.out.println(number2 >>> 2); // prints 1073741822
}
}
Run Code

As we can see the signed and unsigned right shift operator returns different
results for negative bits.

Other operators

Besides these operators, there are other additional operators in Java.

Java instanceof Operator

The instanceof operator checks whether an object is an instanceof a


particular class. For example,
class Main {
public static void main(String[] args) {

45
[Pick the date] [ Type the document title ]

String str = "Programiz";


boolean result;

// checks if str is an instance of


// the String class
result = str instanceof String;
System.out.println("Is str an object of String? " + result);
}
}
Run Code

Output

Is str an object of String? true

Here, str is an instance of the String class. Hence, the instanceof operator
returns true. To learn more, visit Java instanceof.
Java Ternary Operator

The ternary operator (conditional operator) is shorthand for the if-then-


else statement. For example,

variable = Expression ? expression1 : expression2

Here's how it works.

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


 If the Expression is false, expression2 is assigned to the variable.
Let's see an example of a ternary operator.

class Java {
public static void main(String[] args) {

int februaryDays = 29;


String result;

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 Basic Input and Output

Java Output

In Java, you can simply use

System.out.println(); or

System.out.print(); or

System.out.printf();

to send output to standard output (screen).

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

System.out.println("Java programming is interesting.");


}
}
Run Code

Output:

Java programming is interesting.

Here, we have used the println() method to display the string.


48
[Pick the date] [ Type the document title ]

Difference between println(), print() and printf()

 print() - It prints string inside the quotes.


 println() - It 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: print() and println()


class Output {
public static void main(String[] args) {

System.out.println("1. println ");


System.out.println("2. println ");

System.out.print("1. print ");


System.out.print("2. print");
}
}
Run Code

Output:

1. println
2. println
1. print 2. print

49
[Pick the date] [ Type the document title ]

In the above example, we have shown the working of


the print() and println() methods. To learn about the printf() method,
visit Java printf().

Example: Printing Variables and Literals


class Variables {
public static void main(String[] args) {

Double number = -10.6;

System.out.println(5);
System.out.println(number);
}
}
Run Code

When you run the program, the output will be:

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.

Example: Print Concatenated Strings


class PrintVariables {
50
[Pick the date] [ Type the document title ]

public static void main(String[] args) {

Double number = -10.6;

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


System.out.println("Number = " + number);
}
}
Run Code

Output:

I am awesome.
Number = -10.6

In the above example, notice the line,

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

Here, we have used the + operator to concatenate (join) the two strings: "I
am " and "awesome.".
And also, the line,

System.out.println("Number = " + number);

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.

// create an object of Scanner


Scanner input = new Scanner(System.in);

// take input from the user


int number = input.nextInt();

Example: Get Integer Input From the User


import java.util.Scanner;

class Input {
public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter an integer: ");


int number = input.nextInt();

52
[Pick the date] [ Type the document title ]

System.out.println("You entered " + number);

// closing the scanner object


input.close();
}
}
Run Code

Output:

Enter an integer: 23
You entered 23

In the above example, we have created an object named input of


the Scanner class. We then call the nextInt() method of the Scanner class to
get an integer input from the user.
Similarly, we can use nextLong(), nextFloat(), nextDouble(),
and next() methods to get long, float, double, and string input respectively
from the user.

Note: We have used the close() method to close the object. It is


recommended to close the scanner object once the input is taken.

Example: Get float, double and String Input


import java.util.Scanner;

class Input {
public static void main(String[] args) {

Scanner input = new Scanner(System.in);

53
[Pick the date] [ Type the document title ]

// Getting float input


System.out.print("Enter float: ");
float myFloat = input.nextFloat();
System.out.println("Float entered = " + myFloat);

// Getting double input


System.out.print("Enter double: ");
double myDouble = input.nextDouble();
System.out.println("Double entered = " + myDouble);

// Getting String input


System.out.print("Enter text: ");
String myString = input.next();
System.out.println("Text entered = " + myString);
}
}
Run Code

Output:

Enter float: 2.343


Float entered = 2.343
Enter double: -23.4
Double entered = -23.4
Enter text: Hey!
Text entered = Hey!

As mentioned, there are other several ways to get input from the user. To
learn more about Scanner, visit Java Scanner.

Java Expressions, Statements and Blocks

54
[Pick the date] [ Type the document title ]

In previous chapters, we have used expressions, statements, and blocks


without much explaining about them. Now that you know about variables,
operators, and literals, it will be easier to understand these concepts.

Java Expressions

A Java expression consists of variables, operators, literals, and method calls.


To know more about method calls, visit Java methods. For example,

int score;
score = 90;

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


example,

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 a boolean value.


Similarly, "Number 1 is larger than number 2" is a string expression.

Java Statements
55
[Pick the date] [ Type the document title ]

In Java, each statement is a complete unit of execution. For example,

int score = 9*5;

Here, we have a statement. The complete execution of this statement


involves multiplying integers 9 and 5 and then assigning the result to the
variable score.
In the above statement, we have an expression 9 * 5. In Java, expressions are
part of statements.

Expression statements

We can convert an expression into a statement by terminating the


expression with a ;. These are known as expression statements. For example,

// expression
number = 10
// statement
number = 10;

In the above example, we have an expression number = 10. Here, by adding a


semicolon (;), we have converted the expression into a statement (number =
10;).
Consider another example,

// expression
++number
// statement
++number;

56
[Pick the date] [ Type the document title ]

Similarly, ++number is an expression whereas ++number; is a statement.

Declaration Statements

In Java, declaration statements are used for declaring variables. For example,

Double tax = 9.5;

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

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

A block is a group of statements (zero or more) that is enclosed in curly


braces { }. For example,
class Main {
public static void main(String[] args) {

String band = "Beatles";

if (band == "Beatles") { // start of block


System.out.print("Hey ");
System.out.print("Jude!");

57
[Pick the date] [ Type the document title ]

} // end of block
}
}
Run Code

Output:

Hey Jude!

In the above example, we have a block if {....}.


Here, inside the block we have two statements:

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

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

} // 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

In computer programming, comments are a portion of the program that are


completely ignored by Java compilers. They are mainly used to help
programmers to understand the code. For example,

// declare and initialize two variables


int a =1;
int b = 3;

// print the output


System.out.println("This is output");

Here, we have used the following comments,

 declare and initialize two variables

 print the output

Types of Comments in Java

In Java, there are two types of 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!

Here, we have used two single-line comments:

 "Hello, World!" program example


 prints "Hello World!"
The Java compiler ignores everything from // to the end of line. Hence, it is
also known as End of Line comment.

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,

/* This is an example of multi-line comment.


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

class HelloWorld {
public static void main(String[] args) {

System.out.println("Hello, World!");
}
}
Run Code

Output:

Hello, World!

Here, we have used the multi-line comment:

/* This is an example of multi-line comment.


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

This type of comment is also known as Traditional Comment. In this type


of comment, the Java compiler ignores everything from /* to */.

Use Comments the Right Way


61
[Pick the date] [ Type the document title ]

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.

Some believe that code should be self-describing and comments should be


rarely used. However, in my personal opinion, there is nothing wrong with
using comments. We can use comments to explain complex algorithms,
regex or scenarios where we have to choose one technique among different
technique to solve problems.

Note: In most cases, always use comments to explain 'why' rather than 'how'
and you are good to go.

62

You might also like