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

Introduction to Java

Java is a class-based, object-oriented programming language designed for platform independence, allowing developers to write code once and run it anywhere. Developed by James Gosling in 1995, Java is known for its simplicity, robustness, and security features, making it popular for enterprise applications. Key features include multithreading, portability, and a large community, while it faces challenges with performance and memory management compared to languages like C++.

Uploaded by

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

Introduction to Java

Java is a class-based, object-oriented programming language designed for platform independence, allowing developers to write code once and run it anywhere. Developed by James Gosling in 1995, Java is known for its simplicity, robustness, and security features, making it popular for enterprise applications. Key features include multithreading, portability, and a large community, while it faces challenges with performance and memory management compared to languages like C++.

Uploaded by

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

Introduction to Java

Java is a class-based, object-oriented programming language that is designed to have as few


implementation dependencies as possible. It is intended to let application developers Write Once
and Run Anywhere (WORA), meaning that compiled Java code can run on all platforms that support
Java without the need for recompilation. Java was developed by James Gosling at Sun Microsystems
Inc. in May 1995 and later acquired by Oracle Corporation and is widely used for developing
applications for desktop, web, and mobile devices.

Java is known for its simplicity, robustness, and security features, making it a popular choice for
enterprise-level applications. Java applications are compiled to byte code that can run on any Java
Virtual Machine. The syntax of Java is similar to C/C++.

Java makes writing, compiling, and debugging programming easy. It helps to create reusable code
and modular programs.

History of Java

Java’s history is as interesting as it is impactful. The journey of this powerful programming


language began in 1991 when James Gosling, Mike Sheridan, and Patrick Naughton, a team of
engineers at Sun Microsystems known as the “Green Team,” set out to create a new language
initially called “Oak.” Oak was later renamed Java, inspired by Java coffee, and was first publicly
released in 1996 as Java 1.0. This initial version provided a no-cost runtime environment across
popular platforms, making it accessible to a broad audience. Arthur Van Hoff rewrote the Java 1.0
compiler to strictly comply with its specifications, ensuring its reliability and cross-platform
capabilities.

• Java evolved over time, with Java 2 introducing multiple configurations tailored for different
platforms, showcasing its versatility.

• In 1997, Sun Microsystems aimed to formalize Java through the ISO standards body but
eventually withdrew from the process.

• Despite not formalizing through ISO, Sun Microsystems offered most Java
implementations at no cost, earning revenue by licensing specialized products such as
the Java Enterprise System.

• A significant milestone in Java’s history occurred on November 13, 2006, when Sun
Microsystems released a large portion of the Java Virtual Machine (JVM) as free, open-
source software.

• By May 8, 2007, the core JVM code was fully available under open-source distribution terms.

• Java was designed with core principles: simplicity, robustness, security, high performance,
portability, multi-threading, and dynamic interpretation. These principles have made Java a
preferred language for various applications, including mobile devices, internet programming,
gaming, and e-business.

• Today, Java continues to be a cornerstone of modern software development, widely used


across industries and platforms.

Features of Java
1. Platform Independent
Compiler converts source code to byte code and then the JVM executes the bytecode generated by
the compiler. This byte code can run on any platform be it Windows, Linux, or macOS which means if
we compile a program on Windows, then we can run it on Linux and vice versa. Each operating
system has a different JVM, but the output produced by all the OS is the same after the execution of
the byte code. That is why we call java a platform-independent language.

2. Object-Oriented Programming

Java is an object-oriented language, promoting the use of objects and classes. Organizing the
program in the terms of a collection of objects is a way of object-oriented programming, each of
which represents an instance of the class.

The four main concepts of Object-Oriented programming are:

• Abstraction

• Encapsulation

• Inheritance

• Polymorphism

3. Simplicity

Java’s syntax is simple and easy to learn, especially for those familiar with C or C++. It eliminates
complex features like pointers and multiple inheritances, making it easier to write,
debug, and maintain code.

4. Robustness

Java language is robust which means reliable. It is developed in such a way that it puts a lot of effort
into checking errors as early as possible, that is why the java compiler is able to detect even those
errors that are not easy to detect by another programming language. The main features of java that
make it robust are garbage collection, exception handling, and memory allocation.

5. Security

In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it


shows ArrayIndexOutOfBound Exception if we try to do so. That’s why several security flaws like
stack corruption or buffer overflow are impossible to exploit in Java. Also, java programs run in an
environment that is independent of the os(operating system) environment which makes java
programs more secure.

6. Distributed

We can create distributed applications using the java programming language. Remote Method
Invocation and Enterprise Java Beans are used for creating distributed applications in java. The java
programs can be easily distributed on one or more systems that are connected to each other through
an internet connection.

7. Multithreading

Java supports multithreading, enabling the concurrent execution of multiple parts of a program.
This feature is particularly useful for applications that require high performance, such as games and
real-time simulations.
8. Portability

As we know, java code written on one machine can be run on another machine. The platform-
independent feature of java in which its platform-independent bytecode can be taken to any
platform for execution makes java portable. WORA(Write Once Run Anywhere) makes java
application to generates a ‘.class’ file that corresponds to our applications(program) but contains
code in binary format. It provides ease t architecture-neutral ease as bytecode is not dependent on
any machine architecture. It is the primary reason java is used in the enterprising IT industry globally
worldwide.

9. High Performance

Java architecture is defined in such a way that it reduces overhead during the runtime and at some
times java uses Just In Time (JIT) compiler where the compiler compiles code on-demand basis
where it only compiles those methods that are called making applications to execute faster.

How Java Code Executes?

The execution of a Java application code involves three main steps:

Creating the Program

Java programs are written using a text editor or an Integrated Development Environment
(IDE) like IntelliJ IDEA, Eclipse, or NetBeans. The source code is saved with a .java extension.
2. Compiling the Program

The Java compiler (javac) converts the source code into bytecode, which is stored in a .class file. This
bytecode is platform-independent and can be executed on any machine with a JVM.

3. Running the Program

