0% found this document useful (0 votes)
2 views40 pages

COS205 Java Basics

The document provides an overview of Java, a high-level object-oriented programming language developed by Sun Microsystems in 1995, highlighting its features such as platform independence, robustness, and rich APIs. It explains the basic structure of a Java program, the installation process for Java on various operating systems, and the differences between JDK, JRE, and JVM. Additionally, it covers Java identifiers, keywords, and their usage in programming, along with examples of famous applications built using Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views40 pages

COS205 Java Basics

The document provides an overview of Java, a high-level object-oriented programming language developed by Sun Microsystems in 1995, highlighting its features such as platform independence, robustness, and rich APIs. It explains the basic structure of a Java program, the installation process for Java on various operating systems, and the differences between JDK, JRE, and JVM. Additionally, it covers Java identifiers, keywords, and their usage in programming, along with examples of famous applications built using Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

COS205 OBJECT-ORIENTED PROGRAMMING

Introduction to Java



Java is a high-level, object-oriented programming language
developed by Sun Microsystems in 1995. It is mostly used for
building desktop applications, web applications, Android apps and
enterprise systems.

Features of Java
 Object-Oriented Programming (OOP): Java supports
OOP concepts to create modular and reusable code.
 Platform Independence: Java programs can run on any
operating system with a JVM.
 Robust and Secure: Java ensures reliability and security
through strong memory management and exception
handling.
 Multithreading and Concurrency: Java allows
concurrent execution of multiple tasks for efficiency.
 Rich API and Standard Libraries: Java provides
extensive built-in libraries for various programming needs.
 Frameworks for Enterprise and Web
Development: Java supports frameworks that simplify
enterprise and web application development.
 Open-Source Libraries: Java has a wide range of libraries
to extend functionality and speed up development.
 Maintainability and Scalability: Java’s structured design
allows easy maintenance and growth of applications.
Understanding the Hello World Program in
Java
When we learn any programming language, the first step is writing
a simple program to display "Hello World". So, here is a simple Java
program that displays "Hello World" on the screen.
// A Java program to print Hello World!
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello World!");
}
}

Output
Hello World!
Explanation:

Hello World Program Explanation


How to run the above code?
 Write code in a file like [Link].
 Java Compiler "javac" compiles it into bytecode
"[Link]".
 JVM (Java Virtual Machine) reads the .class file and
interprets the bytecode.
 JVM converts bytecode to machine readable code i.e.
"binary" (001001010) and then execute the program. Java
Program Execution Flow.

Comments in Java
Comments are the notes written inside the code to explain what we
are doing. The comment lines are not executed while we run the
program.

Single-line comment

// This is a comment

Multi-line comment

/*
This is a multi-line comment.
This is useful for explaining larger sections of code.
*/
Curly Braces and Indentation in Java
In Java, curly braces {} are used to define blocks of code. For
example, the body of a class or method is enclosed within curly
braces.
Example:
public class Geeks{
public static void main(String[] args) {
{
[Link]("This is inside the block.");
}

[Link]("This is outside the block.");


}
}
 The code block inside {} runs unconditionally and prints a
message.
 Curly braces {} group multiple statements into a single
block, even without conditions.
Famous Applications Built Using Java
 Android Apps: Most of the Android mobile apps are built
using Java.
 Netflix: This uses Java for content delivery and backend
services.
 Amazon: Java language is used for its backend systems.
 LinkedIn: This uses Java for handling high traffic and
scalability.
 Minecraft: This is one of the world’s most popular games
that is built in Java.
 Spotify: This uses Java in parts of its server-side
infrastructure.
 Uber: Java is used for backend services like trip
management.
 NASA WorldWind: This is a virtual globe software built
using Java.
What Can We Do with Java?
Java is used for:
 Mobile App Development: Android development using
Android Studio.
 Web Development: Using frameworks like Spring, Spring
Boot, Struts, Hibernate
 Desktop GUI Applications: With libraries
like JavaFX and Swing.
 Enterprise Applications: Backbone of banking, ERP and
large-scale business software.
 Game Development: With engines like LibGDX and
jMonkeyEngine.
 Big Data Technologies: Like Hadoop and Apache Kafka.
 Internet of Things (IoT): Java can run on embedded
systems and devices.
 Cloud-based Applications: Java is used in services
on AWS, Azure and Google Cloud.
 Scientific Applications: Java is used in tools that process
