0% found this document useful (0 votes)
9 views101 pages

Java Week 1 Part 1

Week 1 of the Java programming course introduces the fundamentals of Java, including its features, environment setup, and basic syntax. Participants will engage in practical exercises, culminating in a mini project to build a Tic-Tac-Toe game. The course also covers key components like JDK, JRE, and JVM, and provides guidance on installing the JDK on various operating systems.

Uploaded by

guptabhai903
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views101 pages

Java Week 1 Part 1

Week 1 of the Java programming course introduces the fundamentals of Java, including its features, environment setup, and basic syntax. Participants will engage in practical exercises, culminating in a mini project to build a Tic-Tac-Toe game. The course also covers key components like JDK, JRE, and JVM, and provides guidance on installing the JDK on various operating systems.

Uploaded by

guptabhai903
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 101

Week 1: Course Overview

Welcome to Week 1 of your Java programming journey! This week lays the
foundation for everything you'll build ahead from understanding what Java is to
writing your first program. Through beginner-friendly explanations, practical coding
exercises and consistent daily learning, you'll gain the confidence and clarity to start
developing real-world Java applications from scratch.
Day 1 – Java Basics and Features
Get introduced to Java, its core principles and why it's one of the most widely used
programming languages.
• What is Java?
• Features of Java
• JDK, JRE and JVM

Day 2 – Environment Setup and Hello World


Install everything you need to start writing Java code and run your first program.
• Install JDK and Set Environment Variables
• Write Your First Java Program
• Java Program Structure & Execution Flow
Day 3 – Java Syntax and Data Types
Learn the basic building blocks of Java syntax and how to work with different data
types.
• Basic Syntax
• Identifiers
• Data Types

Day 4 – Variables and Type Casting


Discover how Java stores data using variables and how to convert between different
data types.
• Variables
• Literals
• Type Casting
Day 5 – Operators and Input/Output
Use Java operators to perform calculations and take user input using standard
methods.
• Operators and Expressions
• Input/Output in Java

Day 6 – Conditional and Looping Constructs


You can add logic to your Java programs with decision -making and loops.
• Conditional Statements
• Loops in Java
Day 7 – Mini Project: Tic-Tac-Toe Game
• Put your knowledge to the test by building a simple console-based Tic-Tac-Toe
game in Java.
• Apply variables, conditionals, loops and I/O in a real-world project.
• Practice clean code formatting and logical thinking.
 INTRODUCTION
Java is a high-level, object-oriented programming language developed by Sun
Microsystems in 1995. It is platform-independent, which means we can write code
once and run it anywhere using the Java Virtual Machine (JVM). Java is mostly used
for building desktop applications, web applications, Android apps, and
enterprise systems.
Key Features of Java
• Platform Independent: Java is famous for its Write Once, Run Anywhere
(WORA) feature. This means we can write our Java code once, and it will run on any
device or operating system without changing anything.
• Simple: Java syntax is very straightforward and very easy to learn. Java
removes complex features like pointers and multiple inheritance, which makes it a good
choice for beginners.
• Object-Oriented: Java follows the object-oriented programming. This makes
code clean and reusable.
• Secured: Java does not support pointers, it includes built-in protections to keep
our programs secure from common problems like memory leakage.
• Multithreading: Java programs can do many things at the same time using
multiple threads. This is useful for handling complex tasks like processing transactions.
• Just-In-Time (JIT) Compiler: Java uses a JIT compiler. It improves performance
by converting the bytecode into machine readable code at the time of execution.

Understanding 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.
Java Hello World Program:
// This is a simple Java program to print Hello World!
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
Output
Hello World!
How does this work:
• // starts a single-line comment. The comments does not executed by Java.
• public class HelloWorld defines a class named HelloWorld. In Java, every
program must be inside a class.
• public static void main(String[] args) is the entry point of any Java application.
It tells the JVM where to start executing the program.
• System.out.println("Hello, World!"); prints the message to the console.
Java program execution follows this below simple flow:

• Write code in a file like HelloWorld.java.


• The Java Compiler "javac" compiles it into bytecode "HelloWorld.class".
• The 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.
To understand Hello World program in detail, refer to article: Java Hello World
Program
Comments in Java
The 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) {
{
System.out.println("This is inside the block.");
}

System.out.println("This is outside the block.");


}
}

• The code block inside {} runs unconditionally and prints a message.


• Curly brackets {} group multiple statements into a single block, even without
conditions.
Naming Conventions in Java
• Java uses standard naming rules that make the code easier and improves the
readability.
• In Java, the class names start with a capital letter for example, HelloWorld.
Method and variable names start with a lowercase letter and use camelCase like
printMessage.
• And the constants are written in all uppercase letters with underscores like
MAX_SIZE.
To understand Naming convention in Java in detail, refer to article: Java Naming
Convention

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 Boot and Jakarta EE.
• Desktop GUI Applications: With libraries like JavaFX and Swing.
• Enterprise Applications: Java is the backbone of many banking and business
software.
• Game Development: Through game engines like LibGDX.
• 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.

Differences Between JDK, JRE and JVM


Understanding the difference between JDK, JRE, and JVM plays
a vital role in understanding how Java works and how each
component contributes to the development and execution of Java
applications.
• JDK: JDK stands for Java Development Kit. It is a set of
development tools and libraries used to create Java programs. It
works together with the JVM and JRE to run and build Java
applications..
• JRE: JRE stands for Java Runtime Environment, and it
provides an environment to run Java programs on the system. The
environment includes Standard Libraries and JVM.
• JVM: JVM stands for Java Virtual Machine. It's responsible for
executing the Java program.
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- Platform- specific, but
Dependen dependent (OS dependent (OS bytecode is
cy specific) specific) platform-
independent

JRE +
ClassLoader, JIT
Development tools JVM + Libraries
Includes Compiler, Garbage
(javac, debugger, (e.g., rt.jar)
Collector
etc.)

Writing and Running a Java Convert bytecode


Use Case compiling Java application on a into native
code system machine code

Note: The JVM is platform-independent in the sense that the


bytecode can run on any machine with a JVM, but the actual JVM
implementation is platform-dependent. Different operating systems
(e.g., Windows, Linux, macOS) require different JVM
implementations that interact with the specific OS and hardware
We have discussed the core differences, now let's take a
closer look at each component. Let, us discuss them in brief
first and interrelate them with the image below proposed.
JDK (Java Development Kit)
The JDK is a software development kit that provides tools to
develop and run Java applications. It includes two main
components:
• Development Tools (to provide an environment to develop your
java programs)
• JRE (to execute your java program)
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
The JDK enables the development and execution of Java
programs. Consider the following process:
• Java Source File (e.g., Example.java): You write the Java
program in a source file.
• Compilation: The source file is compiled by the Java Compiler
(part of JDK) into bytecode, which is stored in a .class file (e.g.,
Example.class).
• Execution: The bytecode is executed by the JVM (Java Virtual
Machine), which interprets the bytecode and runs the Java program.

Working of JDK

Note: From above, media operation computing during the compile


time can be interpreted.

The following actions occur at runtime as listed below:


