Introduction to Java
Introduction to Java
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 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.
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.
• 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
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.
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.
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
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.
• 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.
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.
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.
• 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.
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.
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:
Pointers Yes No
API No Yes
Syntax Difference:
Syntax of c++:
#include <iostream>
using namespace std;
int main() {
syntax of java
Java
import java.io.*;
class GFG {
public static void main (String[] args) {
System.out.println("GFG!");
}
}
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++ is platform-
It can run on any OS
8. Portability dependent. Hence it
hence it is portable.
is not portable.
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 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.
C++ is both a
Java is only an procedural and an
19. Type object-oriented object-oriented
programming language. programming
language.
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.
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 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.
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?
• 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
Javac -version
export JAVA_HOME=/path/to/your/jdk
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.
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.
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.
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.
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
export JAVA_HOME=$(/usr/libexec/java_home)
export PATH=$JAVA_HOME/bin:$PATH
source ~/.bash_profile
source ~/.zshrc
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.
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.
A basic Java program consists of several components that create a functional application:
// FileName : "GFG.java".
2
10
System.out.println("Hello World");
11
12
Output
Hello World
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.
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.
• 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.
javac GFG.java
java GFG
Note: When the class is public, the name of the file has to be the class name.
1. Comments in Java
// System.out.println("This is an comment.");
/*
System.out.println("This is the first line comment.");
System.out.println("This is the second line comment.");
*/
/** documentation */
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.
3. Case Sensitivity
Java is a case-sensitive language, which means that the identifiers AB, Ab, aB , and ab are different in
Java.
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).
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.
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.
A keyword cannot be used as an identifier since it is a reserved word and has some special meaning.
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.
Private Yes No No No
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.
volatile while
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.
Implementation of a Java application program involves the following steps. They include:
class Test
{
System.out.println("My First Java Program.");
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.
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++).
• Create the program by typing it into a text editor and saving it to a file – HelloWorld.java.
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.
// FileName : "HelloWorld.java".
class HelloWorld {
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:
• static : The main method is to be called without an object. The modifiers are public and static
can be written in either order.
• 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
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).
• 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
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:
• a: Variable Name
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.
• 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.
MyVariable
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
geeks123
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.
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 :
class GFG
10
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
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
boolean A data type that can hold True and False values only
char A data type that can hold unsigned 16-bit Unicode characters
Example: Using the keywords as variables name. It will give an error as shown.
class GFG
9
// word in java
10
11
System.out.println(this);
12
13
Output:
Important Points:
• The keywords const and goto are reserved, even though they are not currently in use.
• 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.
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:
import java.io.*;
class GFG
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.
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
twos-
complement 0 8 bits (none) -128 to 127
byte integer
Example
Type Description Default Size Literals Range of values
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
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;
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;
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;
Syntax:
int intVar;
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.
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;
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.
Syntax:
float floatVar;
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;
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.
The char data type is a single 16-bit Unicode character with the size of 2 bytes (16 bits).
Syntax:
char charVar;
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:
class GFG
4
{
char a = 'G';
10
11
12
13
int i = 89;
14
15
16
// if memory is a constraint
17
byte b = 4;
18
19
21
// byte b1 = 7888888955;
22
23
short s = 56;
24
25
26
27
// short s1 = 87878787878;
28
29
30
// is double in java
31
double d = 4.355453532;
32
33
34
float f = 4.7333434f;
35
36
37
38
long l = 12121;
39
40
41
42
43
44
45
46
47
48
Output
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121
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.
Example:
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.
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 :
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.
• 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.
• 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
Example:
// Declaring float variable
float simpleInterest;
// Declaring and initializing integer variable
int time = 10, speed = 20;
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 variable
int b;
}
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
Default (no
Yes No No
modifier)
private No No No
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
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
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.