large amounts of scientific data.

How to Install Java on Windows, Linux and


macOS?



Java is a versatile programming language widely used for building
applications. To start coding in Java, you first need to install
the Java Development Kit (JDK) on your system. This article
provides detailed steps for installing Java on Windows 7, 8, 10, 11,
Linux Ubuntu, and macOS.
Download and Install Java - Windows
Operating System
Here, we will discuss how to download and install Java on a
Windows 64-bit Machine and set up the environment to run the
first Java program on the command prompt. The process is the
same for all Windows i.e. 7, 8, 10, and 11.
Step 1: Visit the official Oracle
website [Link] . Click on the "Download
Java" icon as shown in the below image.
Step 2: Now you can see the latest version is JDK 23 and there
are options for Linux, macOS, and Windows. Click on the Windows
option and then click the x64 Installer option to download
the .exe file for 64-bit Windows OS.

You can simply use this link to download Java for Windows 64 Bit.
After successfully downloading JDK 23, now we need to install the
Java on our Windows System.
Step 3: Go to Downloads and double-click on that
downloaded jdk-23_windows-x64_bin.exe file. So now Java
Installation Wizard get open and then click Next button.

Again click on the Next button to install JDK.

The installation will begin as shown below:


The Java installation is successfully completed as shown
below. Now click on "close" to finish.

Differences Between JDK, JRE and JVM





JDK (Java Development Kit) provides tools and libraries to develop
Java applications, working with JRE and JVM. JRE (Java Runtime
Environment) offers the libraries and JVM needed to run Java
programs. JVM (Java Virtual Machine) executes the compiled Java
bytecode on the system.
Note: Java bytecode can run on any machine with a JVM, but JVM
implementations are platform-dependent for each operating
system.
JDK (Java Development Kit)
JDK is a software development kit used to build Java applications. It
contains the JRE and a set of development tools.
 Includes compiler (javac), debugger, and utilities like jar
and javadoc.
 Provides the JRE, so it also allows running Java programs.
 Required by developers to write, compile, and debug code.
Components of JDK:
 JRE (JVM + libraries)
 Development tools (compiler, jar, javadoc, debugger)
Note:
 JDK is only for development (it is not needed for running
Java programs)
 JDK is platform-dependent (different version for windows,
Linux, macOS)

Working of JDK:

 Source Code (.java): Developer writes a Java program.


 Compilation: The JDK’s compiler (javac) converts the code
into bytecode stored in .class files.
 Execution: The JVM executes the bytecode, translating it
into native instructions.
JRE (Java Runtime Environment)
JRE provides an environment to run Java programs but does not
include development tools. It is intended for end-users who only
need to execute applications.
 Contains the JVM and standard class libraries.
 Provides all runtime requirements for Java applications.
 Does not support compilation or debugging.
Note:
 JRE is only for running applications, not for developing
them.
 It is platform-dependent (different builds for different OS).

Working of JRE:
1. Class Loading: Loads compiled .class files into memory.
2. Bytecode Verification: Ensures security and validity of
bytecode.
3. Execution: Uses the JVM (interpreter + JIT compiler) to
execute instructions and make system calls.
JVM (Java Virtual Machine)
JVM is the core execution engine of Java. It is responsible for
converting bytecode into machine-specific instructions.
 Part of both JDK and JRE.
 Performs memory management and garbage collection.
 Provides portability by executing the same bytecode on
different platforms.
Note:
 JVM implementations are platform-dependent.
 Bytecode is platform-independent and can run on any JVM.
 Modern JVMs rely heavily on Just-In-Time (JIT) compilation
for performance.

Working of JVM:

JVM working
1. Loading: Class loader loads bytecode into memory.
2. Linking: Performs verification, preparation, and resolution.
3. Initialization: Executes class constructors and static
initializers.
4. Execution: Interprets or compiles bytecode into native
code.
JDK vs JRE vs JVM
Aspect JDK JRE JVM

Used to develop Used to run Java Executes Java


Purpose Java applications applications bytecode

JVM is OS-
Platform- Platform- specific, but
Platform dependent (OS dependent (OS bytecode is
Dependenc specific) specific) platform-
y independent

JRE + ClassLoader, JIT


Development JVM + Libraries Compiler,
tools (javac, (e.g., [Link]) Garbage
Includes debugger, etc.) Collector

