Java Basics
Java Basics
COURSE CODE:22CBT306C
What is Java?
Java is a programming language and a platform. Java is a high level, robust, object-oriented
and secure programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of Java. Before Java, its name was Oak.
Platform: Any hardware or software environment in which a program runs, is known as a
platform. Since Java has a runtime environment (JRE) and API, it is called a platform.
Applications
According to Sun, 3 billion devices run Java. There are many devices where Java is currently
used. Some of them are as follows:
Desktop Applications such as acrobat reader, media player, antivirus, etc.
Web Applications such as irctc.co.in, javatpoint.com, etc.
Enterprise Applications such as banking applications.
Mobile
Embedded System
Smart Card
Robotics
Games, etc.
Types of Java Applications
There are mainly 4 types of applications that can be created using Java programming:
1) Standalone Application
Standalone applications are also known as desktop applications or window-based
applications. These are traditional software that we need to install on every machine.
Examples of standalone application are Media player, antivirus, etc. AWT and Swing are
used in Java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates a dynamic page is called a web
application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used
for creating web applications in Java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called an
enterprise application. It has advantages like high-level security, load balancing, and
clustering. In Java, EJB is used for creating enterprise applications.
4) Mobile Application
An application which is created for mobile devices is called a mobile application. Currently,
Android and Java ME are used for creating mobile applications.
Java Platforms / Editions
There are 4 platforms or editions of Java:
1) Java SE (Java Standard Edition)
It is a Java programming platform. It includes Java programming APIs such as java.lang,
java.io, java.net, java.util, java.sql, java.math etc. It includes core topics like OOPs, String,
Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing,
Reflection, Collection, etc.
2) Java EE (Java Enterprise Edition)
It is an enterprise platform that is mainly used to develop web and enterprise applications. It
is built on top of the Java SE platform. It includes topics like Servlet, JSP, Web Services,
EJB, JPA, etc.
3) Java ME (Java Micro Edition)
It is a micro platform that is dedicated to mobile applications.
4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface API.
History of Java
Following are given significant points that describe the history of Java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in
June 1991. The small team of sun engineers called Green Team.
2) Initially it was designed for small, embedded systems in electronic appliances like set-top
boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
Why Java was named as "Oak"?
5) Why Oak?
Oak is a symbol of strength and chosen as a national tree of many countries like the U.S.A.,
France, Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
Why Java Programming named "Java"?
7) Why had they chose the name Java for Java language?
The team gathered to choose a new name. The suggested words were "dynamic",
"revolutionary", "Silk", "jolt", "DNA", etc. They wanted something that reflected the essence
of the technology: revolutionary, dynamic, lively, cool, unique, and easy to spell, and fun to
say.
According to James Gosling, "Java was one of the top choices along with Silk". Since Java
was so unique, most of the team members preferred Java than other names.
8) Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is
a kind of espresso bean. Java name was chosen by James Gosling while having a cup of
coffee nearby his office.
9) Notice that Java is just a name, not an acronym.
10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of
Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
Features of Java
The primary objective of Java programming language creation was to make it portable,
simple and secure programming language. Apart from this, there are also some excellent
features which play an important role in the popularity of this language. The features of Java
are also known as Java buzzwords.
A list of the most important features of the Java language is given below.
Simple
Object-Oriented
Portable
Platform independent
Secured
Robust
Architecture neutral
Interpreted
High Performance
Multithreaded
Distributed
Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun Microsystem, Java language is a simple programming language because:
Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc.
There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.
Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
incorporate both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software development
and maintenance by providing some rules.
Basic concepts of OOPs are:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Platform Independent
Java is platform independent
Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on top of other hardware-based platforms. It has two components:
Runtime Environment
API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere (WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
No explicit pointer
Java Programs run inside a virtual machine sandboxClassloader: Classloader in Java is a part
of the Java Runtime Environment (JRE) which is used to load Java classes into the Java
Virtual Machine dynamically. It adds security by separating the package for the classes of the
local file system from those that are imported from network sources.
Bytecode Verifier: It checks the code fragments for illegal code that can violate
access rights to objects.
Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
The English mining of Robust is strong. Java is robust because:
It uses strong memory management.
There is a lack of pointers that avoids security problems.
Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid
of objects which are not being used by a Java application anymore.
There are exception handling and the type checking mechanism in Java. All these points
make Java robust.
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32
and 64-bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g.,
C++). Java is an interpreted language that is why it is slower than compiled languages, e.g.,
C, C++, etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI
and EJB are used for creating distributed applications. This feature of Java makes us able to
access files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.
Java supports dynamic compilation and automatic memory management (garbage collection).
First Java Program
In this section, we will learn how to write the simple program of Java
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
Compilation Flow:
When we compile Java program using javac tool, the Java compiler converts the source code
into byte code.
class A{
static public void main(String... args){
System.out.println("hello java4");
}
};
5) Valid Java main() method signature:
To compile:
javac Hard.java
To execute:
java Simple
Observe that, we have compiled the code with file name but running the program with class
name. Therefore, we can save a Java program other than class name.
Q) Can you have multiple classes in a java source file?
Yes, like the figure given below illustrates:
Difference between JDK, JRE, and JVM
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it
doesn't physically exist. It is a specification that provides a runtime environment in which
Java bytecode can be executed. It can also run those programs which are written in other
languages and compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are
platform dependent because the configuration of each OS is different from each other.
However, Java is platform independent. There are three notions of the JVM: specification,
implementation, and instance.
The JVM performs the following main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java
Runtime Environment is a set of software tools which are used for developing Java
applications. It is used to provide the runtime environment. It is the implementation of JVM.
It physically exists. It contains a set of libraries + other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun Micro
Systems.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It
physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:
What is JVM ?
It is:
A specification where working of Java Virtual Machine is specified. But implementation
provider is independent to choose the algorithm. Its implementation has been provided by
Oracle and other companies.
An implementation Its implementation is known as JRE (Java Runtime Environment).
Runtime Instance Whenever you write java command on the command prompt to run the java
class, an instance of JVM is created.
What it does?
The JVM performs following operation:
Loads code
Verifies code
Executes code
Provides runtime environment
JVM provides definitions for the:
Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.
JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader, memory area,
execution engine etc.
1) Classloader
Classloader is a subsystem of JVM which is used to load class files. Whenever we run the
java program, it is loaded first by the classloader. There are three built-in classloaders in Java.
Bootstrap ClassLoader: This is the first classloader which is the super class of
Extension classloader. It loads the rt.jar file which contains all class files of Java
Standard Edition like java.lang package classes, java.net package classes, java.util
package classes, java.io package classes, java.sql package classes etc.
Extension ClassLoader: This is the child classloader of Bootstrap and parent
classloader of System classloader. It loades the jar files located inside
$JAVA_HOME/jre/lib/ext directory.
System/Application ClassLoader: This is the child classloader of Extension
classloader. It loads the classfiles from classpath. By default, classpath is set to
current directory. You can change the classpath using "-cp" or "-classpath" switch. It
is also known as Application classloade
2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field and
method data, the code for methods.
3) Heap
It is the runtime data area in which objects are allocated.
4) Stack
Java Stack stores frames. It holds local variables and partial results, and plays a part in
method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method
invocation completes.
5) Program Counter Register
PC (program counter) register contains the address of the Java virtual machine instruction
currently being executed.
6) Native Method Stack
It contains all the native methods used in the application.
7) Execution Engine
It contains:
A virtual processor
Interpreter: Read bytecode stream then execute the instructions.
Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles
parts of the byte code that have similar functionality at the same time, and hence
reduces the amount of time needed for compilation. Here, the term "compiler" refers
to a translator from the instruction set of a Java virtual machine (JVM) to the
instruction set of a specific CPU.
8) Java Native Interface
Java Native Interface (JNI) is a framework which provides an interface to communicate with
another application written in another language like C, C++, Assembly etc. Java uses JNI
framework to send output to the Console or interact with OS libraries.
Java Variables
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java: local,
instance and static.A variable is the name of a reserved area allocated in memory. In other
words, it is a name of the memory location. It is a combination of "vary + able" which means
its value can be changed.of data types in Java: primitive and non-primitive.
Types of Variables
There are three types of variables in Java:
local variable
instance variable
static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
A local variable cannot be defined with "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among
instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can
create a single copy of the static variable and share it among all the instances of the class.
Memory allocation for static variables happens only once when the class is loaded in the
memory.
Example to understand the types of variables in java
public class A
{
static int m=100;//static variable
void method()
{
int n=90; //local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}
Data Types in Java
Data types specify the different sizes and values that can be stored in the variable. There are
two types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long,
float and double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.
boolean Data Type
The Boolean data type is used to store only two possible values: true and false.
Example:
Boolean one = false
byte Data Type
The byte data type is an example of primitive data type. It isan 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used
in place of "int" data type.
Example:
byte a = 10, byte b = -20
short Data Type
The short data type is a 16-bit signed two's complement integer. Its value-range lies between
-32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767.
Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short data
type is 2 times smaller than an integer.
Example:
short s = 10000, short r = -5000
int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is
no problem about memory.
Example:
int a = 100000, int b = -200000
long Data Type
The long data type is a 64-bit two's complement integer.
Example:
long a = 100000L, long b = -200000L
Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is
unlimited.
Example:
float f1 = 234.5f
double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float.
Example:
double d1 = 12.3
char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000'
(or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.
Example:
char letterA = 'A'
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Keywords
Identifiers
Literals
Operators
Separators
Comments
Keywords:
These are the pre-defined reserved words of any programming language. Each keyword has a
special meaning. It is always written in lower case. Java provides the following keywords:
Identifier:
Identifiers are used to name a variable, constant, function, class, and array. It usually defined
by the user. It uses letters, underscores, or a dollar sign as the first character.
Some valid identifiers are:
PhoneNumber
PRICE
radius
Literals:
In programming literal is a notation that represents a fixed value (constant) in the source
code. It can be categorized as an integer literal, string literal, Boolean literal, etc. It is defined
by the programmer. Once it has been defined cannot be changed. Java provides five types of
literals are as follows:
Integer
Floating Point
Character
String
Boolean
LiteralType
23 int
9.86 double
false, true boolean
'K', '7', '-' char
"javatpoint" String
null any reference type
Operators: In programming, operators are the special symbol that tells the compiler to
perform a special operation. Java provides different types of operators that can be classified
according to the functionality they provide. There are eight types of operators in Java, are as
follows:
Arithmetic Operators
Assignment Operators
Relational Operators
Unary Operators
Logical Operators
Ternary Operators
Bitwise Operators
Shift Operators
Operator Symbols
Arithmetic +,-,/,*,%
Unary ++ , - - , !
Assignment = , += , -= , *= , /= , %= ,
^=
Relational ==, != , < , >, <= , >=
Logical && , ||
Ternary (Condition) ?
(Statement1) : (Statement2);
Bitwise &,|,^,~
Shift << , >> , >>>
Separators:
The separators in Java is also known as punctuators. There are nine separators in Java, are as
follows:
Square Brackets []: It is used to define array elements. A pair of square brackets represents
the single-dimensional array, two pairs of square brackets represent the two-dimensional
array.
Parentheses (): It is used to call the functions and parsing the parameters.
Curly Braces {}: The curly braces denote the starting and ending of a code block.
Comma (,): It is used to separate two values, statements, and parameters.
Assignment Operator (=): It is used to assign a variable and constant.
Semicolon (;): It is the symbol that can be found at end of the statements. It separates the two
statements.
Period (.): It separates the package name form the sub-packages and class. It also separates a
variable or method from a reference variable.
Comments:
Comments allow us to specify information about the program inside our Java code. Java
compiler recognizes these comments as tokens but excludes it form further processing. The
Java compiler treats comments as whitespaces. Java provides the following two types of
comments:
Line Oriented: It begins with a pair of forwarding slashes (//).
Block-Oriented:Unary Operators
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and
when. Decision-making statements evaluate the Boolean expression and control the program
flow depending upon the result of the condition provided. There are two types of decision-
making statements in Java, i.e., If statement and switch statement.
If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is
diverted depending upon the specific condition. The condition of the If statement gives a
Boolean value, either true or false. In Java, there are four types of if-statements given below.
Simple if statement
if-else statement
if-else-if ladder
Nested if-statement
Let's understand the if-statements one by one.
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.
Syntax of if statement is given below.
if(condition) {
statement 1; //executes when condition is true
}
Consider the following example in which we have used the if statement in the java code.
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code,
i.e., else block. The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
Consider the following example.
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10)
{
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In
other words, we can say that it is the chain of if-else statements that create a decision tree
where the program may enter in the block of code where the condition is true. We can also
define an else statement at the end of the chain.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
Consider the following example.
public class Student {
public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
}
}
}
Output:
Delhi
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if
or else-if statement.
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Consider the following example.
The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
Cases cannot be duplicate
Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value.
The syntax to use the switch statement is given below.
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Consider the following example to understand the flow of the switch statement.
public class Student implements Cloneable {
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
Output:
2
While using switch statements, we must notice that the case expression will be of the same
type as the variable. However, it will also be a constant value. The switch permits only int,
string, and Enum type variables to be used.
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of
instructions in a repeated order. The execution of the set of instructions depends upon a
particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in
their syntax and condition checking time.
for loop
while loop
do-while loop
Let's understand the loop statements one by one.
It is also known as the exit-controlled loop since the condition is not checked in advance. The
syntax of the do-while loop is given below.
do
{
//statements
} while (condition);
Consider the following example to understand the functioning of the do-while loop in
Java.
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In
other words, jump statements transfer the execution control to the other part of the program.
There are two types of jump statements in Java, i.e., break and continue.
Introduction The Java for loop is a The Java while loop The Java do while
control flow statement that is a control flow loop is a control
iterates a part of statement that flow statement that
the programs multiple executes a part of executes a part of
times. the programs the programs at
repeatedly on the least once and the
basis of given further execution
boolean condition. depends upon the
given boolean
condition.
Single line comments starts with two forward slashes (//). Any text in front of // is not
executed by Java.
Syntax:
//This is single line comment
Java Multi Line Comment
The multi-line comment is used to comment multiple lines of code. It can be used to explain a
complex code snippet or to comment multiple lines of code at a time (as it will be difficult to
use single-line comments there).
Multi-line comments are placed between /* and */. Any text between /* and */ is not
executed by Java.
Syntax:
/*
This is multi line comment
*/
Java Documentation Comment
Documentation comments are usually used to write large programs for a project or software
application as it helps to create documentation API. These APIs are needed for reference, i.e.,
which classes, methods, arguments, etc., are used in the code.
Syntax:
/**
*
*We can use various tags to depict the parameter
*or heading or author name
*We can also use HTML tags
*
*/
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
Unary Operator,
Arithmetic Operator,
Shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
Unary operators
Unary operators are those operators in Java that only need a single operand to perform any function.
They work on the same principal as unary operations in mathematics.
For example, You can use unary operators to represent a positive value, negative value, increment a
value by 1, decrement a value by 1 or to negate a value.
+x (positive value)
-x (negative value)
++x (increment operation)
--x (decrement operation)
!x (negation)
Types of Unary Operators
There are 5 types of the Unary Operators
1. Unary Plus
It represents a positive value like +x = x or +5 = 5.
2. Unary Minus
It represents a negative value like -x = -x or -5 = -5.
5. Logical Complement
It logically inverts the value of a boolean like if x = true, then !x will be false.
Increment Operator (++)
The increment (++) operator (also known as increment unary operator) in Java is used to increase the
value of a variable by 1. Since it is a type of a unary operator, it can be used with a single operand.
Syntax
The syntax for increment operator is a pair of addition signs ie;
++x;
x++;
The operator can be applied either before or after the variable. Both will have the same increment of
1. However, they both have separate uses and can be categorized as the following types.
Pre-Increment Operator
Post-Increment Operator
Example1:
public class IncrementOperator {
public static void main(String[] args) {
int variable = 15;
System.out.println("Original value of the variable = " + variable);
// after using increment operator
variable++; // increments 1, variable = 16
System.out.println("variable++ = " + variable);
++variable; // increments 1, variable = 17
System.out.println("++variable = " + variable);
}
}
Output
Original value of the variable = 15
variable++ = 16
++variable = 17
Pre-Increment Operator (++x;)
If the increment operator (++) is specified before the variable like a prefix (++x), then it is called pre-
increment operator. In this case, the value of the variable is first incremented by 1, and then further
computations are performed.
Example 2.
public class PreIncrementOperator {
public static void main(String[] args) {
int variable = 5;
System.out.println("Original value of the variable = " + variable);
// using pre-increment operator
int preIncrement = ++variable;
System.out.println("variable = " + variable);
System.out.println("preIncrement = " + preIncrement);
System.out.println("++preIncrement = " + ++preIncrement);
}
}
Output
Original value of the variable = 5
variable = 6
preIncrement = 6
++preIncrement = 7
Post-Increment Operator (x++;)
If the increment operator (++) is specified after the variable like a postfix (x++), then it is called post-
increment operator. In this case, the original value of the variable (without increment) is used for
computations and then it is incremented by 1.
Example 3.
public class PostIncrementOperator {
public static void main(String[] args) {
int variable = 100;
System.out.println("Original value of the variable = " + variable);
// using post-increment operator
int postIncrement = variable++; // postIncrement = 100, variable = 101
System.out.println("postIncrement = " + postIncrement);
System.out.println("variable = " + variable + "\n");
// postIncrement = 101
System.out.println("postIncrement++ = " + postIncrement++);
// postIncrement = 102
System.out.println("postIncrement++ = " + postIncrement++);
// postIncrement = 103
System.out.println("postIncrement++ = " + postIncrement++);
System.out.println("\npostIncrement = " + postIncrement);
}
}
Output
Original variable = 100
postIncrement = 100
variable = 101
postIncrement++ = 100
postIncrement++ = 101
postIncrement++ = 102
Pre-Decrement Operator
Post-Decrement Operator
Pre-Decrement Operator (--x;)
If the decrement operator (--) is mentioned before the variable like a prefix (--x), then it is called a
pre-decrement operator. For this case, the value of the variable is first decremented by 1, and then
other computations are performed.
Example 4
public class PreDecrementOperator {
public static void main(String[] args) {
int variable = 11;
System.out.println("Original value of the variable = " + variable);
// using preDecrement operator
int preDecrement = --variable;
// variable = 10
System.out.println("variable = " + variable);
// preDecrement = 10
Output
Original value of the variable = 11
variable = 10
preDecrement = 10
--preDecrement = 9
Example 5
public class PostDecrementOperator {
public static void main(String[] args) {
int variable = 75;
System.out.println("Original value of the variable = " + variable);
// using postDecrement operator
// postDecrement = 75, variable = 74
int postDecrement = variable--;
System.out.println("postDecrement = " + postDecrement);
System.out.println("variable = " + variable + "\n");
// postDecrement = 74
System.out.println("postDecrement-- = " + postDecrement--);
// postDecrement = 73
System.out.println("postDecrement-- = " + postDecrement--);
// postDecrement = 72
System.out.println("postDecrement-- = " + postDecrement--);
System.out.println("\npostDecrement = " + postDecrement);
}
}
Output:
Original value of the variable = 75
postDecrement = 75
variable = 74
postDecrement-- = 75
postDecrement-- = 74
postDecrement-- = 73
postDecrement = 72
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They
act as basic mathematical operations.
The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified
number of times.
The Java right shift operator >> is used to move the value of the left operand to right by the number of
bits specified by the right operand.
public OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}
The logical && operator doesn't check the second condition if the first condition is false. It checks the
second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
The logical || operator doesn't check the second condition if the first condition is true. It checks the
second condition only if the first one is false.
The bitwise | operator always checks both conditions whether first condition is true or false.
Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in Java
programming. It is the only conditional operator which takes three operands.
Another Example:
Java assignment operator is one of the most common operators. It is used to assign the value on its
right to the operand on its left.
Java Assignment Operator Example
In Java, type casting is a method or process that converts a data type into another data
type in both ways manually and automatically. The automatic conversion is done by the
compiler and manual conversion performed by the programmer. In this section, we will
discuss type casting and its types with proper examples.
Type casting
Convert a value from one data type to another data type is known as type casting.
Converting a lower data type into a higher one is called widening type casting. It is also
known as implicit conversion or casting down. It is done automatically. It is safe
because there is no chance to lose data. It takes place when:
byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other.
Let's see an example.
WideningTypeCastingExample.java
Output
In the above example, we have taken a variable x and converted it into a long type. After
that, the long type is converted into the float type.
Converting a higher data type into a lower one is called narrowing type casting. It is also
known as explicit conversion or casting up. It is done manually by the programmer. If
we do not perform casting then the compiler reports a compile-time error.
double -> float -> long -> int -> char -> short -> byte
In the following example, we have performed the narrowing type casting two times. First,
we have converted the double type into long data type after that long data type is
converted into int type.
NarrowingTypeCastingExample.java
Output