The JVM executes the compiled bytecode, translating it into machine code specific to the operating
system and hardware

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

Java Terminologies

1. Java Virtual Machine(JVM)

The JVM is an integral part of the Java platform, responsible for executing Java bytecode. It
ensures that the output of Java programs is consistent across different platforms.

• Writing a program is done by a java programmer like you and me.

• The compilation is done by the JAVAC compiler which is a primary Java compiler included in
the Java development kit (JDK). It takes the Java program as input and generates bytecode as
output.

• In the Running phase of a program, JVM executes the bytecode generated by the compiler.

The Java Virtual Machine (JVM) is designed to run the bytecode generated by the Java
compiler. Each operating system has its own version of the JVM, but all JVMs follow the same
rules and standards. This means Java programs can run the same way on any device with a
JVM, regardless of the operating system. This is why Java is called a platform-independent
language.

2. Bytecode

Bytecode is the intermediate representation of Java code, generated by the Java compiler. It
is platform-independent and can be executed by the JVM.

3. Java Development Kit(JDK)

While we were using the term JDK when we learn about bytecode and JVM. So, as the name
suggests, it is a complete Java development kit that includes everything
including compiler, Java Runtime Environment (JRE), Java Debuggers, Java Docs, etc. For the
program to execute in java, we need to install JDK on our computer in order to create,
compile and run the java program.

4. Java Runtime Environment (JRE)

JDK includes JRE. JRE installation on our computers allows the java program to run, however,
we cannot compile it. JRE includes a browser, JVM, applet support, and plugins. For running
the java program, a computer needs JRE.

5. Garbage Collector

In Java, programmers can’t delete the objects. To delete or recollect that memory JVM has a
program called Garbage Collector. Garbage Collectors can recollect the objects that are not
referenced. So Java makes the life of a programmer easy by handling memory management.
However, programmers should be careful about their code whether they are using objects
that have been used for a long time. Because Garbage cannot recover the memory of
objects being referenced.

6. ClassPath

The Classpath is the file path where the java runtime and Java compiler look for .class files to
load. By default, JDK provides many libraries. If you want to include external libraries they
should be added to the classpath.

Basically everything in java is represented in Class as an object including the main function.

Advantages of Java

• Platform independent: Java code can run on any platform that has a Java Virtual Machine
(JVM) installed, which means that applications can be written once and run on any device.

• Object-Oriented: Java is an object-oriented programming language, which means that it


follows the principles of encapsulation, inheritance, and polymorphism.

• Security: Java has built-in security features that make it a secure platform for developing
applications, such as automatic memory management and type checking.

• Large community: Java has a large and active community of developers, which means that
there is a lot of support available for learning and using the language.

• Enterprise-level applications: Java is widely used for developing enterprise-level


applications, such as web applications, e-commerce systems, and database systems.

Disadvantages of Java

1. Performance: Java can be slower compared to other programming languages, such as C++,
due to its use of a virtual machine and automatic memory management.

2. Memory management: Java’s automatic memory management can lead to slower


performance and increased memory usage, which can be a drawback for some applications.

Similarities and Difference between Java


and C++
Similarities between Java and C++

1. Execution: At compile-time, Java source code or .java file is converted into bytecode
or .class file. At runtime, JVM (Java Virtual Machine) will load the .class file and will convert
it to machine code with the help of an interpreter. After compilation of method calls (using
the Just-In-Time (JIT) compiler), JVM will execute the optimized code. So Java is
both compiled as well as an interpreted language. On the other hand, C++ executes the code
by using only a compiler. The C++ compiler compiles and converts the source code into the
machine code. That’s why C++ is faster than Java but not platform-independent.

Below is the illustration of how Java and C++ codes are executed:

The execution of a Java code is as follows:

Execution of a C++ Code


2. Features: C++ and Java both have several Object Oriented
programming features which provide many useful programming
functionalities. Some features are supported by one and some by the
other. Even though both languages use the concept of OOPs, neither
can be termed 100% object-oriented languages. Java uses primitive
data types and thus cannot be termed as 100% Object-Oriented
Language. C++ uses some data types similar to primitive ones and can
implement methods without using any data type. And thus, it is also
deprived of the 100% Object-Oriented title.
Below is the table which shows the features supported and not
supported by both the programming languages:

Features C++ Java

Abstraction Yes Yes


Features C++ Java

Encapsulation Yes Yes

Single Inheritance Yes Yes

Multiple Inheritance Yes No

Polymorphism Yes Yes

Static Binding Yes Yes

Dynamic Binding Yes Yes

Operator Overloading Yes No

Header Files Yes No

Pointers Yes No

Global Variables Yes No

Template Class Yes No

Interference and Packages No Yes

API No Yes

Syntax Difference:
Syntax of c++:
#include <iostream>
using namespace std;
int main() {

cout << "GFG!";


return 0;
}

syntax of java

Java

package whatever //do not write package name here */

import java.io.*;

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

Applications: Both C++ and Java have vast areas of application.


Below are the applications of both languages:
• Applications of C++ Programming language:
1. Suitable for Developing large software (like passenger
reservation systems).
2. MySQL is written in C++.
3. For fast execution, C++ is majorly used in Game
Development.
4. Google Chromium browser, file system, and cluster data
processing are all written in C++.
5. Adobe Premiere, Photoshop, and Illustrator; these
popular applications are scripted in C++.
6. Advanced Computations and Graphics- real-time physical
simulations, high-performance image processing.
7. C++ is also used in many advanced types of medical
equipment like MRI machines, etc.
• Applications of Java Programming language:
1. Desktop GUI Applications development.
2. Android and Mobile application development.
3. Applications of Java are in embedded technologies like
SIM cards, disk players, TV, etc.
4. Java EE (Enterprise Edition) provides an API and runtime
environment for running large enterprise software.
5. Network Applications and Web services like Internet
connection, Web App Development.
Environment: C++ is a Platform dependent while Java is a platform-
independent programming language. We have to write and run C++ code
on the same platform. Java has the WORA (Write Once and Run
Everywhere) feature by which we can write our code in one platform
once and we can run the code anywhere.
Differences between Java and C++ are as follows:
Sl.
No. Parameters Java C++