Convert
Writing and Running a Java
bytecode into
compiling Java application on a
native machine
code system
Use Case code

Java Identifiers



An identifier in Java is the name given to Variables, Classes,
Methods, Packages, Interfaces, etc. These are the unique names
used to identify programming elements. Every Java Variable must
be identified with a unique name.
class Geeks{
public static void main(String[] args){
int x = 9;
}
}
The image below describes Identifiers in this program:
Rules For Naming Java Identifiers
There are certain rules for defining a valid Java identifier. These
rules must be followed, otherwise, we get a compile-time error.
These rules are also valid for other languages like C and C++.
 The only allowed characters for identifiers are all
alphanumeric characters([A-Z],[a-z],[0-9]), '$'(dollar sign)
and '_' (underscore). For example, "geek@" is not a valid
Java identifier as it contains a '@', a special character.
 Identifiers should not start with digits([0-9]). For example,
"123geeks" is not a valid Java identifier.
 Java identifiers are case-sensitive.
 There is no limit on the length of the identifier, but it is
advisable to use an optimum length of 4 - 15 letters only.
 Reserved Words can't be used as an identifier. For
example, "int while = 20;" is an invalid statement as a
while is a reserved word.
Note: Java has 53 reserved words (including 50 keywords and 3
literals), that are not allowed to be used as identifiers.
Examples of Valid Identifiers
MyVariable
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
geeks123
Examples of Invalid Identifiers
My Variable // contains a space
123geeks // Begins with a digit
a+c // plus sign is not an alphanumeric character
variable-2 // hyphen is not an alphanumeric character
sum_&_difference // ampersand is not an alphanumeric character

Java Keywords
Last Updated : 4 Dec, 2025



In Java, keywords are the reserved words that have some
predefined meanings and are used by the Java compiler for some
internal process or represent some predefined actions. These
words cannot be used as identifiers such as variable names,
method names, class names, or object names.
Now, let us go through a simple example before a deep dive into
the article.
class Geeks {

public static void main(String[] args)


{
// Using final and int keyword
final int x = 10;

// Using if and else keywords


if(x > 10){
[Link]("Failed");
}
else {
[Link]("Successful demonstration"
+" of keywords.");
}
}
}
Output
Successful demonstration of keywords.

What Happens if we use a Variable Name same as


keyword?

Using a keyword as a variable name would give error as shown


below.
class Geeks
{
public static void main(String[] args)
{
String this = "Hello World!";
[Link](this);
}
}
Output:
./[Link]: error: not a statement
String this = "Hello World!";
^
./[Link]: error: ';' expected
String this = "Hello World!";
2 errors
Important Points:
 The keywords const and goto are reserved, even though
they are not currently used in Java.
 true, false, and null look like keywords, but in actuality they
are literals. However, they still can't be used as identifiers
in a program.
 In Java, keywords are case-sensitive, and writing Java
keywords in upper case (like IF instead of if) will throw an
error.

Java Keywords List (As of Java 21)


Java keywords are reserved words that have predefined meanings
in the language. They cannot be used as identifiers (like variable or
method names).
As of Java 21, there are 53 keywords, categorized below by their
usage and purpose.

1. Data Type Keywords

Used to define variable types and specify the kind of data they can
hold.

Keywo
rd Usage

boolea
Defines a variable that holds true or false.
n

byte Defines an 8-bit signed integer.

char Defines a 16-bit Unicode character.

short Defines a 16-bit signed integer.

int Defines a 32-bit signed integer.

long Defines a 64-bit signed integer.

float Defines a 32-bit floating-point number.

double Defines a 64-bit floating-point number.

Specifies that a method does not return any


void value.

2. Control Flow Keywords


Used to control the execution flow of a program, including loops,
branching, and jumps.

Keywo
rd Usage

if Executes code when a condition is true.

Defines an alternate block when an if condition


else is false.

Selects one block of code among multiple


switch options.

Defines an individual branch in


case a switch statement.

default Defines the block executed if no case matches.

for Starts a for loop.

while Starts a while loop.

do Starts a do-while loop.

break Terminates the nearest loop or switch.

continu
Skips to the next iteration of a loop.
e

Exits from a method and optionally returns a


return value.

3. Exception Handling Keywords

Used for handling and managing runtime errors in programs.


Keywo
rd Usage

try Defines a block of code to test for exceptions.