• Class Loader
• Byte Code Verifier
• Interpreter
o Execute the Byte Code
o Make appropriate calls to the underlying hardware
JRE ((Java Runtime Environment)
The JRE is an installation package that provides an environment to
only run(not develop) the Java program (or application) onto your
machine. JRE is only used by those who only want to run Java
programs that are end-users of your system.
Note:
• JRE is only for end-users (not for developers).
• JRE is platform-dependent (different versions for different OS)
Working of JRE
When you run a Java program, the following steps occur:
• Class Loader: The JRE’s class loader loads the .class file
containing the bytecode into memory.
• Bytecode Verifier: JRE includes a bytecode verifier to ensure
security before execution
• Interpreter: JVM uses an interpreter + JIT compiler to execute
bytecode for optimal performance
• Execution: The program executes, making calls to the
underlying hardware and system resources as needed.
JVM (Java Virtual Machine)
The JVM is a very important part of both JDK and JRE because it is
contained or inbuilt in both. Whatever Java program you run using
JRE or JDK goes into JVM and JVM is responsible for executing
the java program line by line, hence it is also known as an
interpreter.
Note:
• JVM is platform -dependent (different JVMs for window, linux,
macOS).
• Bytecode (.class files) is platform-independent (same file runs in
any JVM).
• While JVM includes an interpreter, modern implementations
primarily use JIT compilation for faster execution
Working of JVM
It is mainly responsible for three activities.
• Loading
• Linking
• Initialization
JVM Working

Download and Instal JDK on Windows, Mac, and Linux

Java Development Kit (JDK) is one of the most important tools for developers who use it to
build, compile, and run Java applications. It does not matter if you are a beginner or an
experienced programmer; installing JDK is the first step towards working with Java development.
We can download JDK to create and run Java applications on our system. Also, the JDK is used
to create Android application source files as well, using the Java or Kotlin pr ogramming
language. There are multiple benefits of installing a JDK.
Key Features of JDK:
• Compiler (javac): Converts Java code into bytecode for JVM execution.
• JRE + JVM: Includes runtime environment to execute Java programs.
• Rich Libraries: Pre-built classes for I/O, networking, databases, and more.
• Debugging Tools: JDK provides JDB (Java Debugger) for troubleshooting code.
• Multi-Platform Support: JDK supports write-once, run anywhere (Windows, Linux, macOS).
The system will execute the code using a set of Libraries and Compilers. JDK, JRE, and JVM
should not be confused with one another.
Refer to this article to learn more: Differences between JDK, JRE, and JVM.
Why Install JDK?
• To develop and run Java applications
• Compile Java source code (javac)
• Includes JRE (Java Runtime Environment) and JVM (Java Virtual Machine)
• Required for Android app development (Java/Kotlin)
This article describes the step-by-step process for installing and configuring the JDK on
Windows, Mac, and Linux.
Java JDK Download
The JDK can be installed on the following Platforms:
1. Microsoft Windows
2. Linux
3. macOS
Download JDK (Java Development Kit)
We need to download the JDK first, find the steps below to get started:
Step 1: Visit the Official Website

o to the Official JDK website to download the file.


Oracle Official Website
Since JDK is an open source, so you can get it from OpenJDK in a few clicks.
OpenJDK

Step 2: Select the Appropriate Version


As of 2025, the latest stable versions are JDK 23 (SE) and JDK 21 (LTS). Select the compatible
version as per your operating system (Windows, Mac or Linux)
JDK Latest Version - Download

Step 3: License and Agreement


Go through all the License and Agreement before downloading (from Oracle website), it will not
ask if you'll download it from OpenJDK website.
Install JDK on Windows
Follow the below steps to install JDK on Windows environment i.e.Windows 7, Windows 8,
Windows 8.1, Windows 10, and Windows 11.
Step 1: Run the Java Development Kit (JDK) Installer
Locate the downloaded .exe file (e.g. jdk-23-windows-x64_bin.exe) and make the double click
to begin the Installation process. Follow the installation wizard prompts to complete the
installation process.

JDK Installer for Windows

Step 2: Setup the Environment Variables


Once the installation gets completed, you need to configure environment variables to notify the
system about the directory in which the JDK files are located.
Proceed to C:\Program Files\Java\jdk-{YOUR_JDK_VERSION}\bin (replace {-} with your JDK
version)
Program Files

Step 2.1: To set the Environment Variables, you need to search Environment Variables in the
Task Bar and click on “Edit the system environment variables”.
System
Properties

Step 2.2: Under the Advanced section, Click on "Environment Variables".


Environment Variables

Step 2.3: Under System variables, select the "Path" variable and click on "Edit". Click on
"New" then paste the Path Address i.e. C:\Program Files\Java\jdk-
{YOUR_JDK_VERSION}\bin. Click on "OK".

Path
Step 2.4: Now, in the Environment Variables dialogue, under System variables, click on
"New" and then under Variable name: JAVA_HOME and Variable value: paste address i.e.
C:\Program Files\Java\jdk-{YOUR_JDK_VERSION}. Click on OK => OK => OK.

System Properties

Step 3: Check the Java Version


Open Command Prompt and enter the following commands:
java -version
javac -version

Command Prompt
Install JDK on Linux
Follow the steps below to install the Java software Development Kit on a Linux environment.
These instructions are applicable to various Linux distributions such as Ubuntu, Fedora, and
CentOS.
Note: We have used Kali Linux distributions here.
Step 1: Install Oracle Java Development Kit (JDK)
To install the downloaded JDK File using terminal, Open terminal and change your directory to
downloads by using the command:
$ cd downloads
To list files and packages present in the directory, Type
$ ls

Root Kali

Step 1.1: Now we use Debian Package Manager to configure our downloaded file for
installation by typing
$ sudo dpkg -i jdk-{YOUR_JDK_VERSION} (replace {-} with your version)
Enter your password as we have run an elevated prompt, i.e. the sudo or superuser do
command, which is a quick way to grant specific users permission to perform specific system
commands at the system's root (most powerful) level.

Kali Linux

Step 1.2: Now, Type the following commands to proceed with the installation
$ sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/jdk-
{YOUR_JDK_VERSION}/bin/java 1
$ sudo update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/jdk-
{YOUR_JDK_VERSION}/bin/javac 1

Step 2: Check the Java Version


Open the terminal and enter the following commands
$ java --version
$ javac --version

sudo

Step 3: Configure JAVA_HOME Environment Variable


After the installation is complete, we have to configure environment variables to notify the system
about the directory in which jdk files are located. To find the Location of the JDK Files, run this
command and copy the File Location.
$ sudo update-alternatives --config java
In order to set the environment variable, you need to edit the environment file using the following
command:
$ sudo gedit /etc/environment

Step 3.1: Proceed to add JAVA_HOME=” /usr/lib/jvm/jdk-{YOUR_JDK_VERSION}”


Proceed to save and close the file.
environment

Step 3.2: Now we have to refresh the environment file by using this command:
$ SOURCE /etc/environment
And echo the JAVA_HOME Path
JAVA_HOME

Install JDK on macOS


Follow the steps below to install the Java Development Kit (JDK) on macOS. These instructions
are compatible with various versions of macOS, including Mojave, Catalina, Big Sur, Monterey,
Ventura, Sonoma the latest macOS Sequoia.
Step 1: Install Oracle Java Development Kit (JDK)
Proceed to Install the JDK kit by following the bootstrapped steps:

Installation

Step 2: Configure Environment Variables


Open the terminal and pass the following commands. To find the Location of the JAVA_HOME,
run this command:
$ /usr/libexec/java_home -v{YOUR_VERSION}
Configure

Step 2.1: We have to set this output as our JAVA_HOME Environment Variable. You can use
any command or code editor to edit the file, here we are using VS Code
$ code ~/. bash_profile

Terminal

Step 2.2: At the very bottom, we have to export the path we obtained earlier i.e.
$ export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-
{YOUR_VERSION}.jdk/Contents/Home

bash

Step 2.3: Now we have to refresh the environment file by using this command:
$ source ~/.bash_profile
And echo the JAVA_HOME variable
JAVA_HOME
Java HOME

Step 3: Verify the Java Version


In the terminal, enter the following commands
$ java -version
$ javac -version

javac

Advanatages of JDK
The Advanatages of JDK are listed below:
• Complete Development Kit: It Includes compiler (javac), JRE, JVM, and debugging tools.
• Platform Independence: It write once, run anywhere (WORA) using JVM.
• Rich Libraries & APIs: JDK has built-in support for networking, I/O, databases, and more.
• Performance Optimization: Just-In-Time (JIT) compiler boosts execution speed.
• Backward Compatibility: Older Java apps still run on newer JDK versions.
Disadvantages of JDK
The disadvantages of JDK are listed below:
• Large Memory Usage: JDK consumes more RAM compared to some lightweight
languages.
• Complex Setup: Requires manual environment variable configuration.
• Slower Startup Time: JVM initialization can delay execution.
• License Restrictions: Oracle JDK requires a commercial license for business use.
Conclusion
Installing the latest JDK version is a simple process, whether you're on Windows, macOS or
Linux. By following this guide, you can setup JDK and start developing Java applications in just a
few steps. You can easily download the latest jdk 23 in your system and start with Java
development today.
Java Hello World Program

Java is one of the most popular and widely used programming languages and
platforms. In this article, we will learn how to write a simple Java Program. This
article will guide you on how to write, compile, and run your first Java program. With
the help of Java, we can develop web and mobile applications.
In this article, we will learn:
• How to create your first Java program
• How to compile and run Java code
• Understanding the Hello World program structure
Prerequisites:
• Download install JDK.
• Download install intelliJ
Implementation of Java Hello World
The below-given program is the most simple program of Java printing "Hello World"
to the screen. Let us try to understand every bit of code step by step.
// Simple Java program
// FileName: "HelloWorld.java"
public class HelloWorld
{
// Your program begins with a call to main(). // Prints "Hello, World" to the terminal window.
public static void main(String[] args)
{
System.out.println("Hello, World");
}}

Output
Hello, World

Understanding the Java Hello World Program


1. Class Definition
Every Java program must have at least one class. Here, the class is defined using
the class keyword:
public class HelloWorld {
// Statements go here
}
Note: If the class is public, the filename must match the class name
HelloWorld.java
2. main Method
In the Java programming language, every application must contain a main method
as it is the entry point of the application:
public static void main(String[] args)
• public: Allows JVM to access the method from anywhere.
• static: Method can run without creating an object.
• void: It doesn’t return any value.
• String[] args: Accepts command-line arguments.
3. System.out.println()
This prints output to the console.
System.out.println("Hello, World");
• System: Built-in class from java.lang package.
• out: Static member (PrintStream object) of System.
• println(): Method that prints to console and moves to the next line.
Steps to Implement a Java Program
Java is a platform-independent language that follows a two-step execution process:
• Compilation (source code → bytecode)
• Execution (bytecode → machine code via JVM)
1. Compilation in Java
Java source code (.java files) is compiled by the Java Compiler (javac) into
Bytecode, stored in .class files. This bytecode is platform-independent and ready to
run on any system with a JVM.
• Internally, compilation involves:
• Parsing: Converts code into syntax trees (AST).
• Entering: Populates symbol tables.
• Annotation Processing: Handles annotations.
• Attribution: Performs type checking and name resolution.
• Flow Analysis: Checks for variable use and reachability.
• Desugaring: Removes syntactic shortcuts.
• Generation: Produces .class files.
2. Execution via JVM
The .class files are executed by the Java Virtual Machine (JVM), which includes the
following stages:
a. Class Loader
Loads the main class and other dependencies into memory.
• Primordial Loader: Default system loader.
• Non-primordial Loader: Custom loaders for advanced control.
Class r = loadClass(String className, boolean resolveIt);
b. Bytecode Verifier
Checks that the loaded bytecode is safe to execute. It ensures:
• Variables are initialized
• Method signatures are correct
• Private access rules aren’t violated
• No stack overflows
c. Just-In-Time (JIT) Compiler
Converts bytecode into native machine code at runtime for faster execution.

Just In Time (JIT)


Java Compilation & Execution Example
// Java Program to Illustrate Compilation and Execution
class GFG { public static void main(String[] args) { System.out.print("Hello, World"); }}
Steps:
1. Create file: Save above code as GFG.java
2. Open terminal and navigate to file location
3. Compile the program:
javac HelloWorld.java
4. Run the compiled file:
java HelloWorld
Output
Welcome to Geeks
1. In Windows
Shell
2. In Linux

Shell
Note: If you get ClassNotFoundException, ensure the .class file is in the correct
directory or check your CLASSPATH.
Comments
They can either be multiline or single-line comments.
// Simple Java program
// FileName: "HelloWorld.java"
This is a single-line comment. This type of comment must begin with // as in C/C++.
For multiline comments, they must begin from /* and end with */.
/*
This is a
multi-line comment
*/

Structure and Members in a Java Program


In Java, a program follows a specific structure recommended by the
language. It usually consists of one or more classes, with one class
containing the main method, which is where the program starts
running. Inside these classes, you will find data members
(variables) and methods that define the actions to be performed on
that data.
Basic Blocks of a Java Program
To write a Java program, we first need to define classes and then
put them together. Generally, a standard Java program consists of
the following blocks, as shown below:
package list;public class ClassName
{
// Data members
// Constructor functions
// User-defined methods
public static void main(String[] arguments)
{
// Block of statements }}
Explanation:
• Package: A package groups related classes, interfaces, and
sub-packages. To use pre-defined classes from other packages, a
programmer needs to import those packages. Java automatically
imports the java.lang.* package by default.
• Class: A class is a user-defined data type. Every Java program
starts with at least one class definition. If we declare a class as
public, it means it is accessible from another package.
• Class name: It is the name given to that class; it acts like a new
data type that we can use to create objects.
• Data members: Data members are variables declared inside a
class.
• Constructor: A constructor is a special block of code that runs
automatically when we create a new object from a class. The main
task of a constructor is to initialize the new object. Always remember
the constructor name must be the same as the class name, also it
does not have any return type. .
User-Defined Methods
User-defined methods in Java can be instance or static and contain
the core logic of the program. The main() method is the starting
point of every Java program, must be public static void, and takes a
String[] as an argument.
Types of Data Members
Java Class is a collection of data members and functions. Any Java
program may contain two types of data members.
• Instance or non-static data members
• Static or class data members
Instance Data Members vs Static Data Members
The table below demonstrates the difference between Instance
data member and Static data memeber.
Instance Data Members Static Data Members

Memory is allocated every time an object is Memory is allocated only once when the class i
created. loaded.

Each object has its own copy of instance


All objects share a single copy of static variable
variables.

Declared without the static keyword Declared using the static keyword.

Accessed using the object name Accessed using the class name

It is known as Object-level data members. It is Known as Class-level data members.

Value can be different for each object. Value is common for all objects of the class.

❖ Types of Methods
In Java programs generally, we may define two types of methods
apart from the constructor.
• Instance or non-static methods
• Static or class methods
Instance Methods vs Static Methods
The table below demonstrates the difference between Instance
methods and Static methods.
Instance Methods Static Methods

Used to perform tasks related to Used to perform operations that are


individual objects, such as reading related to the class as a whole, such
records from a file or processing as utility functions or managing shared
object-specific data. resources.

Must include the static keyword in their


Do not require the static keyword in
definition.
their definition.
Syntax: static void
Syntax: void net_salary(parameters)
basic_salary(parameters)
{ statements; }
{ statements; }

Accessed through an object of the


Accessed through the class name.
class

Can access both instance variables Cannot access instance variables or


and static variable methods without an object reference.

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.
Example:
public class Test
{
public static void main(String[] args)
{
int a = 20;
}}
In the above Java code, we have 5 identifiers as follows:
• Test: Class Name
• main: Method Name
• String: Predefined Class Name
• args: Variable Name
• a: Variable Name
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
Reserved Words in Java
Any programming language reserves some words to represent
functionalities defined by that language. These words are called
reserved words. They can be briefly categorized into two parts:
• Keywords (50): Keywords define functionalities. The below table
shows list of 50 keywords.
• literals (3): Literals define value. The three literals are, true,
false and null.
Identifiers are stored by symbol tables and used during the
lexical, syntax, and semantic analysis phase of compilation.
List of Java Reserved Words
abstra continu
for protected transient
ct e

Assert Default Goto public Try

Boolea
Do If Static throws
n

implemen
break double strictfp Package
ts

byte else import super Private

case enum Interface Short switch

Extend instanceo
Catch return void
s f

synchroniz
Char Final Int volatile
ed

class finally long throw Date

const float Native This while

Note: The keywords const and goto are reserved, even though
they are not currently used in Java. In place of const, the final
keyword is used. Some keywords like strictfp are included in later
versions of Java.

Java Data Types


Java is statically typed programming language which means variable types are
known at the compile time.
• In Java, compiler knows exactly what types each variable holds and enforces
correct usage during compilation. For example " int x = "GfG";" gives compiler error in
Java as we are trying to store string in an integer type.
• Data types in Java are of different sizes and values that can be stored in a
variable that is made as per convenience and circumstances to handle different
scenarios or data requirements.
Why Data Types Matter in Java?
Data types matter in Java because of the following reasons, which are listed below:
• Memory Efficiency: Choosing the right type (byte vs int) saves memory.
• Performance: Proper types reduce runtime errors.
• Code Clarity: Explicit typing makes code more readable.
Java Data Type Categories
Java has two categories in which data types are segregated
1. Primitive Data Type: These are the basic building blocks that store simple values
directly in memory. Examples of primitive data types are
• boolean
• char
• byte
• short
• int
• long
• float
• double
Note: The Boolean with uppercase B is a wrapper class for the primitive boolean
type.
2. Non-Primitive Data Types (Object Types): These are reference types that store
memory addresses of objects. Examples of Non -primitive data types are
• String
• Array
• Class
• Interface
• Object
The below diagram demonstrates different types of primitive and non-primitive
data types in Java.
❖ Primitive Data Types in Java
Primitive data store only single values and have no additional capabilities. There are
8 primitive data types. They are depicted below in tabular format below as follows:
Def Example
Type Description Size Range of values
ault Literals

JVM-
depende
boolea fals
true or false nt true, false true, false
n e
(typically
1 byte)

8-bit signed
byte 0 1 byte (none) -128 to 127
integer

Unicode 'a', '\u0041',


\u00
char character(16 2 bytes '\101', '\', '\', 0 to 65,535 (unsign
00
bit) '\n', 'β'

16-bit signed
short 0 2 bytes (none) -32,768 to 32,767
integer

-2,147,483,648
32-bit signed
int 0 4 bytes -2,0,1 to
integer
2,147,483,647

-
9,223,372,036,854,7
64-bit signed 8
long 0L 8 bytes -2L,0L,1L
integer to
9,223,372,036,854,7
7

32-bit IEEE
3.14f, - ~6-7 significant
float 754 floating- 0.0f 4 bytes
1.23e-10f digits
point

64-bit IEEE 3.1415d, ~15-16 significant


double 754 floating- 0.0d 8 bytes
1.23e100d digits
point

1. boolean Data Type


The boolean data type represents a logical value that can be either true or false.
Conceptually, it represents a single bit of information, but the actual size used by the
virtual machine is implementation-dependent and typically at least one byte (eight
bits) in practice. Values of the boolean type are not implicitly or explicitly converted
to any other type using casts. However, programmers can write conversion code if
needed.
Syntax:
boolean booleanVar;
Size : Virtual machine dependent (typically 1 byte, 8 bits)
Example: This example, demonstrating how to use boolean data type to display
true/false values.
// Demonstrating boolean data type
public class Geeks {
public static void main(String[] args)
{
boolean b1 = true;
boolean b2 = false;
System.out.println("Is Java fun? " + b1);
System.out.println("Is fish tasty? " + b2);
}}
OutputIs
Java fun? true
Is fish tasty? false

2. byte Data Type


The byte data type is an 8-bit signed two's complement integer. The byte data type
is useful for saving memory in large arrays.
Syntax:
byte byteVar;
Size : 1 byte (8 bits)
Example: This example, demonstrating how to use byte data type to display small
integer values.
// Demonstrating byte data type
public class Geeks {
public static void main(String[] args)
{
byte a = 25;
byte t = -10;
System.out.println("Age: " + a);
System.out.println("Temperature: " + t);
}}
Output
Age: 25
Temperature: -10

3. short Data Type


The short data type is a 16-bit signed two's complement integer. Similar to byte, a
short is used when memory savings matter, especially in large arrays where space
is constrained.
Syntax:
short shortVar;
Size : 2 bytes (16 bits)
Example: This example, demonstrates how to use short data type to store
moderately small integer value.
// Demonstrating short data types
public class Geeks {
public static void main(String[] args) {
short num = 1000;
short t = -200;
System.out.println("Number of Students: " + num); System.out.println("Temperature: "
+ t); }}

Output
Number of Students: 1000
Temperature: -200

4. int Data Type


It is a 32-bit signed two's complement integer.
Syntax:
int intVar;
Size : 4 bytes ( 32 bits )
Remember: In Java SE 8 and later, we can use the int data type to represent an
unsigned 32-bit integer, which has a value in the range [0, 2 32 -1]. Use the Integer
class to use the int data type as an unsigned integer.
Example: This example demonstrates how to use int data type to display larger
integer values.
// Demonstrating int data types
public class Geeks {
public static void main(String[] args)
{
int p = 2000000;
int d = 150000000;
System.out.println("Population: " + p);
System.out.println("Distance: " + d);
}}

Output
Population: 2000000
Distance: 150000000

5. long Data Type


The long data type is a 64-bit signed two's complement integer. It is used when an
int is not large enough to hold a value, offering a much broader range.
Syntax:
long longVar;
Size : 8 bytes (64 bits)
Remember: In Java SE 8 and later, you can use the long data type to represent an
unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 2 64 -
1. The Long class also contains methods like comparing Unsigned, divide Unsigned,
etc to support arithmetic operations for unsigned long.
Example: This example demonstrates how to use long data type to store large
integer value.
// Demonstrating long data type
public class Geeks {
public static void main(String[] args)
{
long w = 7800000000L;
long l = 9460730472580800L;
System.out.println("World Population: " + w);
System.out.println("Light Year Distance: " + l);
}}

Output
World Population: 7800000000
Light Year Distance: 9460730472580800

6. float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float
(instead of double) if you need to save memory in large arrays of floating-point
numbers. The size of the float data type is 4 bytes (32 bits).
Syntax:
float floatVar;
Size : 4 bytes (32 bits)
Example: This example demonstrates how to use float data type to store decimal
value.
// Demonstrating float data type
public class Geeks {
public static void main(String[] args)
{
float pi = 3.14f;
float gravity = 9.81f;
System.out.println("Value of Pi: " + pi);
System.out.println("Gravity: " + gravity);
}}

Output
Value of Pi: 3.14
Gravity: 9.81

7. double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating-point. For
decimal values, this data type is generally the default choice. The size of the double
data type is 8 bytes or 64 bits.
Syntax:
double doubleVar;
Size : 8 bytes (64 bits)
Note: Both float and double data types were designed especially for scientific
calculations, where approximation errors are acceptable. If accuracy is the most
prior concern then, it is recommended not to use these data types and use
BigDecimal class instead.
It is recommended to go through rounding off errors in java.
Example: This example demonstrates how to use double data type to store precise
decimal value.
// Demonstrating double data type
public class Geeks {
public static void main(String[] args)
{ double pi = 3.141592653589793;
double an = 6.02214076e23;
System.out.println("Value of Pi: " + pi);
System.out.println("Avogadro's Number: " + an);
}}

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

8. char Data Type


The char data type is a single 16-bit Unicode character with the size of 2 bytes (16
bits).
Syntax:
char charVar;
Size : 2 bytes (16 bits)
Example: This example, demonstrates how to use char data type to store individual
characters.
// Demonstrating char data type
public class Geeks{
public static void main(String[] args)
{
char g = 'A';
char s = '$';
System.out.println("Grade: " + g);
System.out.println("Symbol: " + s);
}}

Output
Grade: A
Symbol: $

Why is the Size of char 2 bytes in Java?


Unlike languages such as C or C++ that use the ASCII character set, Java uses the
Unicode character set to support internationalization. Unicode requires more than 8
bits to represent a wide range of characters from different languages, including
Latin, Greek, Cyrillic, Chinese, Arabic, and more. As a result, Java uses 2 bytes to
store a char, ensuring it can represent any Unicode character.
Example: Here we are demonstrating how to use various primitive data types.
// Java Program to Demonstrate Char Primitive Data Type
class Geeks {
public static void main(String args[])
{
// Creating and initializing custom character
char a = 'G';
// Integer data type is generally
// used for numeric values
int i = 89;
// use byte and short
// if memory is a constraint
byte b = 4;
// this will give error as number is
// larger than byte range
// byte b1 = 7888888955;
short s = 56;
// this will give error as number is
// larger than short range
// short s1 = 87878787878;
// by default fraction value
// is double in java
double d = 4.355453532;
// for float use 'f' as suffix as standard
float f = 4.7333434f;
// need to hold big range of numbers then we need
// this data type
long l = 12121;
System.out.println("char: " + a);
System.out.println("integer: " + i);
System.out.println("byte: " + b);
System.out.println("short: " + s);
System.out.println("float: " + f);
System.out.println("double: " + d);
System.out.println("long: " + l); }}

Output
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121

❖ Non-Primitive (Reference) Data Types


The Non-Primitive (Reference) Data Types will contain a memory address of
variable values because the reference types won’t store the variable value directly in
memory. They are strings, objects, arrays, etc.
1. Strings
Strings are defined as an array of characters. The difference between a character
array and a string in Java is, that the string is designed to hold a sequence of
characters in a single variable whereas, a character array is a collection of separate
char-type entities. Unlike C/C++, Java strings are not terminated with a null
character.
Syntax: Declaring a string
<String_Type> <string_variable> = “<sequence_of_string>”;
Example: This example demonstrates how to use string variables to store and
display text values.
// Demonstrating String data type
public class Geeks {
public static void main(String[] args)
{
String n = "Geek1";
String m = "Hello, World!";
System.out.println("Name: " + n);
System.out.println("Message: " + m);
}}

Output
Name: Geek1
Message: Hello, World!

Note: String cannot be modified after creation. Use StringBuilder for heavy string
manipulation

2. Class
A Class is a user-defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one
type. In general, class declarations can include these components, in order:
• Modifiers : A class can be public or has default access. Refer to access
specifiers for classes or interfaces in Java
• Class name: The name should begin with an initial letter (capitalized by
convention).
• Superclass(if any): The name of the class's parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass) one parent.
• Interfaces(if any): A comma-separated list of interfaces implemented by the
class, if any, preceded by the keyword implements. A class can implement more than
one interface.
• Body: The class body is surrounded by braces, { }.
Example: This example demonstrates how to create a class with a constructor and
method, and how to create an object to call the method.
// Demonstrating how to create a class
class Car {
String model;
int year;
Car(String model, int year)
{
this.model = model;
this.year = year;
}
void display()
{
System.out.println(model + " " + year);
}}
public class Geeks {
public static void main(String[] args)
{
Car myCar = new Car("Toyota", 2020);
myCar.display();
}}

Output
Toyota 2020

3. Object
An Object is a basic unit of Object-Oriented Programming and represents real-life
entities. A typical Java program creates many objects, which as you know, interact
by invoking methods. An object consists of :
• State: It is represented by the attributes of an object. It also reflects the
properties of an object.
• Behavior: It is represented by the methods of an object. It also reflects the
response of an object to other objects.
• Identity: It gives a unique name to an object and enables one object to interact
with other objects.
Example: This example demonstrates how to create the object of a class.
// Define the Car class
class Car {
String model;
int year;
// Constructor to initialize the Car object
Car(String model, int year)
{
this.model = model;
this.year = year;
}}
// Main class to demonstrate object creation
public class Geeks {
public static void main(String[] args)
{
// Create an object of the Car class
Car myCar = new
Car("Honda", 2021);
// Access and print the object's properties
System.out.println("Car Model: " + myCar.model);
System.out.println("Car Year: " + myCar.year); }}

Output
Car Model: Honda
Car Year: 2021

4. Interface
Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, no body).
• Interfaces specify what a class must do and not how. It is the blueprint of the
class.
• An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move(). So it specifies a set
of methods that the class has to implement.
• If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then the class must be declared abstract.
• A Java library example is Comparator Interface. If a class implements this
interface, then it can be used to sort a collection.
Example: This example demonstrates how to implement an interface.
// Demonstrating the working of interface
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound()
{
System.out.println("Woof");
}}
public class InterfaceExample {
public static void main(String[] args)
{
Dog myDog = new Dog();
myDog.sound();
}}

Output
Woof

5. Array
An Array is a group of like-typed variables that are referred to by a common name.
Arrays in Java work differently than they do in C/C++. The following are some
important points about Java arrays.
• In Java, all arrays are dynamically allocated. (discussed below)
• Since arrays are objects in Java, we can find their length using member length.
This is different from C/C++ where we find length using size.
• A Java array variable can also be declared like other variables with [] after the
data type.
• The variables in the array are ordered and each has an index beginning with 0.
• Java array can also be used as a static field, a local variable, or a method
parameter.
• The size of an array must be specified by an int value and not long or short.
• The direct superclass of an array type is Object.
• Every array type implements the interfaces Cloneable and java.io.Serializable.
Example: This example demonstrates how to create and access elements of an
array.
// Demonstrating how to create an array
public class Geeks {
public static void main(String[] args)
{
int[] num = {1, 2, 3, 4, 5};
[] arr = {"Geek1", "Geek2", "Geek3"};
System.out.println("First Number: " + num[0]);
System.out.println("Second Fruit: " + arr[1]);
}}
Output
First Number: 1
Second Fruit: Geek2

Primitive vs Non-Primitive Data Types


The table below demonstrates the difference between Primitive and Non -Primitive
Data types

Aspect Primitive Non-Primitive

Memor
Stored on the stack Stored on the heap
y

Primitive data types are Non-primitive data types are


Speed
faster slower

Exampl
int x = 5; String s = "Geeks";
e

Understanding Java’s data types is fundamental to efficient programming. Each data


type has specific use cases and constraints, making it essential to choose the right
type for the task at hand. This ensures optimal memory usage and program
performance while leveraging Java’s strong typing system to catch errors early in the
development process.

❖ Java Keywords
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.
Example:
// Java Program to demonstrate Keywords
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){
System.out.println("Failed");
}
else
{
System.out.println("Successful demonstration"+" of keywords.");
}
}}