C++ was developed by


Java was developed by Bjarne Stroustrup at
1. Founder James Gosling at Sun Bell Labs in 1979 as
Microsystems. an extension of the
C language.

2. First Release On May 23, 1995 In October 1985

Java SE 18 was
Stable C++20 released on
3. released on 22 March
Release 15th December 2020
2022

Official
4. oracle.com/java isocpp.org
Website

C++ was Influenced


Java was Influenced by Influenced by
Influenced by Ada 83, Pascal, Ada, ALGOL 68, C,
5.
By: C++, C#, etc. ML, Simula,
languages. Smalltalk, etc.
languages.

Java was influenced C++ was influenced


to develop BeanShell, to develop C99,
Influenced C#, Clojure, Groovy, Java, JS++, Lua,
6.
to: Hack, J#, Kotlin, Perl, PHP, Python,
PHP, Python, Scala, Rust, Seed7, etc.
etc. languages. languages.

Platform-independent, Platform dependent,


Platform Java bytecode works should be compiled
7.
Dependency on any operating for different
system. platforms.
Sl.
No. Parameters Java C++

C++ is platform-
It can run on any OS
8. Portability dependent. Hence it
hence it is portable.
is not portable.

Java is both Compiled


C++ is a Compiled
9. Compilation and Interpreted
Language.
Language.

Memory Memory Management is Memory Management in


10.
Management System Controlled. C++ is Manual.

Virtual It doesn’t have a It has Virtual


11.
Keyword Virtual Keyword. keywords.

It supports only
single inheritance.
It supports both
Multiple Multiple inheritances
12. single and multiple
Inheritance are achieved
Inheritance.
partially using
interfaces.

It supports only
It supports both
method overloading
13. Overloading method and operator
and doesn’t allow
overloading.
operator overloading.

It has limited It strongly supports


14. Pointers
support for pointers. pointers.

It supports direct
It doesn’t support
system library
direct native library
15. Libraries calls, making it
calls but only Java
suitable for system-
Native Interfaces.
level programming.

Libraries have a wide C++ libraries have


range of classes for comparatively low-
16. Libraries
various high-level level
services. functionalities.
Sl.
No. Parameters Java C++

It supports It doesn’t support


Documentation documentation documentation
17.
Comment comments (e.g., /**.. comments for source
*/) for source code. code.

C++ doesn’t have


Java provides built- built-in support for
Thread
18. in support for threads, depends on
Support
multithreading. third-party
threading libraries.

C++ is both a
Java is only an procedural and an
19. Type object-oriented object-oriented
programming language. programming
language.

Java uses the (System


class): System.in for C++ uses cin for
Input-Output
20. input input and cout for
mechanism
and System.out for an output operation.
output.

Java doesn’t support C++ supports goto


21. goto Keyword
goto Keyword keyword.

Java doesn’t support C++ supports


Structures
22. Structures and Structures and
and Unions
Unions. Unions.

Java supports only C++ supports both


Parameter
23. the Pass by Value Pass by Value and
Passing
technique. pass by reference.

All classes in Java


are subclasses of the
A fresh inheritance
Inheritance Object class, hence
24. tree is always
Tree Java only ever
created in C++.
follows a single
inheritance tree.
Sl.
No. Parameters Java C++

It supports both
It supports no global
25. Global Scope global scope and
scope.
namespace scope.

It supports manual
Automatic object
Object object management
26. management with
Management using new and
garbage collection.
delete.

Call by Value C++ both supports


Java supports only
27. and Call by call by value and
call by value.
reference call by reference.

Java is not so
C++ is nearer to
28. Hardware interactive with
hardware.
hardware.

Game engines,
Machine learning,
Internet and Android
Operating systems,
games, Mobile
Google Search
applications,
Engine, Web
Language Used Healthcare and
29. browsers, Virtual
for research computation,
Reality (VR), Game
Cloud applications,
development, Medical
Internet of Things
technology,
(IoT) devices, etc.
Telecommunications,
Databases, etc.

Mozilla Firefox,
Wikipedia, LinkedIn, Amazon, Apple OS,
Application
30. Android OS, Uber, and Spotify, Adobe
built
Minecraft, Photoshop, and
Youtube

Setting up Environment Variables For Java

Setting up environment variables for Java is essential because it helps the system locate the Java
tools needed to run the Java programs. Before setting up the environment variables, the Java
Development Kit (JDK) needs to be installed on your system and you must know the JDK
installation directory on your system.
To set Java Environment Variables, you need to set,

• JAVA_HOME: It points to the directory where the JDK is installed on the system.

• PATH: It specifies where the operating system should look for executable files.

Setting the Environment Variables in Windows

Step 1: Download and install the latest JDK from the official Oracle website. To know how to
download JDK on Windows OS, refer to this article: How to Install Java on Windows, Linux and
macOS?

Step 2: Set JAVA_HOME

• Click Windows + S, search for “Environment Variables”, and click Edit the system
environment variables. In the System Properties window, click Environment Variables.

• Now, go to Environment Variable > System Variable section > click New.

in the Variable name field, enter JAVA_HOME and in the Variable value field enter the path where
the JDK is installed. Click OK to save the changes.
Step 3: Now we need to update the PATH variable. For this, open the C: drive, go to Program Files >
Java > jdk-23 > bin folder, then copy the path.

Go inside System Variables section, select the path variable. Right-click on it and choose the
option Edit. In the Edit environment window, click New

Then add the path to the JDK’s bin folder (e.g., C:\Program Files\Java\jdk-23\bin).
Click OK to save the changes.

Step 4: Now to verify the installation, open command Prompt and run the below commands:

java –version

To verify the Java compiler, run the below command:

Javac -version

Setting up Environment Variables in Linux


Step 1: After installing the JDK in Linux, We need to configure the system so that it can recognize
Java.

Step 2: Now we need to set JAVA_HOME. To do this,