catch Defines a block to handle exceptions thrown by try.

Defines a block that always executes


finally after try and catch.

throw Used to manually throw an exception.

throws Declares the exceptions a method can throw.

Tests assumptions during program execution for


assert debugging.

4. Object-Oriented Keywords

Used to define classes, interfaces, and objects, as well as


inheritance and encapsulation properties.

Keyword Usage

class Declares a class.

interface Declares an interface.

extends Indicates inheritance from a superclass.

impleme
Indicates that a class implements an interface.
nts

new Creates new objects.


Keyword Usage

this Refers to the current object.

super Refers to the superclass of the current object.

Declares a class or method that must be implemented in


abstract a subclass.

final Prevents inheritance, overriding, or modification.

static Declares class-level variables or methods.

sealed Restricts which classes can extend a given class.

permits Specifies the subclasses allowed to extend a sealed class.

5. Access Control Keywords

Define the visibility or accessibility of classes, methods, and


variables.

Keywor
d Usage

public Accessible from anywhere in the program.

protect Accessible within the same package or by


ed subclasses.

private Accessible only within the same class.

6. Package and Import Keywords

Used to organize classes and access external code.


Keywo
rd Usage

packag
Defines a namespace for classes.
e

Allows access to classes from other


import packages.

7. Multithreading and Synchronization Keywords

Used to handle concurrent execution of code and ensure thread


safety.

Keyword Usage

synchroniz Defines critical sections that only one thread can access
ed at a time.

volatile Indicates that a variable may change asynchronously.

8. Memory Management and Object Serialization


Keywords

Handle object persistence, garbage collection, and native method


calls.

Keywo
rd Usage

transie
Excludes a variable from serialization.
nt

Specifies that a method is implemented in native (non-


native Java) code.
9. Modifier and Utility Keywords

Define additional behaviors and precision control.

Keywo
rd Usage

Ensures consistent floating-point calculations across


strictfp platforms.

10. Reserved (Unused) Keywords

These keywords are reserved but not currently used by Java.

Keywo
rd Usage

Reserved for future use; not currently


const implemented.

Reserved for future use; not currently


goto implemented.

11. Special Literals

Keywo
rd Usage

true Represents the boolean value true.

false Represents the boolean value false.

Represents the absence of any reference


null
value.
Java Data Types



Java is a statically typed programming language, meaning variable
types are known at compile time. The compiler ensures type
correctness, preventing assignments like int x = "GfG";, which
would cause a compile-time error.
Data types in Java define the kind of data a variable can hold and
the memory required to store it. They are broadly divided into two
categories:
Primitive Data Types: Store simple values directly in
memory.
 Non-Primitive (Reference) Data Types: Store memory
references to objects.
Data Types in Java

Primitive Data Types


Primitive types are the fundamental data types that store single
values. Java defines eight primitive data types, summarized below:

Descripti Defau
Type on lt Size Example Range

JVM-
depende
Logical
false nt true, false —
boole values
(typically
an 1 byte)

8-bit
signed 0 1 byte 10 -128 to 127
byte integer

16-bit
'A', '\
Unicode \u0000 2 bytes 0 to 65,535
u0041'
char character

16-bit
-32,768 to
signed 0 2 bytes 2000
32,767
short integer

-
32-bit 2,147,483,6
signed 0 4 bytes 1000, -500 48 to
integer 2,147,483,6
int 47

64-bit
123456789
signed 0L 8 bytes ±9.22e18
L
long integer

32-bit
~6–7 digits
floating 0.0f 4 bytes 3.14f
precision
float point

doubl 64-bit 0.0d 8 bytes 3.14159d ~15–16


Descripti Defau
Type on lt Size Example Range

floating digits
e point precision

1. Boolean Data Type

Represents one of two logical values: true or false. Commonly used


for conditional checks.
Syntax:
boolean booleanVar;
public class Geeks {
public static void main(String[] args) {
boolean isJavaFun = true;
boolean isFishTasty = false;
[Link]("Is Java fun? " + isJavaFun);
[Link]("Is fish tasty? " + isFishTasty);
}
}

Output
Is Java fun? true
Is fish tasty? false

2. Byte Data Type

An 8-bit signed integer used to save memory in large numeric


arrays.
Syntax:
byte byteVar;
Size : 1 byte (8 bits)
public class Geeks {
public static void main(String[] args) {
byte age = 25;
byte temperature = -10;
[Link]("Age: " + age);
[Link]("Temperature: " + temperature);
}
}