Output
Successful demonstration of keywords.

Java Keywords List


Java contains a list of keywords or reserved words which are also highlighted with
different colors be it an IDE or editor in order to segregate the differences between
flexible words and reserved words. As of Java 21, there are 53 keywords defined in
Java. They are listed below in the table with the primary action associated with them.
Keywords Usage

Specifies that a class or method will be


abstract
implemented later, in a subclass

Assert describes a predicate placed in a


Java program to indicate that the
assert
developer thinks that the predicate is
always true at that place.

A data type that can hold True and False


boolean
values only

A control statement for breaking out of


break
loops.

A data type that can hold 8-bit data


byte
values

Used in switch statements to mark


case
blocks of text

Catches exceptions generated by try


catch
statements

A data type that can hold unsigned 16-bit


char
Unicode characters

class Declares a new class

const Reserved but not used

continue Sends control back outside a loop

Specifies the default block of code in a


default
switch statement

do Starts a do-while loop


A data type that can hold 64-bit floating-
double
point numbers

Indicates alternative branches in an if


else
statement

A Java keyword is used to declare an


enum enumerated type. Enumerations extend
the base class.

Indicates that a class is derived from


extends
another class or interface

Indicates that a variable holds a constant


final value or that a method will not be
overridden

Indicates a block of code in a try-catch