Open the terminal and run the below command:

export JAVA_HOME=/path/to/your/jdk

Step 3: Update the PATH Variable on Linux

Add the JDK bin directory to the PATH, and run the below command in the terminal:

export PATH=$PATH:$JAVA_HOME/bin

Step 4: The above changes are temporary. To make the environment variable changes permanent,
you need to add the export commands to your shell’s configuration file. Depending on the shell you
are using.

• For bash use the command nano ~/.bashrc

• For zsh use the command nano ~/.zshrc

• For fish use the command nano ~/.config/fish/config.fish

Add the following commands at the end of the file.

export JAVA_HOME=/path/to/your/jdk

export PATH=$PATH:$JAVA_HOME/bin

After saving the file, run the following command to apply the changes:

source ~/.bashrc

This will set your JAVA_HOME and PATH variables on Linux permanently.

Step 5: Verify the Installation

To confirm the JAVA_HOME path, run the below command:

echo $JAVA_HOME

It should output the path of JDK Installer. If the output is empty that means
the JAVA_HOME environment variable is not set properly.

To confirm the updated PATH, run the below command:

echo $PATH

It should output the path of the bin directory to your JDK. If the output is empty that means
the PATH environment variable is not set properly. Then write java --version and javac -version to
verify the installation.

Setting up Environment Variables in macOS

Step 1: After installing the JDK in macOS, we need to configure the system so that it can recognize
Java.
Step 2: Now to set the JAVA_HOME and PATH environment variables permanently, we need to add
them to our shell’s configuration file depending on the shell we are using.

• For bash (if you have older version of macOS) run the command nano ~/.bash_profile

• For zsh(default shell for macOS 10.15 Catalina and later) run the command nano ~/.zshrc

Add the following commands at the end of the file:

export JAVA_HOME=$(/usr/libexec/java_home)

export PATH=$JAVA_HOME/bin:$PATH

Step 3: Now, we need to apply the changes.

For bash apply the changes by running the below command:

source ~/.bash_profile

For zsh apply the changes by running the below command:

source ~/.zshrc

Step 4: Verify the Installation

Check JAVA_HOME environment variable by running the below command:

echo $JAVA_HOME

It should output the path of JDK Installer. If the output is empty that means
the JAVA_HOME environment variable is not set properly.

Check PATH environment variable by running the below command:

echo $PATH

It should output the path of the bin directory to your JDK. If the output is empty that means
the PATH environment variable is not set properly.

Then write java --version and javac -version command to verify the installation on macOS.

After following these steps, your environment variable for Java will be set correctly, and you can
easily run Java programs from the terminal without any issues.

Java Syntax

ava is an object-oriented programming language which is known for its simplicity, portability, and
robustness. The syntax of Java programming language is very closely aligned with C and C++ which
makes it easier to understand. Let’s understand the Syntax and Structure of Java Programs with a
basic “Hello World” program.

Structure of Java Program

A basic Java program consists of several components that create a functional application:

// FileName : "GFG.java".
2