Output
Age: 25
Temperature: -10

3. Short Data Type

A 16-bit signed integer often used when memory is limited and


values are moderate in size.
Syntax:
short shortVar;
Size : 2 bytes (16 bits)
public class Geeks {
public static void main(String[] args) {
short students = 1000;
short temp = -200;
[Link]("Students: " + students);
[Link]("Temperature: " + temp);
}
}

Output
Number of Students: 1000
Temperature: -200

4. int Data Type

A 32-bit signed integer commonly used for whole numbers.


Syntax:
int intVar;
Size : 4 bytes ( 32 bits )
public class Geeks {
public static void main(String[] args) {
int population = 2000000;
int distance = 150000000;
[Link]("Population: " + population);
[Link]("Distance: " + distance);
}
}
Output
Population: 2000000
Distance: 150000000

5. long Data Type

A 64-bit signed integer used when int is not sufficient for large
values.
Syntax:
long longVar;
Size : 8 bytes (64 bits)
public class Geeks {
public static void main(String[] args) {
long worldPopulation = 7800000000L;
long lightYears = 9460730472580800L;
[Link]("World Population: " +
worldPopulation);
[Link]("Light Years: " + lightYears);
}
}

Output
World Population: 7800000000
Light Year Distance: 9460730472580800

6. float Data Type

A 32-bit single-precision floating-point type used for fractional


values.
Syntax:
float floatVar;
Size : 4 bytes (32 bits)
public class Geeks {
public static void main(String[] args) {
float pi = 3.14f;
float gravity = 9.81f;
[Link]("Pi: " + pi);
[Link]("Gravity: " + gravity);
}
}

Output
Value of Pi: 3.14
Gravity: 9.81

7. double Data Type

A 64-bit double-precision floating-point type and the default for


decimal numbers.
Syntax:
double doubleVar;
Size : 8 bytes (64 bits). It is recommended to go through rounding
off errors in java.
public class Geeks {
public static void main(String[] args) {
double pi = 3.141592653589793;
double avogadro = 6.02214076e23;
[Link]("Pi: " + pi);
[Link]("Avogadro's Number: " + avogadro);
}
}

Output
Value of Pi: 3.141592653589793
Avogadro's Number: 6.02214076E23

8. char Data Type

A 16-bit Unicode character used to store single symbols or letters.


Syntax:
char charVar;
Size : 2 bytes (16 bits)
Example: This example, demonstrates how to use char data type
to store individual characters.
public class Geeks {
public static void main(String[] args) {
char grade = 'A';
char symbol = '$';
[Link]("Grade: " + grade);
[Link]("Symbol: " + symbol);
}
}

Output
Grade: A
Symbol: $

Non-Primitive (Reference) Data Types


Non-primitive data types store references (memory addresses)
rather than actual values. They are created by users and include
types like String, Class, Object, Interface, and Array.

1. String

String represents a sequence of characters enclosed in double


quotes. Unlike C/C++, Java strings are objects and are immutable.
Syntax:
String str = "Hello";
public class Geeks {
public static void main(String[] args) {
String name = "Geek1";
String message = "Welcome to Java";
[Link]("Name: " + name);
[Link]("Message: " + message);
}
}

Output
Name: Geek1
Message: Welcome to Java
Note: String cannot be modified after creation. Use StringBuilder
for heavy string manipulation.

2. Class

A class is a user-defined blueprint that defines variables and


methods. It represents a type of object and forms the foundation of
Object-Oriented Programming.
class Car {
String model;
int year;

Car(String model, int year) {


[Link] = model;
[Link] = year;
}

void display() {
[Link](model + " " + year);
}
}

public class Geeks {


public static void main(String[] args) {
Car myCar = new Car("Toyota", 2020);
[Link]();
}
}

Output
Toyota 2020

3. Object

An Object is an instance of a class representing real-world entities.


It has state (data), behavior (methods), and identity (unique
reference).
class Car {
String model;
int year;

Car(String model, int year) {


[Link] = model;
[Link] = year;
}
}

public class Geeks {


public static void main(String[] args) {
Car myCar = new Car("Honda", 2021);
[Link]("Model: " + [Link]);
[Link]("Year: " + [Link]);
}
}