finally
structure that will always be executed

A data type that holds a 32-bit floating-


float
point number

for Used to start a for loop

goto Reserved but not used

Tests a true/false expression and


if
branches accordingly

Specifies that a class implements an


implements
interface

import References other classes

Indicates whether an object is an


instanceof instance of a specific class or
implements an interface
A data type that can hold a 32-bit signed
int
integer

interface Declares an interface

long A data type that holds a 64-bit integer

Specifies that a method is implemented


native
with native (platform-specific) code

new Creates new objects

This indicates that a reference does not


null
refer to anything

package Declares a Java package

An access specifier indicating that a


private method or variable may be accessed
only in the class it's declared in

An access specifier indicating that a


method or variable may only be
protected accessed in the class it's declared in (or
a subclass of the class it's declared in or
other classes in the same package)

An access specifier used for classes,


interfaces, methods, and variables
public indicating that an item is accessible
throughout the application (or where the
class that defines it is accessible)

Sends control and possibly a return


return
value back from a called method

short A data type that can hold a 16-bit integer


Indicates that a variable or method is a
static class method (rather than being limited
to one particular object)

A Java keyword is used to restrict the


strictfp precision and rounding of floating-point
calculations to ensure portability.

Refers to a class's base class (used in a


super
method or class constructor)