public class GFG {

// Program begins with a call to main() method

public static void main(String args[])

// Prints "Hello World"

10

System.out.println("Hello World");

11

12

Output

Hello World

Terminologies of a Basic Java Program

1. Class: The class is a blueprint (plan) of the instance of a class (object). It can be defined as a logical
template that share common properties and methods.

• Example 1: Blueprint of the house is class.

• Example 2: In real world, Alice is an object of the “Human” class.

2. Object: The object is an instance of a class. It is an entity that has behavior and state.

• Example: Dog, Cat, Monkey etc. are the object of “Animal” class.
• Behavior: Running on the road.

3. Method: The behavior of an object is the method.

• Example: The fuel indicator indicates the amount of fuel left in the car.

4. Instance Variables: Every object has its own unique set of instance variables. The state of an
object is generally created by the values that are assigned to these instance variables.

Example: Steps to compile and run a java program in a console

javac GFG.java
java GFG

Note: When the class is public, the name of the file has to be the class name.

Java Basic Syntax

1. Comments in Java

There are three types of comments in Java.

i. Single line Comment

// System.out.println("This is an comment.");

ii. Multi-line Comment

/*
System.out.println("This is the first line comment.");
System.out.println("This is the second line comment.");
*/

iii. Documentation Comment. Also called a doc comment.

/** documentation */

2. Source File Name

The name of a source file should exactly match the public class name with the extension of . java.
The name of the file can be a different name if it does not have any public class. Assume you have a
public class GFG.

GFG.java // valid syntax


gfg.java // invalid syntax

3. Case Sensitivity

Java is a case-sensitive language, which means that the identifiers AB, Ab, aB , and ab are different in
Java.

System.out.println("Hello World"); // valid syntax


system.out.println("Hello World"); // invalid syntax because of the first letter of System keyword is
always uppercase.

4. Class Names

• The first letter of the class should be in Uppercase (lowercase is allowed but discouraged).
• If several words are used to form the name of the class, each inner word’s first letter should
be in Uppercase. Underscores are allowed, but not recommended. Also allowed are numbers
and currency symbols, although the latter are also discouraged because they are used for a
special purpose (for inner and anonymous classes).

class MyJavaProgram // valid syntax


class 1Program // invalid syntax
class My1Program // valid syntax
class $Program // valid syntax, but discouraged
class My$Program // valid syntax, but discouraged (inner class Program inside the class My)
class myJavaProgram // valid syntax, but discouraged

5. public static void main(String [] args)

The method main() is the main entry point into a Java program; this is where the processing starts.
Also allowed is the signature public static void main(String… args) .

6. Method Names

• All the method names should start with a lowercase letter (uppercase is also allowed but
lowercase is recommended).

• If several words are used to form the name of the method, then each first letter of the inner
word should be in Uppercase. Underscores are allowed, but not recommended. Also allowed
are digits and currency symbols.

public void employeeRecords() // valid syntax


public void EmployeeRecords() // valid syntax, but discouraged

7. Identifiers in Java

• Identifiers are the names of local variables, instance and class variables, and labels, but also
the names for classes, packages, modules and methods. All Unicode characters are valid, not
just the ASCII subset.

• All identifiers can begin with a letter, a currency symbol or an underscore ( _ ). According to
the convention, a letter should be lower case for variables.

• The first character of identifiers can be followed by any combination of letters, digits,
currency symbols and the underscore. The underscore is not recommended for the names of
variables. Constants (static final attributes and enums) should be in all Uppercase letters.

• Most importantly identifiers are case-sensitive.

A keyword cannot be used as an identifier since it is a reserved word and has some special meaning.

Legal identifiers: MinNumber, total, ak74, hello_world, $amount, _under_value


Illegal identifiers: 74ak, -amount

8. White spaces in Java

A line containing only white spaces, possibly with the comment, is known as a blank line, and the
Java compiler totally ignores it.

9. Access Modifiers
These modifiers control the scope of class and methods.

• Access Modifiers: default, public, protected, private.

• Non-access Modifiers: final, abstract, static, transient, synchronized, volatile, native.

Access Within Within Outside Package by subclass Outside


Modifier Class Package only Package

Private Yes No No No

Default Yes Yes No No

Protected Yes Yes Yes No

Public Yes Yes Yes Yes

10. Java Keywords

Keywords or Reserved words are the words in a language that are used for some internal process or
represent some predefined actions. These words are therefore not allowed to use as variable names
or objects.

abstract assert boolean break

byte case catch char

class const continue default

do double else enum

extends final finally float

for goto if implements

import instanceof int interface


abstract assert boolean break

long native new package

private protected public return

short static strictfp super

switch synchronized this throw

throws transient try void

volatile while

Java Hello World Program

Java is one of the most popular and widely used programming languages and platforms. Java is fast,
reliable, and secure. Java is used in every nook and corner from desktop to web applications,
scientific supercomputers to gaming consoles, cell phones to the Internet. In this article, we will learn
how to write a simple Java Program.

Steps to Implement Java Program

Implementation of a Java application program involves the following steps. They include:

1. Creating the program

2. Compiling the program

3. Running the program

1. Creating Programs in Java

We can create a program using Text Editor (Notepad) or IDE (NetBeans)

class Test

public static void main(String[] args)

{
System.out.println("My First Java Program.");

File Save: d:\Test.java

2. Compiling the Program in Java

To compile the program, we must run the Java compiler (javac), with the name of the source file on
the “command prompt” like as follows

If everything is OK, the “javac” compiler creates a file called “Test.class” containing the byte code of
the program.

3. Running the Program in Java

We need to use the Java Interpreter to run a program. Java is easy to learn, and its syntax is simple
and easy to understand. It is based on C++ (so easier for programmers who know C++).

The process of Java programming can be simplified in three steps:

• Create the program by typing it into a text editor and saving it to a file – HelloWorld.java.

• Compile it by typing “javac HelloWorld.java” in the terminal window.

• Execute (or run) it by typing “java HelloWorld” in the terminal window.

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.

// This is a simple Java program.

// FileName : "HelloWorld.java".

class HelloWorld {

// Your program begins with a call to main().

// Prints "Hello, World" to the terminal window.

public static void main(String[] args)


8

System.out.println("Hello, World");

10

11

Output

Hello, World

1. Class Definition

This line uses the keyword class to declare that a new class is being defined.

class HelloWorld {

//

//Statements

2. HelloWorld

It is an identifier that is the name of the class. The entire class definition, including all of its members,
will be between the opening curly brace ” { ” and the closing curly brace ” } “.

3. main Method

In the Java programming language, every application must contain a main method. The main
function(method) is the entry point of your Java application, and it’s mandatory in a Java program.
whose signature in Java is:

public static void main(String[] args)

Explanation of the above syntax

• public : So that JVM can execute the method from anywhere.

• static : The main method is to be called without an object. The modifiers are public and static
can be written in either order.

• void : The main method doesn’t return anything.

• main() : Name configured in the JVM. The main method must be inside the class definition.
The compiler executes the codes starting always from the main function.
• String[] : The main method accepts a single argument, i.e., an array of elements of type
String.

Like in C/C++, the main method is the entry point for your application and will subsequently invoke
all the other methods required by your program.

The next line of code is shown here. Notice that it occurs inside the main() method.

System.out.println("Hello, World");

This line outputs the string “Hello, World” followed by a new line on the screen. Output is
accomplished by the built-in println( ) method. The System is a predefined class that provides access
to the system and out is the variable of type output stream connected to the console.

Comments

They can either be multiline or single-line comments.

// This is a simple Java program.

// Call this file "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 */.

Important Points

• The name of the class defined by the program is HelloWorld, which is the same as the name
of the file(HelloWorld.java). This is not a coincidence. In Java, all codes must reside inside a
class, and there is at most one public class which contains the main() method.

• By convention, the name of the main class(a class that contains the main method) should
match the name of the file that holds the program.

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

Compiling the Program

• After successfully setting up the environment, we can open a terminal in both Windows/Unix
and go to the directory where the file – HelloWorld.java is present.

• Now, to compile the HelloWorld program, execute the compiler – javac, to specify the name
of the source file on the command line, as shown:

javac HelloWorld.java

• The compiler creates a HelloWorld.class (in the current working directory) that contains the
bytecode version of the program. Now, to execute our program, JVM (Java Virtual Machine)
needs to be called using Java, specifying the name of the class file on the command line, as
shown:

java HelloWorld

• This will print “Hello World” to the terminal screen.

In Windows
In Linux

Java Identifiers

An identifier in Java is the name given to Variables, Classes, Methods, Packages, Interfaces, etc. These
are the unique names and every Java Variables must be identified with unique names.

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. There are 53 reserved words in Java.

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) and literals(3). Keywords define functionalities and literals define value.
Identifiers are used by symbol tables in various analyzing phases(like lexical, syntax, and semantic) of
a compiler architecture.

abstract continue for protected transient

Assert Default Goto public Try

Boolean Do If Static throws

break double implements strictfp Package

byte else import super Private

case enum Interface Short switch

Catch Extends instanceof return void

Char Final Int synchronized volatile

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 place of
const, the final keyword is used. Some keywords like strictfp are included in later versions of Java.

Java Keywords

In Java, Keywords are the Reserved words in a programming language that are used for some internal
process or represent some predefined actions. These words are therefore not allowed to use
as variable names or objects.
Example :

// Java Program to demonstrate Keywords

class GFG

public static void main(String[] args)

// Using final and int keyword

final int x = 10;

10

// Using if and else keywords

11

if(x>10){

12

System.out.println("Failed");

13

14

else{

15

System.out.println("Succesful Demonstration"
16

+" of keywords");

17

18

19

Output

Succesful 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.
They are listed below in the table with the primary action associated with them.

Keyword Usage

Specifies that a class or method will be implemented later, in a


abstract
subclass

Assert describes a predicate placed in a Java program to indicate


assert that the developer thinks that the predicate is always true at that
place.

boolean A data type that can hold True and False values only

break A control statement for breaking out of loops.

byte A data type that can hold 8-bit data values

case Used in switch statements to mark blocks of text


Keyword Usage

catch Catches exceptions generated by try statements

char A data type that can hold unsigned 16-bit Unicode characters

class Declares a new class

continue Sends control back outside a loop

default Specifies the default block of code in a switch statement

do Starts a do-while loop

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

else Indicates alternative branches in an if statement

A Java keyword is used to declare an enumerated type.


enum
Enumerations extend the base class.

extends Indicates that a class is derived from another class or interface

Indicates that a variable holds a constant value or that a method


final
will not be overridden

Indicates a block of code in a try-catch structure that will always be


finally
executed

float A data type that holds a 32-bit floating-point number

for Used to start a for loop


Keyword Usage

if Tests a true/false expression and branches accordingly

implements Specifies that a class implements an interface

import References other classes

Indicates whether an object is an instance of a specific class or


instanceof
implements an interface

int A data type that can hold a 32-bit signed integer

interface Declares an interface

long A data type that holds a 64-bit integer

Specifies that a method is implemented with native (platform-


native
specific) code

new Creates new objects

null This indicates that a reference does not refer to anything

package Declares a Java package

An access specifier indicating that a method or variable may be


private
accessed only in the class it’s declared in

An access specifier indicating that a method or variable may only


protected be 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)
Keyword Usage

An access specifier used for classes, interfaces, methods, and


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

Sends control and possibly a return value back from a called


return
method

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

Indicates that a variable or method is a class method (rather than


static
being limited to one particular object)

A Java keyword is used to restrict the precision and rounding of


strictfp
floating-point calculations to ensure portability.

Refers to a class’s base class (used in a method or class


super
constructor)

switch A statement that executes code based on a test value

synchronized Specifies critical sections or methods in multithreaded code

this Refers to the current object in a method or constructor

throw Creates an exception

throws Indicates what exceptions may be thrown by a method

transient Specifies that a variable is not part of an object’s persistent state

try Starts a block of code that will be tested for exceptions


Keyword Usage

void Specifies that a method does not have a return value

volatile This indicates that a variable may change asynchronously

while Starts a while loop

The sealed keyword is used to declare a class as “sealed,” meaning


sealed
it restricts which classes can extend it.

The permits keyword is used within a sealed class declaration to


permits
specify the subclasses that are permitted to extend it.

Example: Using the keywords as variables name. It will give an error as shown.

// Java Program to illustrate what if

// we use the keywords as the variable name

class GFG

public static void main(String[] args)

// Note "this" is a reserved

9
// word in java

10

String this = "Hello World!";

11

System.out.println(this);

12

13

Output:

./HelloWorld.java:6: error: not a statement


String this = "Hello World!"; System.out.println(this);
^
./HelloWorld.java:6: error: ';' expected
String this = "Hello World!"; System.out.println(this);
^
2 errors

Important Points:

• The keywords const and goto are reserved, even though they are not currently in use.

• Currently, they are no longer supported 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.

• What are the keywords of Java?


• Keywords are the reserved words in Java having certain
meanings. These words are not allowed to use as variable
names or object names.
• Java Data Types
ava is statically typed and also a strongly typed language because, in Java, each type of data (such as
integer, character, hexadecimal, packed decimal, and so forth) is predefined as part of the
programming language and all constants or variables defined for a given program must be described
with one of the Java data types.

Data types in Java are of different sizes and values that can be stored in the variable that is made as
per convenience and circumstances to cover up all test cases. Java has two categories in which data
types are segregated

1. Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double. The
Boolean with uppercase B is a wrapper class for the primitive data type boolean in Java.
2. Non-Primitive Data Type or Object Data type: such as String, Array, etc.

Example:

// Java Program to demonstrate int data-type

import java.io.*;

class GFG

public static void main (String[] args)

// declaring two int variables

int a = 10;

10

int b = 20;

11

12

System.out.println( a + b );

13

14

}
Output

30

Now, let us explore different types of primitive and non-primitive data types.

Data Types in JAVA

Primitive Data Types in Java

Primitive data are only single values and have no special capabilities. There are 8 primitive data
types. They are depicted below in tabular format below as follows:

Example
Type Description Default Size Literals Range of values

boolean true or false false 8 bits true, false true, false

twos-
complement 0 8 bits (none) -128 to 127
byte integer
Example
Type Description Default Size Literals Range of values

‘a’, ‘\u0041’, characters representation


Unicode of ASCII values
\u0000 16 bits ‘\101’, ‘\\’, ‘\’,
character
char ‘\n’, ‘β’ 0 to 255

twos-
complement 0 16 bits (none) -32,768 to 32,767
short integer

-2,147,483,648
twos-
complement 0 32 bits -2,-1,0,1,2 to
intger
int 2,147,483,647

-
twos- 9,223,372,036,854,775,808
-2L,-
complement 0 64 bits
1L,0L,1L,2L to
integer
long 9,223,372,036,854,775,807

1.23e100f , -
IEEE 754
0.0 32 bits 1.23e-100f , upto 7 decimal digits
floating point
float .3f ,3.14F

1.23456e300d
IEEE 754
0.0 64 bits , -123456e- upto 16 decimal digits
floating point
double 300d , 1e1d

Primitive Data Types

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)

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)

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)

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.

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.

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)

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.

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)

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:

// Java Program to Demonstrate Char Primitive Data Type

class GFG

4
{

public static void main(String args[])

// Creating and initializing custom character

char a = 'G';

10

11

// Integer data type is generally

12

// used for numeric values

13

int i = 89;

14

15

// use byte and short

16

// if memory is a constraint

17

byte b = 4;

18

19

// this will give error as number is


20

// larger than byte range

21

// byte b1 = 7888888955;

22

23

short s = 56;

24

25

// this will give error as number is

26

// larger than short range

27

// short s1 = 87878787878;

28

29

// by default fraction value

30

// is double in java

31

double d = 4.355453532;

32

33

// for float use 'f' as suffix as standard

34

float f = 4.7333434f;

35
36

// need to hold big range of numbers then we need

37

// this data type

38

long l = 12121;

39

40

System.out.println("char: " + a);

41

System.out.println("integer: " + i);

42

System.out.println("byte: " + b);

43

System.out.println("short: " + s);

44

System.out.println("float: " + f);

45

System.out.println("double: " + d);

46

System.out.println("long: " + l);

47

48

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:

// Declare String without using new operator


String s = "GeeksforGeeks";
// Declare String using new operator
String s1 = new String("GeeksforGeeks");

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:

1. Modifiers : A class can be public or has default access. Refer to access specifiers for classes or
interfaces in Java

2. Class name: The name should begin with an initial letter (capitalized by convention).

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

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

5. Body: The class body is surrounded by braces, { }.

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 :

1. State : It is represented by the attributes of an object. It also reflects the properties of an


object.

2. Behavior : It is represented by the methods of an object. It also reflects the response of an


object to other objects.

3. Identity : It gives a unique name to an object and enables one object to interact with other
objects.

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.

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.

Key Points to Remember

• Strong Typing: Java enforces strict type checking at compile-time, reducing runtime errors.

• Memory Efficiency: Choosing the right data type based on the range and precision needed
helps in efficient memory management.
• Immutability of Strings: Strings in Java cannot be changed once created, ensuring safety in
multithreaded environments.

• Array Length: The length of arrays in Java is fixed once declared, and it can be accessed using
the length attribute

• Java Variables
Variables are the containers for storing the data values or you can also
call it a memory location name for the data. Every variable has a:
• Data Type – The kind of data that it can hold. For example,
int, string, float, char, etc.
• Variable Name – To identify the variable uniquely within the
scope.
• Value – The data assigned to the variable.
There are three types of variables in Java – Local, Instance, and
Static.
Example:
int age = 27; // integer variable having value
27

String name = "gfg" // string variable


How to Declare Java Variables?
We can declare variables in Java as pictorially depicted below:
From the image, it can be easily perceived that while declaring a
variable, we need to take care of two things that are:
1. datatype: In Java, a data type define the type of data that a
variable can hold.
2. data_name: Name was given to the variable.
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:

Example:
// Declaring float variable
float simpleInterest;
// Declaring and initializing integer variable
int time = 10, speed = 20;

// Declaring and initializing character variable


char var = 'h';
Types of Java Variables
Now let us discuss different types of variables which are listed
as follows:
1. Local Variables
2. Instance Variables
3. Static Variables
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 after exiting from the block or when the call returns
from the function.
• The scope of these variables exists only within the block in
which the variables are declared, i.e., we can access these
variables only within that block.
• Initialization of the local variable is mandatory before using it
in the defined scope.
Example 1:
1
// Java Program to show the use of local variables
2
import java.io.*;
3

4
class GFG {
5
public static void main(String[] args)
6
{
7
// Declared a Local Variable
8
int var = 10;
9

10
// This variable is local to this main method only
11
System.out.println("Local Variable: " + var);
12
}
13
}

Output
Local Variable: 10

Example 2:
1
// Java Program to show the use of
2
// Local Variables
3
import java.io.*;
4
public class GFG {
5
public static void main(String[] args)
6
{
7
// x is a local variable
8
int x = 10;
9

10
// message is also a local
11
// variable
12
String message = "Hello, world!";
13

14
System.out.println("x = " + x);
15
System.out.println("message = " + message);
16

17
if (x > 5) {
18
// result is a
19
// local variable
20
String result = "x is greater than 5";
21
System.out.println(result);
22
}
23

24
// Uncommenting the line below will result in a
25
// compile-time error System.out.println(result);
26

27
for (int i = 0; i < 3; i++) {
28
String loopMessage
29
= "Iteration "
30
+ i; // loopMessage is a local variable
31
System.out.println(loopMessage);
32
}
33

34
// Uncommenting the line below will result in a
35
// compile-time error
36
// System.out.println(loopMessage);
37
}
38
}

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

2. Instance Variables
Instance variables are non-static variables and are declared in a class
outside of any method, constructor, or block.
• As instance variables are declared in a class, these 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:
1
// Java Program to show the use of
2
// Instance Variables
3
import java.io.*;
4

5
class GFG {
6

7
// Declared Instance Variable
8
public String geek;
9
public int i;
10
public Integer I;
11
public GFG()
12
{
13
// Default Constructor
14
// initializing Instance Variable
15
this.geek = "Shubham Jain";
16
}
17
18
// Main Method
19
public static void main(String[] args)
20
{
21
// Object Creation
22
GFG name = new GFG();
23

24
// Displaying O/P
25
System.out.println("Geek name is: " + name.geek);
26
System.out.println("Default value for int is "+ name.i);
27

28
// toString() called internally
29
System.out.println("Default value for Integer is "+ name.I);
30
}
31
}

Output
Geek name is: Shubham Jain
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:
1
// Java Program to show the use of
2
// Static variables
3
import java.io.*;
4

5
class GFG {
6
// Declared static variable
7
public static String geek = "Shubham Jain";
8

9
public static void main(String[] args)
10
{
11

12
// geek variable can be accessed without object
13
// creation Displaying O/P GFG.geek --> using the
14
// static variable
15
System.out.println("Geek Name is : " + GFG.geek);
16

17
// static int c = 0;
18
// above line, when uncommented,
19
// will throw an error as static variables cannot be
20
// declared locally.
21
}
22
}

Output
Geek Name is : Shubham Jain

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 GFG
{
// Static variable
static int a;

// Instance variable
int b;
}

Scope of Variables in Java

The scope of variables is the part of the program where the variable is
accessible. Like C/C++, in Java, all identifiers are lexically (or statically)
scoped, i.e. scope of a variable can be determined at compile time and
independent of the function call stack. In this article, we will learn
about Java Scope Variables.
Java Scope of Variables
Java Scope Rules can be covered under the following categories.
• Instance Variables
• Static Variables
• Local Variables
• Parameter Scope
• Block Scope
Now we will discuss all these Scopes and variables according to them.
1. Instance Variables – Class Level Scope
These variables must be declared inside class (outside any function).
They can be directly accessed anywhere in class. Let’s take a look at
an example:
public class Test {
// All variables defined directly inside a class
// are member variables
int a;
private String b;
void method1() {….}
int method2() {….}

char c;
}
• We can declare class variables anywhere in class, but outside
methods.
• Access specified of member variables doesn’t affect scope of
them within a class.
• Member variables can be accessed outside a class.
Access Modifiers and Member Variable Scope

Modifier Package Subclass World

public Yes Yes Yes

protected Yes Yes No

Default (no
Yes No No
modifier)

private No No No

2. Static Variables – Class Level Scope


Static Variable is a type of class variable shared across instances.
Static Variables are the variables which once declared can be used
anywhere even outside the class without initializing the class. Unlike
Local variables it scope is not limited to the class or the block.
Example:
1
// Using Static variables
2
import java.io.*;
3

4
class Test{
5
// static variable in Test class
6
static int var = 10;
7
}
8

9
class Geeks
10
{
11
public static void main (String[] args) {
12
// accessing the static variable
13
System.out.println("Static Variable : "+Test.var);
14
}
15
}

Output
Static Variable : 10

3. Method Level Scope – Local Variable


Variables declared inside a method have method level scope and can’t
be accessed outside the method.
public class Test {
void method1()
{
// Local variable (Method level scope)
int x;
}
}
Note: Local variables don’t exist after method’s execution is over.
4. Parameter Scope – Local Variable
Here’s another example of method scope, except this time the variable
got passed in as a parameter to the method:
class Test {
private int x;
public void setX(int x) {
this.x = x;
}
}
The above code uses this keyword to differentiate between the local
and class variables.
Example of Method and Parameter Scope:
1
// Using Method Scope and Parameter Scope
2
public class Geeks
3
{
4
// Class Scope variable
5
static int x = 11;
6

7
// Instance Variable
8
private int y = 33;
9

10
// Parameter Scope (x)
11
public void testFunc(int x) {
12
// Method Scope (t)
13
Geeks t = new Geeks();
14
this.x = 22;
15
y = 44;
16

17
// Printing variables with different scopes
18
System.out.println("Geeks.x: " + Geeks.x);
19
System.out.println("t.x: " + t.x);
20
System.out.println("t.y: " + t.y);
21
System.out.println("y: " + y);
22
}
23

24
// Main Method
25
public static void main(String args[]) {
26
Geeks t = new Geeks();
27
t.testFunc(5);
28
}
29
}

Output
Geeks.x: 22
t.x: 22
t.y: 33
y: 44

5. Block Level Scope


A variable declared inside pair of brackets “{” and “}” in a method has
scope within the brackets only.
Example:
1
// Using Block Scope
2
public class Test
3
{
4
public static void main(String args[])
5
{
6
// Block Level Scope
7
{
8
// The variable x has scope within
9
// brackets
10
int x = 10;
11
System.out.println(x);
12
}
13

14
// Uncommenting below line would produce
15
// error since variable x is out of scope.
16

17
// System.out.println(x);
18
}
19
}
Output:
10
Incorrect Usage of Local Variables
1. For Block Level Cases which are wrong
Let’s look at tricky example of loop scope. Predict the output of
following program. You may be surprised if you are regular C/C++
programmer.
Programs:
Case 1Case 2
1
class Test
2
{
3
public static void main(String args[])
4
{
5
// local variable declared
6
int a = 5;
7
8
// for loop variable declared
9
for (int a = 0; a < 5; a++)
10
{
11
System.out.println(a);
12
}
13
}
14
}
15

16

17
/*
18
Output:
19

20
6: error: variable a is already defined in method go(int)
21
for (int a = 0; a < 5; a++)
22
^
23
1 error
24
*/
Note: In C++, Program 1 will run. But in Java it is an error because in
Java, the name of the variable of inner and outer loop must be
different. A similar program in C++ works. See this.
2. Incorrect Way to use Local Variable – Block Scope
IncorrectCorrect
1
class Test
2
{
3
public static void main(String args[])
4
{
5
for (int x = 0; x < 4; x++)
6
{
7
System.out.println(x);
8
}
9

10
// Will produce error
11
System.out.println(x);
12
}
13
}
14

15

16
/*
17
Output:
18
11: error: cannot find symbol
19
System.out.println(x);
20

21
*/
Output:
0 1 2 3 4
Important Points about Variable Scope in Java
• In general, a set of curly brackets { } defines a scope.
• In Java we can usually access a variable as long as it was
defined within the same set of brackets as the code we are
writing or within any curly brackets inside of the curly
brackets where the variable was defined.
• Any variable defined in a class outside of any method can be
used by all member methods.
• When a method has the same local variable as a member,
“this” keyword can be used to reference the current class
variable.
• For a variable to be read after the termination of a loop, It
must be declared before the body of the loop.

You might also like