Output
Car Model: Honda
Car Year: 2021

4. Interface

An interface defines a contract of abstract methods that


implementing classes must define. It provides a way to achieve
abstraction and multiple inheritance in Java.
interface Animal {
void sound();
}

class Dog implements Animal {


public void sound() {
[Link]("Woof");
}
}

public class Geeks {


public static void main(String[] args) {
Animal dog = new Dog();
[Link]();
}
}

Output
Woof

5. Array

An array stores multiple elements of the same type in a single


structure. Java arrays are objects, dynamically allocated, and
indexed from 0.
public class Geeks {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Geek1", "Geek2", "Geek3"};
[Link]("First number: " + numbers[0]);
[Link]("Second name: " + names[1]);
}
}

Output
First number: 1
Second name: Geek2

Java Variables



In Java, variables are containers used to store data in memory.
Variables define how data is stored, accessed, and manipulated.
A variable in Java has three components,
 Data Type: Defines the kind of data stored (e.g., int,
String, float).
 Variable Name: A unique identifier following Java naming
rules.
 Value: The actual data assigned to the variable.
class Geeks {
public static void main(String[] args) {

// Declaring and initializing variables

// Integer variable
int age = 25;

// String variable
String name = "GeeksforGeeks";

// Double variable
double salary = 50000.50;

// Displaying the values of variables


[Link]("Age: " + age);
[Link]("Name: " + name);
[Link]("Salary: " + salary);
}
}
Output
Age: 25
Name: GeeksforGeeks
Salary: 50000.5

How to Declare Java Variables?


The image below demonstrates how we can declare a variable in
Java:

Variable Declaration
From the image, it can be easily perceived that while declaring a
variable, we need to take care of two things that are data type of
the variable and name.

How to Initialize Java Variables?


It can be perceived with the help of 3 components explained above:
Variable Initialization
Example: Here, we are initializing variables of different types like
float, int and char.
class Geeks{
public static void main(String[] args) {
// Declaring and initializing variables

// Initializing float variable


float si = 5.5f;

// Initializing integer variables


int t = 10;
int s = 20;

// Initializing character variable


char var = 'h';

// Displaying the values of the variables


[Link]("Simple Interest: " + si);
[Link]("Speed: " + s);
[Link]("Time: " + t);
[Link]("Character: " + var);
}
}

Output
Simple Interest: 5.5
Speed: 20
Time: 10
Character: h

Rules to Name Java Variables


 Start with a Letter, $, or _ – Variable names must begin with
a letter (a–z, A–Z), dollar sign $, or underscore _.
 No Keywords: Reserved Java keywords (e.g., int, class, if)
cannot be used as variable names.
 Case Sensitive: age and Age are treated as different
variables.
 Use Letters, Digits, $, or _ : After the first character, you
can use letters, digits (0–9), $, or _.
 Meaningful Names: Choose descriptive names that
reflect the purpose of the variable (e.g., studentName
instead of s).
 No Spaces: Variable names cannot contain spaces.
 Follow Naming Conventions: Typically, use camelCase
for variable names in Java (e.g., totalMarks).
Java Operators



Java operators are special symbols that perform operations on
variables or values. These operators are essential in programming
as they allow you to manipulate data efficiently.

Java-Operator
1. Arithmetic Operators
Arithmetic Operators are used to perform simple arithmetic
operations on primitive and non-primitive data types.
public class GFG{
public static void main(String[] args) {
int a = 10, b = 3;

// Addition
int sum = a + b;

// Subtraction
int diff = a - b;

// Multiplication
int mul = a * b;

// Division
int div = a / b;

// Modulus
int mod = a % b; // Modulus

[Link]("Sum: " + sum);


[Link]("Difference: " + diff);
[Link]("Multiplication: " + mul);
[Link]("Division: " + div);
[Link]("Modulus: " + mod);
}
}

Output
Sum: 13
Difference: 7
Multiplication: 30
Division: 3
Modulus: 1

2. Unary Operators
Unary Operators need only one operand. They are used to
increment, decrement, or negate a value.
import [Link].*;

// Driver Class
class Geeks{

public static void main(String[] args){

// Integer declared
int a = 10;
int b = 10;
// Using unary operators
[Link]("Postincrement : " + (a++));
[Link]("Preincrement : " + (++a));

[Link]("Postdecrement : " + (b--));


[Link]("Predecrement : " + (--b));
}
}