A statement that executes code based


switch
on a test value

Specifies critical sections or methods in


synchronized
multithreaded code

Refers to the current object in a method


this
or constructor

throw Creates an exception

Indicates what exceptions may be


throws
thrown by a method

Specifies that a variable is not part of an


transient
object's persistent state

Starts a block of code that will be tested


try
for exceptions

Specifies that a method does not have a


void
return value

This indicates that a variable may


volatile
change asynchronously

while Starts a while loop


The sealed keyword is used to declare a
sealed class as "sealed," meaning it restricts
which classes can extend it.

The permits keyword is used within a


sealed class declaration to specify the
permits
subclasses that are permitted to extend
it.

Example: Using a keyword as a variable name would give error as shown below.
// Java Program to illustrate what if
// we use the keywords as the variable name
class Geeks
{
public static void main(String[] args)
{
// Note "this" is a reserved
// word in java
String this = "Hello World!";
System.out.println(this);
}
}

Output:
./Geeks.java:9: error: not a statement
String this = "Hello World!";
^
./Geeks.java:9: 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.
)
Literals in Java
In Java, a Literal is value of boolean, numeric, character, or string data. Any
constant value that can be assigned to the variable is called a literal.
// Here 100 is a constant/literal.
int x = 100;
Types of Literals in Java
Java supports the following types of literals:
• Integral Literals
• Floating-Point Literals
• Char Literals
• String Literals
• Boolean Literals
Integral Literals in Java
For Integral data types (byte, short, int, long), we can specify literals in four ways,
which are listed below:
1. Decimal literals (Base 10): In this form, the allowed digits are 0-9.
int x = 101;
2. Octal literals (Base 8): In this form, the allowed digits are 0-7.
// The octal number should be prefix with 0.
int x = 0146;
3. Hexadecimal literals (Base 16): In this form, the allowed digits are 0-9, and
characters are a-f. We can use both uppercase and lowercase characters, as we
know that Java is a case-sensitive programming language, but here Java is not
case-sensitive.
// The hexa-decimal number should be prefix
// with 0X or 0x.
int x = 0X123Face;
4. Binary literals: From 1.7 onward, we can specify literal value even in binary form
also, allowed digits are 0 and 1. Literals value should be prefixed with 0b or 0B.
int x = 0b1111;
Example:
public class Geeks {
public static void main(String[] args)
{
// decimal-form literal
int a = 101;
// octal-form literal
int b = 0100;
// Hexa-decimal form literal
int c = 0xFace;
// Binary literal
int d = 0b1111;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d); }}

Output
101
64
64206
15

Note: By default, every literal is of int type, we can specify explicitly as long type by
suffixed with l or L. There is no way to specify byte and short literals explicitly but
indirectly we can specify. Whenever we are assigning integral literal to the byte
variable and if the value is within the range of byte then the compiler treats it
automatically as byte literals.
Floating-Point Literal in Java
For Floating-point data types, we can specify literals in only decimal form, and we
can not specify in octal and Hexadecimal forms.
1. Decimal literals(Base 10): In this form, the allowed digits are 0-9.
double d = 123.456;
Example:
public class Geeks {
public static void main(String[] args)
{
// decimal-form literal (float type suffix 'f' or 'F' is required)
float a = 101.230f;
// It is a decimal literal despite the leading zero
float b = 0123.222f;
// Hexadecimal floating-point literals are NOT supported in Java and will cause an error
// This line causes compilation error
// float c = 0x123.222;
System.out.println(a);
System.out.println(b);
// Commented out due to error
// System.out.println(c);
}}

Output
101.23
123.222
Note:
• By default, every floating-point literal is of double type, and hence we cant assign
directly to the float variable without suffix f and F. But we can specify floating-point literal
as float type by suffixed with f or F. We can specify explicitly floating-point literal as
double type by suffixed with d or D(but suffix is optinal).
• Hexadecimal floating-point literals are not supported in Java, and attempting to
use them causes a compilation error.
Char Literals in Java
For char data types, we can specify literals in four ways which are listed below:
1. Single quote: We can specify literal to a char data type as a single character
within the single quote.
char ch = 'a';
2. Char literal as Integral literal: we can specify char literal as integral literal, which
represents the Unicode value of the character, and that integral literal can be
specified either in Decimal, Octal, and Hexadecimal forms. But the allowed range is
0 to 65535.
char ch = 062; // Octal literal representing character with Unicode code 50 (which is
'2')
Note: If invalid digits are used for octal (means digit other than 0=7), it will cause a
compile-time error, for example:
char b = 0789; // Invalid octal literal due to digits 8 and 9 — causes compile-time
error
3. Unicode Representation: We can specify char literals in Unicode representation
‘\uxxxx’. Here xxxx represents 4 hexadecimal numbers.
char ch = '\u0061';// Here /u0061 represent a.
4. Escape Sequence: Every escape character can be specified as char literals.
char ch = '\n';

Example:
// Java program to illustrate the
// application of char literals
public class Geeks {
public static void main(String[] args)
{
// single character literal within single quotes
char ch = 'a';
// invalid octal literal (causes compilation error)
// char b = 0789;
// Unicode representation
char c = '\u0061';
System.out.println(ch);
// commented out due to error
// System.out.println(b);
System.out.println(c);
// Escape character literal
System.out.println("\" is a symbol");
}}

Output
a
a
" is a symbol

String Literals in Java


Any sequence of characters within double quotes is treated as String literals.
String s = "Hello";
String literals may not contain unescaped newline or linefeed characters. However,
the Java compiler will evaluate compile-time expressions, so the following String
expression results in a string with three lines of text.
Example:
String text = "This is a String literal\n"
+ "which spans not one and not two\n"
+ "but three lines of text.\n";

Illustration:
// Java program to illustrate the
// application of String
literalspublic class Geeks {
public static void main(String[] args)
{
String s = "Hello";
// Without double quotes, it is treated as a variable and causes a compiler error // String s1
= Hello;
System.out.println(s);
// commented out due to error
// System.out.println(s1);
}}

Output
Hello
Boolean Literals in Java
Only two values are allowed for Boolean literals, i.e., true and false.
boolean b = true;
boolean c = false;
Example:
// Java program to illustrate the
// application of boolean literals
public class Geeks{
public static void main(String[] args)
{
boolean b = true;
boolean c = false;
// The following lines cause compilation
// errors and are commented out
// boolean d = 0;
// boolean e = 1;
System.out.println(b);
System.out.println(c);
// System.out.println(d);
// System.out.println(e);
}}

Output
true
false

String Concatenation and Mixed Mode Operations


When we are performing concatenation operations, then the values in brackets are
concatenated first. Then the values are concatenated from the left to the right. We
should be careful when we are mixing character literals and integers in String
concatenation operations and this type of operation are known as Mixed Mode
operation.
Example:
// Java program to illustrate the behaviour of
// char literals and integer literals when// we are performing addition
public class Geeks {
public static void main(String[] args)
{
// ASCII value of 0 is 48
int first = '0';
// ASCII value of 7 is 55
int second = '7';
System.out.println("Geeks!" + first +'2' + second);
}}

Output
Geeks!48255
Explanation: Whenever we are performing addition between a string and integer,
the overall result is converted into a string. The above program evaluation is done in
the following way:
"Geeks!" + first + '2' + second
"Geeks! " + 48 + '2' + 55
"Geeks!48" + '2' + 55
"Geeks!482" + 55
"Geeks!48255"

Java Variables
In Java, variables are containers that store data in memory.
Understanding variables plays a very important role as it defines
how data is stored, accessed, and manipulated.
Key Components of Variables in Java:
A variable in Java has three components, which are listed below:
• 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.
Note: There are three types of variables in Java: Local, Instance
and Static.
Example: The below example demonstrates the variable
declaration in Java
// Demonstarting how to declare and use a variable in Java
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
System.out.println("Age: " + age);
System.out.println("Name: " + name);
System.out.println("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:
1. data type: In Java, a data type define the type of data that a
variable can hold.
2. variable name: Must follow Java naming conventions (e.g.,
camelCase).
In this way, a name can only be given to a memory location. It can
be assigned values in two ways:
• Variable Initialization
• Assigning value by taking input
How to Initialize Java Variables?
It can be perceived with the help of 3 components explained above:

Varible Initialization

Example: Here, we are initalizing variables of different types like


float, int and char.
// Demonstrating how to intialize variables
// of different types in Java
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
System.out.println("Simple Interest: " + si);
System.out.println("Speed:”+s); System.out.println("Time:"+t);
System.out.println("Character: " + var);
}}

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

Types of Java Variables


Now let us discuss different types of variables which are listed as
follows:
• Local Variables
• Instance Variables
• Static Variables

Type of Variable
Let us discuss the traits of every type of variable listed here in
detail.
1. Local Variables
A variable defined within a block or method or constructor is called
a local variable.
• The Local variable is created at the time of declaration and
destroyed when the function completed its execution.
• The scope of local variables exists only within the block in which
they are declared.
• We first need to initialize a local variable before using it within its
scope.
Example: This example show how a local variable is declared and
used inside the main method and it can not be used outside of it.
// Java Program to show the use of local variables
import java.io.*;
class Geeks {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;
// This variable is local to this main method only
System.out.println("Local Variable: " + var);
}}

Output
Local Variable: 10

Example: This example demonstrates that local variables are only


accessible within the block in which they are declared
// Java Program to show the use of
// Local Variables
import java.io.*;
public class Geeks {
public static void main(String[] args) {
// x is a local variable
int x = 10;
// message is also a local
// variable
String message = "Hello, world!";
System.out.println("x = " + x);
System.out.println("message = " + message);
if (x > 5) {
// result is a
// local variable
String result = "x is greater than 5"; System.out.println(result);
}
// Uncommenting the line below will result in a
// compile-time error System.out.println(result);
for (int i = 0; i < 3; i++) {
String loopMessage = "Iteration "+ i;
// loopMessage is a local variable System.out.println(loopMessage);
}
// Uncommenting the line below will result in a
// compile-time error
// System.out.println(loopMessage);
}}

Output
x = 10
message = Hello, world!
x is greater than 5
Iteration 0
Iteration 1
Iteration 2

2. Instance Variables
Instance variables are known as non-static variables and are
declared in a class outside of any method, constructor, or block.
• Instance variables are created when an object of the class is
created and destroyed when the object is destroyed.
• Unlike local variables, we may use access specifiers for instance
variables. If we do not specify any access specifier, then the default
access specifier will be used.
• Initialization of an instance variable is not mandatory. Its default
value is dependent on the data type of variable. For String it is null, for
float it is 0.0f, for int it is 0, for Wrapper classes like Integer it is null,
etc.
• Scope of instance variables are throughout the class except the
static contexts.
• Instance variables can be accessed only by creating objects.
• We initialize instance variables using constructors while creating
an object. We can also use instance blocks to initialize the instance
variables.
Example: This example demonstrates the use of instance
variables, which are declared within a class and initialized via a
constructor, with default values for uninitialized primitive types.
// Java Program to show the use of
// Instance Variables
import java.io.*;
class Geeks {
// Declared Instance Variable
public String geek;
public int i;
public Integer I;
public Geeks()
{
// Default Constructor
// initializing Instance Variable
this.geek = "Sweta Dash";
}
// Main Method
public static void main(String[] args)
{
// Object Creation
Geeks name = new Geeks();
// Displaying O/P
System.out.println("Geek name is: " + name.geek);
System.out.println("Default value for int is "+ name.i);
// toString() called internally
System.out.println("Default value for Integer is: "+ name.I);
}
}

Output
Geek name is: Sweta Dash
Default value for int is 0
Default value for Integer is: null

3. Static Variables
Static variables are also known as class variables.
• These variables are declared similarly to instance variables. The
difference is that static variables are declared using the static keyword
within a class outside of any method, constructor, or block.
• Unlike instance variables, we can only have one copy of a static
variable per class, irrespective of how many objects we create.
• Static variables are created at the start of program execution and
destroyed automatically when execution ends.
• Initialization of a static variable is not mandatory. Its default value
is dependent on the data type of variable. For String it is null, for float
it is 0.0f, for int it is 0, for Wrapper classes like Integer it is null, etc.
• If we access a static variable like an instance variable (through
an object), the compiler will show a warning message, which won't
halt the program. The compiler will replace the object name with the
class name automatically.
• If we access a static variable without the class name, the
compiler will automatically append the class name. But for accessing
the static variable of a different class, we must mention the class
name as 2 different classes might have a static variable with the same
name.
• Static variables cannot be declared locally inside an instance
method.
• Static blocks can be used to initialize static variables.
Example: This example demonstrates the use of static variables,
which belong to the class and can be accessed without creating an
object of the class.
// Java Program to show the use of
// Static variables
import java.io.*;
class Geeks {
// Declared static variable
public static String geek = "Sweta Dash";
public static void main(String[] args)
{
// geek variable can be accessed without object
// creation Displaying O/P Geeks.geek --> using the
// static variable
System.out.println("Geek Name is: " + Geeks.geek);
// static int c = 0;
// above line, when uncommented,
// will throw an error as static variables cannot be
// declared locally.
}}

Output
Geek Name is: Sweta Dash

Instance Variables vs Static Variables


Now let us discuss the differences between the Instance variables
and the Static variables:
• Each object will have its own copy of an instance variable,
whereas we can only have one copy of a static variable per class,
irrespective of how many objects we create. Thus, static variables
are good for memory management.
• Changes made in an instance variable using one object will not
be reflected in other objects as each object has its own copy of the
instance variable. In the case of a static variable, changes will be
reflected in other objects as static variables are common to all objects
of a class.
• We can access instance variables through object references,
and static variables can be accessed directly using the class name.
• Instance variables are created when an object is created with the
use of the keyword 'new' and destroyed when the object is destroyed.
Static variables are created when the program starts and destroyed
when the program stops.
Syntax: Static and instance variables
class Geeks
{
// Static variable
static int a;
// Instance variable
int b;
}
Common Mistakes to Avoid
The common mistakes that can occur when working with variables
in Java are listed below:
• Using uninitialized local variables: Accessing a local variable
without initializing it leads to a compile-time error.
• Confusing == and .equals() for Strings: == is used to compare
object references, while .equals() is used to compare the content of
the strings.
• Modifying static variables incorrectly: Changing static
variables in a multi-threaded environment can lead to thread safety
issues

Typecasting in Java

In Java, typecasting is the process of converting one data type to another data type.
Types of Type Casting
There are two types of Type Casting in Java:
• Widening Type Casting
• Narrow Type Casting

1. Widening Type Casting (Implicit Casting)


A lower data type is transformed into a higher one by a process
known as widening type casting. Implicit type casting and casting
down are some names for it. It occurs naturally. Since there is no
chance of data loss, it is secure. Widening Type casting occurs
when:
• The target type must be larger than the source type.
• Both data types must be compatible with each other.
Note: Widening type casting is also sometimes called upcasting
for primitives, but it is not correct to call it casting down.
Syntax:
larger_data_type variable_name = smaller_data_type_variable;
Example:
// Java program to demonstrate Widening TypeCasting
import java.io.*;
class Geeks {
public static void main(String[] args)
{
int i = 10;
// Wideing TypeCasting (Automatic Casting)
// from int to long
long l = i;
// Wideing TypeCasting (Automatic Casting)
// from int to double
double d = i;
System.out.println("Integer: " + i);
System.out.println("Long: " + l);
System.out.println("Double: " + d); }}

Output
Integer:10
Long:10
Double: 10.0

2. Narrow Type Casting (Explicit Casting)


The process of downsizing a bigger data type into a smaller one is
known as narrowing type casting. Casting up or explicit type casting
are other names for it. It doesn't just happen by itself. If we don't
explicitly do that, a compile-time error will occur. Narrowing type
casting is unsafe because data loss might happen due to the lower
data type's smaller range of permitted values. A cast operator
assists in the process of explicit casting.
Syntax:
smaller_data_type variable_name = (smaller_data_type)
larger_data_type_variable;

Example:
// Java Program to demonstrate Narrow type casting
import java.io.*;
class Geeks {
public static void main(String[] args)
{
double i = 100.245;
// Narrowing Type Casting
short j = (short)i;
int k = (int)i;
System.out.println("Original Value before Casting" +i); System.out.println("After
Type Casting to short ” + j);
System.out.println("After Type Casting to int " + k);
}}

Output
Original Value before Casting100.245
After Type Casting to short 100
After Type Casting to int 100

Types of Explicit Casting


Mainly there are two types of Explicit Casting:
• Explicit Upcasting
• Explicit Downcasting
1. Explicit Upcasting
Upcasting is the process of casting a subtype to a supertype in the
inheritance tree's upward direction. When a sub-class object is
referenced by a superclass reference variable, an automatic
process is triggered without any further effort.
Example:
// Java Program to demonstrate Explicit Upcasting
import java.io.*;
class Animal {
public void makeSound()
{
System.out.println("The animal makes a sound");
}} class Dog extends Animal
{
public void makeSound()
{
System.out.println("The dog barks");
}
public void fetch()
{
System.out.println("The dog fetches a ball");
}}
class Geeks {
public static void main(String[] args)
{
// Upcasting
Animal animal = new Dog();
Calls the overridden method in Dog class
animal.makeSound();
// This would give a compile error as fetch() is not /
/ a method in Animal class
// animal.fetch();
}}

Output
The dog barks

2. Explicit Downcasting
When a subclass type refers to an object of the parent class, the
process is referred to as downcasting. If it is done manually, the
compiler issues a runtime ClassCastException error. It can only be
done by using the instanceof operator. Only the downcast of an
object that has already been upcast is possible.
Example:
// Java Program to demonstrate Explicit downcasting
import java.io.*;
class Animal {
public void eat()
{
System.out.println("The animal is eating.");
}}
class Cat extends Animal {
public void meow()
{
System.out.println("The cat is meowing.");
}}
class Geeks
{
public static void main(String[] args)

Animal animal = new Cat();


animal.eat();
// Explicit downcasting
Cat cat = (Cat)animal;
cat.meow();
}}

Output
The animal is eating.
The cat is meowing.

Typecasting is also applicable to reference types, but must be done


carefully. Casting an object to an incompatible type will result in a
ClassCastException at runtime.
Object obj = "hello"; // A String stored in an Object
String s = (String) obj; // Valid cast, no error
Integer i = (Integer) obj; // Runtime error: ClassCastException
To avoid such issues, it's good practice to use the instanceof
operator before downcasting:
if (obj instanceof String) {
String s = (String) obj;
System.out.println("String value: " + s);
}

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.
Example: Below code describes basic structure of operator. how to use operators
like the + and - operators are used to perform addition and subtraction on numeric
values."
// Java program to show the use of + and - operators
public class Geeks {
public static void main(String[] args)
{
// Declare and initialize variables
int num1 = 500;
int num2 = 100;
// Using the + (addition) operator
int sum = num1 + num2;
System.out.println("The Sum is: "+sum);
// Using the - (subtraction) operator
int diff = num1 - num2;
System.out.println("The Difference is: "+diff);
}}

Output
The Sum is: 600
The Difference is: 400