Output
Postincrement : 10
Preincrement : 12
Postdecrement : 10
Predecrement : 8

3. Assignment Operator
The assignment operator assigns a value from the right-hand side
to a variable on the left. Since it has right-to-left associativity, the
right-hand value must be declared or constant.
public class GFG{
public static void main(String[] args){

int n = 10;

// n = n + 5
n += 5;
[Link]("After += : " + n);

// n = n * 2
n *= 2;
[Link]("After *= : " + n);

// n = n - 5
n -= 5;
[Link]("After -= : " + n);

// n = n / 2
n /= 2;
[Link]("After /= : " + n);

// n = n % 3
n %= 3;
[Link]("After %= : " + n);
}
}

Output
After += : 15
After *= : 30
After -= : 25
After /= : 12
After %= : 0
Note: Use compound assignments (+=, -=) for cleaner code.
4. Relational Operators
Relational Operators are used to check for relations like equality,
greater than, and less than. They return boolean results after the
comparison and are extensively used in looping statements as well
as conditional if-else statements.
import [Link].*;

class Geeks{

public static void main(String[] args){

// Comparison operators
int a = 10;
int b = 3;
int c = 5;

[Link]("a > b: " + (a > b));


[Link]("a < b: " + (a < b));
[Link]("a >= b: " + (a >= b));
[Link]("a <= b: " + (a <= b));
[Link]("a == c: " + (a == c));
[Link]("a != c: " + (a != c));
}
}

Output
a > b: true
a < b: false
a >= b: true
a <= b: false
a == c: false
a != c: true

5. Logical Operators
Logical Operators are used to perform "logical AND" and "logical
OR" operations, similar to AND gate and OR gate in digital
electronics. They have a short-circuiting effect, meaning the
second condition is not evaluated if the first is false.
import [Link].*;

class Geeks {

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

// Logical operators
boolean x = true;
boolean y = false;

[Link]("x && y: " + (x && y));


[Link]("x || y: " + (x || y));
[Link]("!x: " + (!x));
}
}

Output
x && y: false
x || y: true
!x: false

6. Ternary operator
The Ternary Operator is a shorthand version of the if-else
statement. It has three operands and hence the name Ternary. The
general format is,
public class Geeks{

public static void main(String[] args){

int a = 20, b = 10, c = 30, result;

// result holds max of three


// numbers
result = ((a > b) ? (a > c) ? a : c : (b > c) ? b : c);
[Link]("Max of three numbers = "+ result);
}
}

Output
Max of three numbers = 30

7. Bitwise Operators
These operators perform operations at the bit level.
 Bitwise Operators manipulate individual bits using AND, OR,
XOR, and NOT.
 Shift Operators move bits to the left or right, effectively
multiplying or dividing by powers of two.

import [Link].*;

class Geeks
{
public static void main(String[] args)
{
// Bitwise operators
int d = 0b1010;
int e = 0b1100;

[Link]("d & e : " + (d & e));


[Link]("d | e : " + (d | e));
[Link]("d ^ e : " + (d ^ e));
[Link]("~d : " + (~d));
[Link]("d << 2 : " + (d << 2));
[Link]("e >> 1 : " + (e >> 1));
[Link]("e >>> 1 : " + (e >>> 1));
}
}

Output
d & e : 8
d | e : 14
d ^ e : 6
~d : -11
d << 2 : 40
e >> 1 : 6
e >>> 1 : 6

8. instanceof Operator
The instanceof operator is used for type checking. It can be used to
test if an object is an instance of a class, a subclass, or an
interface. The general format,
public class GFG{

public static void main(String[] args){

String str = "Hello";


[Link](str instanceof String);

Object obj = new Integer(10);


[Link](obj instanceof Integer);
[Link](obj instanceof String);
}
}

Output
true
true
false

Common Mistakes to Avoid

The common mistakes that can occur when working with Java
Operators are listed below:
 Confusing == with =: Using == for assignment instead
of = for equality check leads to logical errors.
 Incorrect Use of Floating-Point
Comparison: Comparing floating point numbers using ==
can lead to unexpected results due to precision issues.
 Integer Division Confusion: Dividing two integers will
result in integer division (truncating the result).
 Overusing + for String Concatenation in Loops: Using
+ for concatenating strings in loops leads to performance
issues because it creates new string objects on each
iteration.

You might also like