Explanation:
• A class named Geeks is created containing the main method.
• Two integer variables num1 and num2 are declared and initialized with values.
• The + operator is used to add the two numbers and store the result in sum.
• The result of addition is printed to the console.
• The - operator is used to subtract the second number from the first and store the
result in diff.
Types of Operators in Java
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. An instance of an operator
Let's see all these operators one by one with their proper examples.
1. Arithmetic Operators
Arithmetic Operators are used to perform simple arithmetic operations on primitive
and non-primitive data types.
• * : Multiplication
• / : Division
• % : Modulo
• + : Addition
• - : Subtraction
Note:
• Division (/) truncates decimal points for integers.
• Modulus (%) is useful for checking even/odd numbers.
Example: This example demonstrates the use of arithmetic operators on integers
and string-to-integer conversion for performing mathematical operations.
// Java Program to show the use of
// Arithmetic Operators
import java.io.*;
class Geeks {
public static void main (String[] args)
{
// Arithmetic operators on integers
int a = 10; int b = 3;
// Arithmetic operators on Strings
String n1 = "15";
String n2 = "25";
// Convert Strings to integers
int a1 = Integer.parseInt(n1);
int b1 = Integer.parseInt(n2);
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));
System.out.println("a1 + b1 = " + (a1 + b1));
}}

Output
a + b = 13
a-b=7
a * b = 30
a/b =3
a%b=1
a1 + b1 = 40

2. Unary Operators
Unary Operators need only one operand. They are used to increment, decrement, or
negate a value.
• - , Negates the value.
• + , Indicates a positive value (automatically converts byte, char, or short to int).
• ++ , Increments by 1.
o Post-Increment: Uses value first, then increments.
o Pre-Increment: Increments first, then uses value.
• -- , Decrements by 1.
o Post-Decrement: Uses value first, then decrements.
o Pre-Decrement: Decrements first, then uses value.
• ! , Inverts a boolean value.
Example: This example demonstrates the use of unary operators for post-
increment, pre-increment, post-decrement, and pre-decrement operations.
// Java Program to show the use of
// Unary Operators
import java.io.*;
// Driver Class
class Geeks {
// main function
public static void main(String[] args)
{
// Integer declared
int a = 10;
int b = 10;
// Using unary operators
System.out.println("Postincrement:"+ (a++));
System.out.println("Preincrement : " + (++a));
System.out.println("Postdecrement:"+(b--));
System.out.println("Predecrement : " + (--b));
}}

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

3. Assignment Operator
'=' The assignment operator is used to assign a value to any variable. It has right-to-
left associativity, i.e. value given on the right-hand side of the operator is assigned to
the variable on the left, and therefore right-hand side value must be declared before
using it or should be a constant.
The general format of the assignment operator is:
variable = value;
In many cases, the assignment operator can be combined with others to create
shorthand compound statements. For example, a += 5 replaces a = a + 5. Common
compound operators include:
• += , Add and assign.
• -= , Subtract and assign.
• *= , Multiply and assign.
• /= , Divide and assign.
• %= , Modulo and assign.
Example: This example demonstrates the use of various assignment operators,
including compound, bitwise, and shift operators, for modifying a variable.
// Java Program to show the use of
// Assignment Operators
import java.io.*; // Driver Class
class Geeks {
// Main Function
public static void main(String[] args)
{
// Assignment operators
int f = 7;
System.out.println("f += 3: " + (f += 3));
System.out.println("f -= 2: " + (f -= 2));
System.out.println("f *= 4: " + (f *= 4));
System.out.println("f /= 3: " + (f /= 3));
System.out.println("f %= 2: " + (f %= 2));
System.out.println("f &= 0b1010: " + (f &= 0b1010));
System.out.println("f |= 0b1100: " + (f |= 0b1100));
System.out.println("f ^= 0b1010: " + (f ^= 0b1010));
System.out.println("f <<= 2: " + (f <<= 2));
System.out.println("f >>= 1: " + (f >>= 1));
System.out.println("f >>>= 1: " + (f >>>= 1));
}}

Output
f += 3: 10
f -= 2: 8
f *= 4: 32
f /= 3: 10
f %= 2: 0
f &= 0b1010: 0
f |= 0b1100: 12
f ^= 0b1010: 6
f <<= 2: 24
f >>= 1: 12
f >>>= 1: 6

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. The general format
is ,
variable relation_operator value
Relational operators compare values and return Boolean results:
• == , Equal to.
• != , Not equal to.
• < , Less than.
• <= , Less than or equal to.
• > , Greater than.
• >= , Greater than or equal to.
Example: This example demonstrates the use of relational operators to compare
values and return boolean results.
// Java Program to show the use of
// Relational Operators
import java.io.*;
// Driver Class
class Geeks {
// main function
public static void main(String[] args)
{ // Comparison operators
int a = 10;
int b = 3;
int c = 5;
System.out.println("a > b: " + (a > b));
System.out.println("a < b: " + (a < b));
System.out.println("a >= b: " + (a >= b));
System.out.println("a <= b: " + (a <= b));
System.out.println("a == c: " + (a == c));
System.out.println("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.
Conditional operators are:
• &&, Logical AND: returns true when both conditions are true.
• ||, Logical OR: returns true if at least one condition is true.
• !, Logical NOT: returns true when a condition is false and vice-versa
Example: This example demonstrates the use of logical operators (&&, ||, !) to
perform boolean operations.
// Java Program to show the use of
// Logical operators
import java.io.*;
class Geeks {
// Main Function
public static void main (String[] args)
{
// Logical operators
boolean x = true;
boolean y = false;
System.out.println("x && y: " + (x && y));
System.out.println("x || y: " + (x || y));
System.out.println("!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,
condition ? if true : if false
The above statement means that if the condition evaluates to true, then execute the
statements after the '?' else execute the statements after the ':'.
Example: This example demonstrates the use of the ternary operator to find the
maximum of three numbers.
// Java program to illustrate
// max of three numbers using// ternary operator.
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); System.out.println( "Max of three numbers
= "+ result);
}}

OutputMax of three numbers = 30


7. Bitwise Operators
Bitwise Operators are used to perform the manipulation of individual bits of a
number and with any of the integer types. They are used when performing update
and query operations of the Binary indexed trees.
• & (Bitwise AND): returns bit-by-bit AND of input values.
• | (Bitwise OR): returns bit-by-bit OR of input values.
• ^ (Bitwise XOR): returns bit-by-bit XOR of input values.
• ~ (Bitwise Complement): inverts all bits (one's complement).
Example: This example demonstrates the use of bitwise operators (&, |, ^, ~, <<,
>>, >>>) to perform bit-level operations.
// Java Program to show the use of
// bitwise operators
import java.io.*;
class Geeks {
public static void main(String[] args)
{
// Bitwise operators
int d = 0b1010;
int e = 0b1100;
System.out.println("d & e : " + (d & e));
System.out.println("d | e : " + (d | e));
System.out.println("d ^ e : " + (d ^ e));
System.out.println("~d : " + (~d));
System.out.println("d << 2 : " + (d << 2));
System.out.println("e >> 1 : " + (e >> 1));
System.out.println("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. Shift Operators
Shift Operators are used to shift the bits of a number left or right, thereby multiplying
or dividing the number by two, respectively. They can be used when we have to
multiply or divide a number by two. The general format ,
number shift_op number_of_places_to_shift;
• << (Left shift): Shifts bits left, filling 0s (multiplies by a power of two).
• >> (Signed right shift): Shifts bits right, filling 0s (divides by a power of two),
with the leftmost bit depending on the sign.
• >>> (Unsigned right shift): Shifts bits right, filling 0s, with the leftmost bit always
0.
Example: This example demonstrates the use of shift operators (<<, >>) to shift
the bits of a number left and right.
// Java Program to show the use of
// shift operators
import java.io.*;
class Geeks {
public static void main(String[] args)
{
int a = 10;
// Using left shift
System.out.println("a<<1 : " + (a << 1));
// Using right shift
System.out.println("a>>1 : " + (a >> 1));
}}

Output
a<<1 : 20
a>>1 : 5

9. 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,
object instance of class/subclass/interface
Example: This example demonstrates the use of the instanceof operator to
check if an object is an instance of a specific class or interface
// Java program to show the use of
// Instance of operator
public class Geeks {
public static void main(String[] args)
{
Person obj1 = new Person();
Person obj2 = new Boy();
// As obj is of type person, it is not an
// instance of Boy or interface
System.out.println("obj1 instanceof Person: "+ (obj1 instanceof Person));
System.out.println("obj1 instanceof Boy:” + (obj1 instanceof Boy)); System.out.println("obj1
instanceof MyInterface: "+ (obj1 instanceof MyInterface)); // Since obj2 is of type boy,
// whose parent class is person
// and it implements the interface Myinterface
// it is instance of all of these classes

System.out.println("obj2 instanceof Person: " + (obj2 instanceof Person));


System.out.println("obj2 instanceof Boy: " + (obj2 instanceof Boy));
System.out.println("obj2 instanceof MyInterface: " + (obj2 instanceof MyInterface)); }
}
// Classes and Interfaces used// are declared here
class Person {}
class Boy extends Person implements MyInterface {}
interface MyInterface {}

Output
obj1 instanceof Person: true
obj1 instanceof Boy: false
obj1 instanceof MyInterface: false
obj2 instanceof Person: true
obj2 instanceof Boy: true
obj2 instanceof MyInterface: true

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.

Operator Precedence and Associativity in Java

Precedence and associative rules are applied when dealing with hybrid equations
that involve more than one type of operator. In such cases, these rules determine
which part of the equation to consider first, as there can be many different valuations
for the same equation.
Operator Precedence in Java
In Java, operator precedence specifies the order in which operations are performed
within an expression. When an expression contains multiple operators, those with
higher precedence are evaluated before those with lower precedence.
For expression:
10+20*30
The expression contains two operators, + (addition) and * (multiplication). According
to operator precedence, multiplication (*) has higher precedence than addition (+),
so multiplication is checked first. After evaluating multiplication, the addition operator
is then evaluated to give the final result.

Operator Precedence
Example:
public class OperatorPrecedenceExample {
public static void main(String[] args)
{

// Multiplication has higher precedence than


// addition
int result = 10 + 20 * 30;
System.out.println("Result: " + result);
}}

Output
Result: 610

Explanation:
• In the following code (multiplication) has higher precedence than + (addition).
• So in 10 + 20 * 30, the multiplication happens first:
20 * 30 = 600 // first execute this expression
10 + 600 = 610// next execute this expression
Operator Precedence Table in Java
The table below illustrates the precedence of operators in decreasing order of
magnitude, with the top row representing the highest precedence and the bottom
row showing the lowest preced

ence.

Operator Associativity in Java


Operator associativity in Java determines the order of evaluation when multiple
operators of the same precedence appear in an expression.
Java supports two types of associativity:
1. Left-to-Right Associativity
When multiple operators of the same precedence appear in an expression, they are
evaluated from left to right. For example, in the expression a + b - c, addition and
subtraction have the same precedence and are left-associative, so the expression is
evaluated as (a + b) - c.
Operators with left-to-right associativity include:
• Arithmetic operators: +, -, *, /, %
• Relational operators: >, <, >=, <=
• Logical AND/OR: &&, ||
• Bitwise operators: &, |, ^, <<, >>
public class LeftToRight {
public static void main(String[] args)
{
int a = 10, b = 5, c = 2;
int result = a - b + c;
// evaluated as (10 - 5) + 2 = 7

System.out.println("Final output " + result); }}

Output
Final output 7

Explanation: Here, - and + have the same precedence and are left-associative, so
evaluation happens left to right.
2. Right-to-Left Associativity
Right-to-Left Associativity means that operators are evaluated from right to left when
they have the same precedence.
Operators with right-to-left associativity include:
• Assignment operators: =, +=, -=, etc.
• Unary operators: ++, --, !, ~
public class RightToLeftAssociativity {
public static void main(String[] args) { int a, b; a = b = 4; // evaluated as a = (b = 4)
System.out.println("a: " + a); // 4 System.out.println("b: " + b); // 4 }}

Outputa: 4
b: 4

Explanation: The assignment = is right-associative, so b = 4 is evaluated first, then


a = b.
For expression:
100 / 10 % 10
The division (/) and modulus (%) operators have the same precedence, so the order
in which they are evaluated depends on their left-to-right associativity. This means
the division is performed first, followed by the modulus operation. After the
calculations, the result of the modulus operation is determined.
Operator Associativity

Example of Java Operator Precedence and Associativity


In general, operator precedence and associativity are applied together in
expressions. Consider the expression exp = 100 + 200 / 10 - 3 * 10, where the
division (/) and multiplication (*) operators have the same precedence but are
evaluated before addition (+) and subtraction (-). Due to left-to-right associativity, the
division is evaluated first, followed by multiplication. After evaluating the division and
multiplication, the addition and subtraction are evaluated from left to right, giving the
final result.

Operator Precedence
Example: Now see how this expression evaluate:
int exp = 100 + 200 / 10 - 3 * 10;
public class OperatorPrecedence {
public static void main(String[] args)
{
int result = 100 + 200 / 10 - 3 * 10;

// Verifying the result of the same expression


System.out.println("Final Output: " + result);
}}

Output
Final Output: 90

Explanation:
• * and / have higher precedence than + and -
200 / 10 = 20
3 * 10 = 30 // Evaluate left to right:
• + and - have same precedence, evaluated left to right:
100 + 20 = 120
120 - 30 = 90 // Evaluate left to right

Java IO - Input/Output in Java with Exam

Java provides various Streams with its I/O package that helps the
user to perform all the input-output operations. These streams
support all the types of objects, data-types, characters, files, etc., to
fully execute the I/O operations.
The image below demonstrates the flow of data from a source to
a destination.

Standard or Default Streams in Java


Before exploring various input and output streams, let's look at 3
standard or default streams that Java has to provide, which are
also most commonly used:

• System.in: This is the standard input stream (System.in) that


is used to read characters from the keyboard or any other standard
input device.
• System.out: This is the standard output stream (System.out)
that is used to produce the result of a program on an output device
like the computer screen.
Here is a list of the various print functions that we use to output
statements:
Java Print Functions Used with System.out
Now, we are going to discuss the main print function used with
System.out which are listed below:
1. print(): This method in Java is used to display a text on the
console. This text is passed as the parameter to this method in the
form of String. This method prints the text on the console and the
cursor remains at the end of the text at the console. The next
printing takes place from just here.
Syntax:
System.out.print(parameter);
Example:
// Java program to illustrate print()
import java.io.*;
class Geeks {
public static void main(String[] args)
{
// using print()
// all are printed in the
// same line
System.out.print("GfG! ");
System.out.print("GfG! ");
System.out.print("GfG! ");
}}

Output
GfG! GfG! GfG!

2. println(): This method in Java is also used to display a text on


the console. It prints the text on the console and the cursor moves
to the start of the next line at the console. The next printing takes
place from the next line.
Syntax:
System.out.println(parameter);
Example:
// Java program to illustrate println()
import java.io.*;
class Geeks {
public static void main(String[] args)
{
// using println()
// all are printed in the
// different line
System.out.println("GfG! ");
System.out.println("GfG! ");
System.out.println("GfG! ");
}}

Output
GfG!
GfG!
GfG!

3. printf(): This is the easiest of all methods as this is similar to


printf in C. Note that System.out.print() and System.out.println()
take a single argument, but printf() may take multiple arguments.
This is used to format the output in Java.
Example:
// A Java program to demonstrate
// working of printf() in Java
class Geeks {
public static void main(String[] args)
{
int x = 100;
// Printing a simple integer
System.out.printf("Printing simple integer: x = %d%n", x);
// Printing a floating-point
// number with precision
System.out.printf("Formatted with precision: PI = %.2f%n", Math.PI);
float n = 5.2f;
// Formatting a float to 4 decimal places
System.out.printf("Formatted to specific width: n = %.4f%n", n);
n = 2324435.3f;
// Right-aligning and formatting a
// float to 20-character width
System.out.printf("Formatted to right margin: n = %20.4f%n", n);
}}

Output
Printing simple integer: x = 100
Formatted with precision: PI = 3.14
Formatted to specific width: n = 5.2000
Formatted to right margin: n = 2324435.2500

System.err Example
It is used to display the error messages. It works similarly to
System.out with print(), println(), and printf() methods.
Example:
// Java Program demonstrating System.err
public class Geeks {

public static void main(String[] args) {

// Using print()
System.err.print("This is an error message using print().\n");

// Using println()
System.err.println("This is another error message using println().");

//Using printf()
System.err.printf("Error code: %d, Message: %s%n", 404, "Not Found");
}
}

Output:
This is an error message using print().
This is another error message using println().
Error code: 404, Message: Not Found

Types of Streams
Depending on the type of operations, streams can be divided into
two primary classes:
1. Input Stream: These streams are used to read data that must
be taken as an input from a source array or file or any peripheral
device. For eg., FileInputStream, BufferedInputStream,
ByteArrayInputStream etc.

2. Output Stream: These streams are used to write data as


outputs into an array or file or any output peripheral device. For eg.,
FileOutputStream, BufferedOutputStream,
ByteArrayOutputStream etc.
Types of Streams Depending on the Types of File
Depending on the types of file, Streams can be divided into two
primary classes which can be further divided into other classes as
can be seen through the diagram below followed by the
explanations.
1. ByteStream:This is used to process data byte by byte (8 bits).
Though it has many classes, the FileInputStream and the
FileOutputStream are the most popular ones. The FileInputStream
is used to read from the source and FileOutputStream is used to
write to the destination.
Here is the list of various ByteStream Classes:
Stream class Description

BufferedInputStrea
It is used for Buffered Input Stream.
m

It contains method for reading java standard


DataInputStream
datatypes.

FileInputStream This is used to reads from a file

InputStream This is an abstract class that describes stream input.

This contains the most used print() and println()


PrintStream
method

BufferedOutputStre
This is used for Buffered Output Stream.
am

This contains method for writing java standard data


DataOutputStream
types.

FileOutputStream This is used to write to a file.

OutputStream This is an abstract class that describe stream output.

Example:
// Java Program illustrating the
// Byte Stream to copy
// contents of one file to another file.
import java.io.*;
public class Geeks {
public static void main(
String[] args) throws IOException
{

FileInputStream sourceStream = null;


FileOutputStream targetStream = null;

try {
sourceStream
= new FileInputStream("sorcefile.txt");
targetStream
= new FileOutputStream("targetfile.txt");

// Reading source file and writing


// content to target file byte by byte
int temp;
while ((
temp = sourceStream.read())
!= -1)
targetStream.write((byte)temp);
}
finally {
if (sourceStream != null)
sourceStream.close();
if (targetStream != null)
targetStream.close();
}
}
}

Output:
Shows contents of file test.txt
2. CharacterStream: In Java, characters are stored using Unicode
conventions (Refer this for details). Character stream automatically
allows us to read/write data character by character. Though it has
many classes, the FileReader and the FileWriter are the most
popular ones. FileReader and FileWriter are character streams
used to read from the source and write to the destination
respectively.
Here is the list of various CharacterStream Classes:
Stream class Description

BufferedReader It is used to handle buffered input stream.

FileReader This is an input stream that reads from file.

InputStreamRead This input stream is used to translate byte to


er character.

OutputStreamRea This output stream is used to translate character to


der byte.

This is an abstract class that define character stream


Reader
input.

This contains the most used print() and println()


PrintWriter
method

This is an abstract class that define character stream


Writer
output.

BufferedWriter This is used to handle buffered output stream.

FileWriter This is used to output stream that writes to file.

Example:
// Java Program illustrating that
// we can read a file in a human-readable
// format using FileReader

// Accessing FileReader, FileWriter,


// and IOException
import java.io.*;

public class Geeks


{
public static void main(String[] args) throws IOException
{
FileReader sourceStream = null;

try {
sourceStream = new FileReader("test.txt");

// Reading sourcefile and


// writing content to target file
// character by character.
int temp;

while (( temp = sourceStream.read())!= -1 )


System.out.println((char)temp);
}
finally {

// Closing stream as no longer in use


if (sourceStream != null)
sourceStream.close();
}
}
}

Note: Please make sure that the file test.txt is in the same
directory, this file contains the text which we want to read.
Vis

You might also like