Java Documentatie

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 47

Java programming language

Java is one of the most popular and widely used programming languages.
 Java had been one of the most popular programming languages for many years.
 Java is Object Oriented. However, it is not considered as a pure object-oriented as it provides support for
primate data types (like int, char, etc)
 The Java codes are first compiled into byte code (machine-independent code). Then the byte code runs on Java
Virtual Machine (JVM) regardless of the underlying architecture.
 Java syntax is similar to C/C++. But Java does not provide low-level programming functionalities like pointes.
Also, Java codes are always written in the form of classes and objects.
 Java is used in all kinds of applications like Mobile Applications (Android is Java-based), desktop applications,
web applications, client -server applications, enterprise applications, and many more.
 When compared with C++, Java codes are generally more maintainable because Java does not allow many things
which may lead to bad/inefficient programming if used incorrectly. For example, non-primitives are always
references in Java. So we cannot pass large objects (like we can do in C++) to functions, we always pass
references in Java. One more example, since there are no pointes, bad memory access is also not possible.
 When compared with Python, Java kind of fits between C++ and Python. The programs are written in Java
typically run faster than corresponding Python programs and slower than C++. Like C++, java does static type
checking, but Python does not.

 The Java programming language is a fundamental programming language that every student should be skilled at
to have a successful career in software development. Start your journey with Java Programming Foundation –
Self Paced Course, which will help strengthen your Java basics concepts like, data types, operators, functions,
loops & much more.
 The Java Collections Framework is a collection of classes, interfaces, and methods that provides us with data
structures including LinkedList, ArrayList, HasMap, and others. Anyone with basic understanding of data
structures and Java foundations can enrol in Fundamentals of Java Collection Framework – Self Paced Course
and enhance their programming skills.

// A Java program to print "Hello World"


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

Output: Hello World

Java Tutorial
Java is one of the most popular and widely used programming language and platform. A platform is an
environment that helps to develop and run programs written in any programming language.
Java is fast, reliable and secure. From desktop to web applications, scientific supercomputers to gaming
consoles, cell phones to the internet, Java is used in every nook and corner.
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++). Java has removed many confusing and rarely-used features e.g. explicit pointers,
operator overloading etc. Java also takes care of memory management and for that, it provides an automatic
garbage collector. This collects the unused objects automatically.

1
Java Tutorial

Bellow is the complete guide as to how to get started with Java and make yourself proficient in it.
1. About Java: Before taking your step, the most important thing to do is to get the answer of all WHYs. Here it
refers to the questions like WHAT IS JAVA, WHY IT IS POPULAR, WHAT ARE ITS FEATURES, etc etc. By digging into
the mentioned article, you will not only learn the important thing about Java but also you will understand how to
start learning it. Learn about Java here: How to start learning Java
2. Java Environment: To work on any programming language, one first needs to know about its environment.
Environment refers to the circumstances where a programming language works and how the program works.
Java runs on JVM environment. Click on the mentioned article to know more about JVM, its architecture and
how it works. Learn about JVM here: JVM
3. Java Programming basics: To become proficient in any programming language, one Firstly needs to understand
the basics of the language. Therefore, this article will give you in-depth knowledge of the basics of Java in a very
simple format. By reading this article, you will get the topics from how to set up the Java Environment to the
details about its coding. Learn about Java Programming basic here: Java programming basics
4. Object Oriented Programming (OOPs) Concept in Java: Java is and object-oriented programming language. OOP
makes the complete program simpler by dividing in into a number of objects. The objects can be used as a bridge
to have data flow from one function to another. We can easily modify data and function as per the requirement.
Hence learning about OOPs concepts makes a very important step in learning Java. Learn about OOPs concepts
in Java here: Object Oriented Programming (OOPs) Concept in Java
5. Classes and Objects in Java: Classes and Objects are basic concepts in Object Oriented Programming which
revolve around the real-life entities and Java programming. It means that to implement anything in Java, Classes
and objects are made. This article will give you an insight about Classes and Objects and also help you reltate it
to the real worls. Learn about Classes and Objects in Java here: Classes and objects in Java
6. Constructor in Java: In Order to efficiently use Classes and Objects, one needs to know about the Constructors in
Java. Constructors are used to initialize the object’s state. Like methods, a constructor also contains collection of
statements (i.e. instructions) that are executed at time of Objects creations. Learn about Constructors in Java
here: Constructors in java
7. Methods in Java: A method is a collection of statements that perform some specific task and return result to the
caller. A method can perform some specific task without returning anything. Methods allow us to reuse the code
without retyping the code. In Java, every method must be a part of some class which is different from languages
like C. C++ and Python. Methods are time savers and help us to reuse the code without retyping the code. This
not only makes methods an important part of Java but also a must learn topic for learners. Learn about Methods
in Java here: Methods in Java
2
8. Strings in Java: Strings are defined as an array of characters. Java, unlike other programming languages, provides
a very easy implementation of Strings which can be learnt even by beginner. Hover over this mentioned article
to learn in depth about the Strings in Java. Learn about strings in Java here: Strings in Java
9. Arrays in Java: An array is a group of like-typed variables that are referred to by a common name. Array in Java
work differently than they do in C/C++. To know more, refer the mentioned article. Learn about Arrays In Java
here: Arrays in Java
10. Collections in Java: A Collection is a group of individual objects represented as a single unit. Java provides
Collection Framework which defines several classes and interfaces to represent a group of objects as a single
unit. Java Collection Framework is not the most important part in learning Data Structures and Algorithms, but
also it is the most useful module in a programming language. Learn about Collections in Java here: Collections in
Java
11. Generics in Java: Generics in Java is similar to templates in C++. The idea is to allow type (Integer, String, … etc
and user-defined types) to be a parameter to methods. Classes and interfaces. For example, classes like HashSet,
ArrayList, HashMap, etc, use generics very well. We can use them for any type. So not only Generics makes a
very important asset in programming, but it also makes the backbone of writing efficient code as well. Learn
about Generics in Java here: Generics in Jaca
12. Stream in Java: Introduces in Java 8, the Stream API is used to process collections of objects. A stream is a
sequence of objects that support various methods which can be pipelined to produce the desired result. Though
this was introduced later in Java, it has gained huge importance in the Java programming very quickly. To be able
to work on data fluently in Java, one must learn about the Streams. Learn about Streams in Java here: Streams
in Java
13. Exceptions and Exception Handling in Java: Manya times in the learning of Java till now, you must have come
across the world “EXCEPTION”. AN exception is an unwanted or unexpected event, which occurs during the
execution of a program i.e. at run time, that disrupts the normal flow of the program’s instruction. So to develop
a module that does not break, one has to learn how to handle exceptions. Learn about Exceptions and
Exception Handling in Java here: Exceptions and Exception Handling in Java
14. Regular Expression (ReGex) in Java: Thought this word might seen new to you, Regular Expression is a very
important part of Development. Regular Expression of Regex (in short) is an API for defining String patters that
can be used for searching, manipulating and editing text. It is widely used to define a constraint on strings such
as a password. Learn about Regular Expressions here: Regular Expression (ReGex) in Java
15. Multithreading in Java: Multithreading is a Java feature that allows concurrent execution of two or more parts
of a program for maximum utilization of CPU. Each part of such a program is called a thread. So, threads are
light-weight processes within a process. Though this might seem difficult at first, it’s a very important part of
concurrent programming in Java. Learn about Multithreading in Java here: Multithreading in Java
16. File Handling in Java: Java too supports file handling and allows users to handle files i.e. to read and write,
along with many other file handling options, to operate on file. The concept of file handling has stretched over
various other languages, but the implementation is either complicated or lengthy, but alike other concepts of
Java, this concept here is also easy and short. Learn about File Handling in Java here: File Handling in Java
17. Packages in Java: Package in Java is a mechanism to encapsulate a group of classes, sub packages and
interfaces. In other words, a package in Java refers to collection of classes, interfaces, abstract classes, and
exception that will help in a module in Java programming. Learn about Packages in Java here: Packages in Java

Introduction to Java
Java was develop by James Grosling at Sun Microsystems_Inc in the year 1991, later acquired by Oracle
Corporation. It is a simple programming language. Java makes writing, compiling, and debugging programming easy.
It helps to create reusable code and modular programs.
Java is a class-based, object-oriented programming language and is designed to have few implementation
dependencies as possible. A general purpose programming language made for developers to write once run
anywhere that is compiled Java code can run on all platforms that support Java. Java applications are compiled to
byte code that can run on any Java Virtual Machine. The syntax of Java is similar to C/C++.
History

3
Java’s history is very interesting. It is a programming language created in 1991. James Grosling, Mike Sheridan,
and Patrick Naughton, a team of Sun engineers known as the Green team initiated the Java language in 1991. Sun
microsystems released its first public implementation in 1996 as Java 1.0. It provides no-cost-run-times on popular
platforms. Java 1.0 compiler was re-written in Java by Arthur Van Hoff to strictly comply with its specifications. With
the arrival of Java 2, new versions had multiple configurations built for different types of platforms.
In 1997, Sun Microsystems approached the ISO standards body and later formalized Java, but it soon withdrew
from the process. At one time, Sun made most of its Java implementations available without charge, despite their
proprietary software status. Sun generated revenue from Java through the selling of licenses for specialized products
such as the Java Enterprise System.
On November 13, 2006, Sun released much of its Java virtual machine as free, open-source software. On May, 8,
2007, Sun finished the process, making all of its JVM’s core code available under open-source distribution terms.
The principle for creating Java were simple, robust, secured, high performance, portable, multi-threaded,
interpreted, dynamic, etc. In 1995 Java was developed by James Grosling, who is know as the Father of Java.
Currently, Java is used in mobile devices, internet programming, games, e-business, etc.

Java programming language is named JAVA. Why?


After the name OAK, the team decide to give a new name to it and the suggested words were Silk, Jolt,
revolutionary, DNA, dynamic, etc. These all names were easy spell and fun to say, but they all wanted the name to
reflect the essence of technology. In accordance with James Grosling, Java the among the top names along with SILK,
and since java was a unique name so most of them preferred it.
Java is the name of an island, in Indonesia, where the first coffee(named java coffee) was produces. And this
name was chosen by James Grosling while having coffee near his office. Note tha Java is just a name, not an
acronym.

Java terminology
Before learning Java, one must be familiar with these common term of Java.
1. Java Virtual Machine (JVM): This generally referred to as JVM. There are three executions phases of a
program. They are written, compile and run the program.
a. Writing a program is done by the java programmer like you and me.
b. 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.
c. In the Running phase of a program, JVM executes the bytecode generated by the compiler.
Now, we understood that the function of Java Virtual Machine is to execute the bytecode produced by the
compiler. Every Operating System has a different JVM but the output they produce after the execution of
bytecode is the same across all the operating systems. This is why Java is know as a platform-independent
language.
2. Bytecode in the Development process: As discussed, the JAVAC compiler of JDK compiles the java source
code into bytecode so that it can be executed by JVM. It is saved as .class file by the compiler. To view the
bytecode, a disassembler like JAVAP can be used.
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 supports, 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 Collector 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 object being referenced.

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

Primary/Main Features of Java


1. Platform Independent: Compiler converts source code to bytecode and then the JVM executes the bytecode
generated by the compiler. This bytecode can run on any platform be it Windows, Linux, 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
bytecode. That is why we call Java a platform-independent language.
2. Object-Oriented Programming Language: Organizing the program in terms of collection of objects is a way
of object-oriented programming, each of which represents and instance of the class.
The four main concepts of Object-Oriented programming are:
o Abstraction
o Encapsulation
o Inheritance
o Polumorphism
3. Simple: Java is one of the simple languages as it does not have complex features like pointes, operator
overloading, multiple inheritances, Explicit memory allocation.
4. Robust: 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 feature of java that make it robust are
garbage collection, Exception Handling and memory allocation.
5. Secure: In Java, we don’t have pointers, se 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 imposible to exploit in Java.
6. Distributed: We can create distributed applications using the java programming language. Remote Method
Invocation and Enterprise Java Beans are used for creating distributed application in Java. The Java programs
can be easily distributed on one or more systems that are connect to each other through an internet
connection.
7. Multithreading: Java supports multithreading. It is a Java feature that allows concurrent execution of two or
more parts of a program for maximum utilization of CPU.
8. Portable: 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.
9. High Performance: Java architecture is defined in such a way that it reduces overhead during the runtime
and at some time java uses Just in Time(JIT) compiler where the compiler compiles code on-demand basics
where is only compiles those methods that are called making applications to execute faster.
10. Dynamic flexibility: Java being completely object-oriented gives us the flexibility to add classes, new
methods to existing classes and even create new classes through sub-classes. Java even supports functions
written in other languages such C,C++ which are referred to as native methods.
11. Sandbox Execution: Java programs run in a separate space that allow user to execute their applications
without affecting the underlying system with help of a bytecode verifier. Bytecode verifier also provides
additional security as its role is to check the code for any violation of access.
12. Write Once Run Anywhere: As discussed above java application generates a ‘.class’ file which corresponds
to our application(program) but contains code in binary format. It provides ease t architecture-neutral easy
as bytecode is not dependent on any machine architecture. It is the primary reason java is used in the
enterprising IT industry globally worldwide.
13. Power of compilation and interpretation: Most languages are designed with purpose either they are
compiled language or they are interpreted language. But Java integrates arising enormous power as Java
compiler compile the source code to bytecode and JVM executes this bytecode to machine OS-dependent
executable code.

5
Example:

// Demo Java program

// Importing classes from packages


import java.io.*;

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{

// Print statement
System.out.println("Welcome to GeeksforGeeks");
}
}

Output
Welcone to GeeksforGeeks
Explanation:
1. Comments: Comments are used for explaining the code and are used in a similar manner in Java or C or C++.
Compiler ignore the comment entries and do not execute them. Comments can be of a single line or multiple
lines.
Single like Comments:
Syntax:
// Single line comment

Multi-line Comments:
Syntax:
/* Multi line comments*/
2. import java.io.*: This mean all the classes of io package can be imported. Java io package provides a set of
input and output streams for reading and writing date to files or other input or output sources.
3. class: The class contains the date and the methods to be used in the program. Methods define the behavior
of class. Class GFG has only one method Main in JAVA.
4. static void Main(): static keyword tells us that this method is accessible without instantiating the class
5. void: keywords tell that this method will not return anything. The main() method is the entry point of our
application.
6. System.in : This is the standard input stream that is used to read characters from the keyboard or any other
standard input device
7. System.out: This is the standard output stream that is used to produce the result of a program on an output
device like the computer screen.
8. println(): This method in Java is also used to display text on the console. It prints the text on the console and
the cursor moves to the start of the next line at the console. The next printing takes place from the next line.

Everything in java , is represented in Class as an object including the main function.


6
Introduction to Java
Nowdays Java and C++ programming languages are vastly used in competitive coding. Due to some features,
these two programming languages are widely used in industrie as well. C++ is a widely popular language among
coders for its efficiency, high speed, and dynamic memory utilization. Java is widely used in the IT industry, it is
incomparable to any other programming language in terms of software development.

Let’s go through the various points to compare these popular coding languages:
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 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 coverts the source code into the
machine code. That’s why C++ is faster than Java but not platform-independent.
Bellow is the illustration of how Java and C++ codes are executed:
Ececution of a Java Code

Ececution of a C++ Code

7
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 as 100% object-oriented languages. Java uses
primitive data types and thus cannot be termed as 100% Object-Oriented Language. C++ use 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 programming languages:

Features C++ Java


Abstraction Yes Yes
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

1. Applications: Both C++ and Java have vast areas of application. Below are the applications of both
languages:
 Application of C++ programming language:
1. Suitable for Developing large software (like passenger reservation system).
2. MySQL is written in C++.
3. For fast execution, C++ is majorly used in Game Development.
4. Google Chromium browser, file system, cluster data processing are all written in C++.
5. Adobe Premiere, Photoshop, and Illustrator; these popular application 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.
 Application 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.
2. Environment: C++ is 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++:

8
Parameters Java C++

C++ was developed by Bjarne


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

First Release On May 23, 1995 In October 1985

Java SE 14 or JDK 14 was released on March


Stable Release C++17 was released in December 2017.
17, 2020.

Official Website oracle.com/java isocpp.org

C++ was Influenced by Influenced by


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

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

Platform Platform independent, Java bytecode works Platform dependent, should be


Dependency on any operating system. compiled for different platforms.

C++ is platform-dependent. Hence it is


Portability It can run in any OS hence it is portable.
not portable.

Java is both Compiled and Interpreted


Compilation C++ is only Compiled Language.
Language.

Memory Memory Management in C++ is


Memory Management is System Controlled.
Management Manual.

Virtual Keyword It doesn’t have Virtual Keyword. It has Virtual Keyword.

It supports only single inheritance. Multiple


Multiple It supports both single and multiple
inheritances are archived partially using
Inheritance Inheritance.
interfaces.

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

Pointers It has limited support for pointers. It strongly supports pointers.

It supports direct system library calls,


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

Libraries have a wide range of classes for C++ libraries have comparatively low-
Libraries
various high-level services. level functionalities.

Documentation It supports documentation comments It doesn’t support documentation


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

C++ doesn’t have built-in support for


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

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

9
Parameters Java C++

language. oriented programming language.

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

goto Keyword Java doesn’t support goto Keyword C++ supports goto keyword.

Structures and
Java doesn’t support Structures and Unions. C++ supports Structures and Unions.
Unions

Java supports only the Pass by Value C++ supports both Pass by Value and
Parameter Passing
technique. pass by reference.

It supports both global scope and


Global Scope It supports no global scope.
namespace scope.

Object Automatic object management with It supports manual object management


Management garbage collection. using new and delete.

Setting up the environment in JAVA


Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, etc.
Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of
computer architecture. The latest version is Java 17. Below are the environment settings for both Linux and
Windows. JVM, JRE, and JDK three are all platform-dependent because the configuration of each Operating System is

10
different. But, Java is platform-independent. Few things must be clear before setting up the environment which can
better be perceived from the below image provide as follows:

 JDK(Java Development Kit): JDK is intended for software developers and includes development tools such as
the Java compiler, Javadoc, Jar, and a debugger.
 JRE(Java Runtime Environment): JRE contains the parts of the Java libraries required to run Java programs
and is intended for end-users. JRE can be viewed as a subset of JDK.
 JVM: JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides a runtime
environment in which Java bytecode can be executed. JVMs are available for many hardware and software
platforms.

Now let us discuss the steps for setting up a Java environment with visual aids. Let’s use the Windows operating
system to illustrate visual aids.
Steps: Here we will be proposing steps for three different operating systems as listed:
1. Windows operating system
2. Linux operating system
3. macOS operating system

A. Windows Operating System


Steps for setting the environment in Windows operating system are as follows:
Step 1: Java8 JDK is available at Download Java 8. Click the second last link for Windows(32 bit) and the last link
for Windows(64 bit) as highlighted below.

11
Step 2: After download, run the .exe file and follow the instructions to install Java on your machine. Once you
installed Java on your machine, you have to set up the environment variable.
Step 3: Go to Control Panel -> System and Security -> System. Under the Advanced System Setting option click
on Environment Variables as highlighted below.

Step 4: Now, you have to alter the “Path” variable under System variables so that it also contains the path to the
Java environment. Select “Path” variable and click on the Edit button as highlighted below.

Step 5: You will see a list of different paths, click on the New button, and then add the path where java is
installed. By default, java is installed in “C:/Program Files/Java/jdk/bin” folder or “C:/Program
files(x86)/Java/jdk/bin”. In case, you have installed java at any other location, then add that path.

12
Step 6: Click on OK, Save the settings, and you are done!! Now to check whether the installation is done
correctly, open the command prompt and type javac – version. You will see that java is running on your machine.
Note: To make sure whether the compiler is set up, type javac in the command prompt. You will see a list
related to javac.

B. Linux Operating System


In Linux, there are several ways to install java. But we will refer to the simplest and easy way to install java using
a terminal. For Linux, we will install OpenJDK. OpenJDK is a free and open-source implementation of the Java
programming language. Stept for setting the environment in the Linux operating system are as follows:
Step 1: Go to Application -> Accessories -> Terminal.
Stept 2: Type command as below as follows:
sudo apt-get install openjdk-8-jdk

Step 3: For the “JAVA_home” (Environment Variable) type command as shown below, in “Terminal” using your
installation path… (Note: the default path is as shown, but if you have to install OpenJDK at another location
then set that path.)
export JAVA_HOME = /usr/lib/jvm/java-8-openjdk

Step 4: For “PATH” (Environment Value) type command as shown below, in “Terminal” using your installation
path… Note: the default path is as shown, but if you have to install OpenJDK at another location then set that
path.)
export PATH = $PATH:/usr/lib/jvm/java-8-openjdk/bin
Note: We are done setting up the environment in Java for Linux OS

Note: Now to check whether the installation is done correctly, type java -version in the Terminal. You will
see that java
 Notepad/gedit: they are simple text-editor for writing java programs. Notepad is available on
Windows and gedit is available on Linux.
 Eclipse IDE: It is the most widely used IDE(Integrated Development Environment) for developing
software in Java. You can download Eclipse.

C. MacOS Operating System


Step 1: Open the terminal from the application folder or simply press “command” and “shift” key together and
write initials of the terminal and press enter.
It will be good to have pachage manager such as hombrew installed in you machine as we can operate to
install any software from here itself simply by using terminal commands.

Step 2: Now in order to configure first write the command ‘java -version’ where the message below it will pop
that there is no
java –version
javac –version

Note: If it was set up then you would have been getting the version displayed on the screen as it is shown
below where is that machine it was already set up. So remember to cross-check in your machine once
you have successfully set up in yours.

13
Step 3: Once we are done with installing JDK now let us move on setting up the Java home environment variable
for that you will have to look into something called s’bash_profile’ using the below command
ls -al
You will notice that in your terminal there will be no bash_profile set but it shown below so here in this machine
it is already set up. In order to set up if not there we have to create it for which lets up prior seek into java home
variables whether it is set up or not.

Step 4: Setting up the home java variable. Using the below command to check or setup if not installed as follows
on ther terminal:
echo $JAVA_HOME

If it is showing blank then the Java home variable is not set up as perceived from the above image.

Step 5: Installing bash_profile


Make sure to go to the root folder in the terminal and write the command ‘touch./bash_profile’

Now you will see that bash-profiles created which is as shown in step2 in your machine which hone can verify by
writing command as follows:
ls -al
14
Step 6: Edit the .bash_profile created and for java, you just have to write the command marked in below media
and provided below as follows:
export JAVA_HOME=$(/usr/libexec/java_home)
// no need to remember this command

Save this file and relaunch the terminal by closing it.

Step 7: Verifying whether it is installed by entering the following two commands


source .bash_profile
echo $JAVA_HOME

Now from the above media, we can see the java variable is all set to go as earlier there was a blank therein the
above media.
Java Basic Syntax
A Java program is a collection of objects, and these objects communicate through method calls to each other to
work together. Here is a brief discussion on the Classes and Objects, Method, Instance variables, syntax, and
semantics of Java.

Basic terminologies in Java


1. Class: The class is a blueprint(plan) of the instance of a class(object). It can be defined as a template which
describes the data and behavior associated with its instance.
 Example: Blueprint of the house is class.
2. Object: The object is an instance of a class. It is an entity which has behavior and state.
 Example: A car is an object whose states are: brand, colour, number-plate.
 Behaviour: Running on the road.
3. Method: the behaviour 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 is a console
javac GFG.java

15
java GFG

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

Output:
GFG!

Note: When the class is public, the name of the file has to be the class name.
The Basic Syntax:
1. Comments in Java
There are three types of comment in Java
- Single line Comment
//System.out.println(“GFG!”);
- Multi-line Comment
/*
System.out.println(“GFG!”);
System.out.println(“Alice!”);
*/
- 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.
GFC.java // valid syntax
gfg.java // invalid syntax

3. Case Sensitivity
Java in a case-sensitive language, which means that the indentifiers AB, Ab,aB, and ab are different in Java.
System.out.println(“Alice”); // valid syntax
system.out.printline(“Alice”); // invalid syntax

4. Class Names
a. The first letter of the class should be in Uppercase (lowercase is allowed, but not discouraged).
b. 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 the 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
in the signature public static void main(String… args).

16
6. Method names
a. All the method names should start with a lowercase letter.
b. 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, labels, but also the names for classes,
packages, modules and methods. All Unicode characters are valid, not just the ASCII subset.
a. 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.
b. 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.
c. Most importantly identifiers are case-sensitive.
d. 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 know as a blank line, and the Java compiler
totally ignores it.

9. Access Modifiers: These modifiers control the scope of class and methods.
a. Access Modifiers: default, public, protected, private
b. Non-Access Modifiers: final, abstract, strictfp

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
do double else enum
extends final finally float
for goto if implements
import instanceof int interface
long native new package
private protected public return
short static strictfp super
switch synchronized this throw
throws transient try void
volatile while

17
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.
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 windows.
 Execute (or run) it by typing “java HelloWorld” in the terminal windows.
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[])
18
{
System.out.println("Hello, World");
}
}

Output:
Hello, World

The “Hello World!” program consist of three primary components: the HelloWorld class definition, the main method,
and source code comments. The following explanation will provide you with basic understanding of the code:
1. Class definition
This line uses the keyword class to declare that a new class is being defined.
class HelloWorld

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 whose signature is:
public static void main(String[] args)
 public: So that JVM can execute the method from anywhere.
 static: The main method is to be called without an object. The modifiers public and static can be written
in either order.
 void: The main method doesn’t return anything.
 main(): Name configured in JVM.
 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 carriable 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.

Compiling the program

19
 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 reates 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

20

youtube video link: Beginning Java programming with HelloWorld Example

Differences between JDK,FRE and JVM


Java Development Kit (JDK) is a software development environment used for developing Java application and
applets. It includes the Java Runtime Environment(JRE), an interpreter/loader (Java), a compiler (javac), an archiver
(jar), a documentation generator (Javadoc), and other tools needed in Java development.

Now we need an environment to make a run of our program. Henceforth, JRE stands for “Java Runtime
Environment” and may also be written as “Java RTE”. The Java Runtime Environment provides the minimum
requirements for executing a Java application; it consist of the Java Virtual Machine(JVM), core classes, and
supporting files.

Now let us discuss JVM, which stands out for java virtual machine. It is as follows:
 A specification where the working of Java Virtual Machine is specified. But implementation provider is
independent to choose the algorithm. Its implementation has been provide by Sun and other companies.
 An implementation is a computer program that meets the requirements of the JVM specification.
 Runtime Instance Whenever you write a java command on the command prompt to run the java class,
an instance of JVM is created.

21
Before proceeding to the differences between JDK, JRE, and JVM, let us discuss them in brief first and interrelate
with the image below being proposed.

Don’t get confused as we are going to discuss all of them one by one.

1. JDK(Java Development Kit) is a Kit that provides the environment to develop and execute(run) the Java
program. JDK is a kit( or package) that includes two things
 Development Tools(to provide an environment to develop you java programs)
 JRE (to execute you java program)
2. JRE(Java Runtime Environment) is an installation package that provides an environment to only run(not
develop) the java program(or application) onto your machine. JRE is only used by those who only want to
run Java programs that are end-users of your system.
3. JVM (Java Virtual Machine) is a very important part of both JDK and JRE because it is contained or inbuilt in
both. Whatever Java program you run using JRE or JDK goes into JVM and JVM is responsible for executing
the java program line by line, hence it is also known as an interpreter.

Now let us discuss components of JRE in order to understand the importance of it and to perceive how it actually
works. For this let us discuss components.

The components of JRE is as follows:


1. Deployment technologies, including deployment, Java Web Start, and Java Plug-in.
2. User interface toolkits, including Abstract Windows Toolkit(AWT), Swing, Java 2D, Accesibility, Image I/O,
Print Service, Sound, drag, and drop (DnD), and input methods.
3. Integration libraries, including Interface Definition Language(IDL), Java Database Connectivity(JDBC), Java
Naming and Directory Interface(JNDI), Remote Method Invocation(RMI), Remote Method Invocation Over
Internet Inter-Orb Protocol(RMI-IIOP), and scripting.
4. Other base libraries, including international support, input/output(I/O), extension mechanism, Beans, Java
Management Extensions(JMX), Java Native Interface(JNI), Math, Networking, Override Mechanism, Security,
Serialization, and Java for XML Processing(XML JAXP).
5. Lang and util base libraries, including lang and util, management, versioning, zip, instrument, reflection,
Collections, Concurrency Utilities, Java Archive(JAR), Logging, Preferences API, Ref Objects, and Regular
Expressions.
6. Java Virtual Machine(JVM), including Java HotSpot Client and Server Virtual Machines.

After having an adequate understanding of the components, now let us discuss the working of JRE. In order to
understand how JRE works, let us consider and illustration below as follows:
22
Illustration:
Consider a java source file saved as ‘Example.java’. The file is compiled into a set of Byte Code that is
stored in a “.class” file. Here it will be “Example.class”.

Note: From above, media operation computing during the compile time can be interpreted.
The following actions occur at runtime as listed below:
 Class Loader
 Byte Code Verified
 Intrepreter
o Execute the Byte Code
o Make appropriate calls to the underlying hardware

Now let us discuss in brief how JVM do works out. It is as follows:


JVM becomes an instance of JRE at the runtime of a Java program. It is widely known as a runtime interpreter. JVM
largely helps in the abstraction of inner implementation from the programmers who make use of libraries for their
programs from JDK.
It is manly responsible for three activities.
 Loading
 Linking
 Initialization

Similarly, now let us discuss the working of JRE which is as follows:


 JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that actually
calls the main method present in a java code. JVM is a part of JRE(Java Runtime Environment).
 Java applications are called WORA(Write Once Run Anywhere). This means a programmer can develop Java
code on one system and can expect it to run on any other Java-enabled system without any adjustments.
This is all possible because of JVM.

23
 When we compile a .java file, .class files(contains byte-code) with the same class names present in .java file
are generated by the Java compiler. This .class file goes into various steps when we run it. These steps
together describe the whole JVM.

How JVM Works -JVM Architecture?


JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that actually calls the
main method present in a Java code. JVM is a part of JRE(Java Runtime Environment).

24
Java applications are called WORA(Write Once Run Anywhere). This means a programmer can develop Java code on
one system and can expect it to run on any other Java-enabled system without any adjustment. This is all possible
because of JVM.
When we compile a .java file, .class files(contains byte-code) with the same class names present in .java file are
generated by the Java compiler. This .class file goes into various steps when we run it. These steps together deschibe
the whole JVM.

Class Loader Subsystem


It is mainly responsible for three activities.
 Loading
 Lonking
 Initialization
Loading: The Class loader reads the “.class” file, generate the corresponding binary data and save it in the method
area. For each “.class” file, JVM stores the following information in the method area.

 The fully qualified name of the loaded class and its immediate parent class.
 Whether the “.class” file is related to Class or Interface or Enum.
 Modifier, Variables and Method information etc.

After loading the “.class” file, JVM creates and object of type Class to represent this file in the heap memory. Please
note that this object is of type Class predefined in java.lang package. These Class object can be used by the
programmer for getting class level information like the name of the class, parent name, methods and variable
information etc. To get his object reference we can use getClass() method of Object class.

// A Java program to demonstrate working


// of a Class type object created by JVM
// to represent .class file in memory.
import java.lang.reflect.Field;
import java.lang.reflect.Method;

// Java code to demonstrate use


// of Class object created by JVM
public class Test {
public static void main(String[] args)

25
{
Student s1 = new Student();

// Getting hold of Class


// object created by JVM.
Class c1 = s1.getClass();

// Printing type of object using c1.


System.out.println(c1.getName());

// getting all methods in an array


Method m[] = c1.getDeclaredMethods();
for (Method method : m)
System.out.println(method.getName());

// A sample class whose information


// is fetched above using its Class object.
class Student {
private String name;
private int roll_No;

public String getName() { return name; }


public void setName(String name) { this.name = name; }
public int getRoll_no() { return roll_No; }
public void setRoll_no(int roll_no)
{
this.roll_No = roll_no;
}
}

Output:
Student
getName
setName
getRoll_no
26
setRoll_no
name
roll_No

Note: For every loaded “.class” file, only one object of the class is created.

Student s2 = new Student();


// c2 will point to same object where
// c1 is pointing
Class c2 = s2.getClass();
System.out.println(c1==c2); // true

Linking: Performs verification, preparation, and (optionally) resolution.

 Verification: It ensures the correctness of the .class file i.e. it checks whether this file is properly formatted
and generated by a valid compiler or not. It verification fails, we get run-time exception
java.lang.VerifyError. This activity is done by the component ByteCodeVerifier. Once this activity is
completed then the class file is ready for compilation.
 Preparation: JVM allocates memory for class variables and initializing the memory to default values.
 Resolution: It is the process of replacing symbolic references from the type with direct references. It is done
by searching into the method area to locate the referenced entity.

Initialization: In this phase, all static variables are assigned with their values defined in the code and static block(if
any). This is executed from top to bottom in a class and from parent to child in the class hierarchy.
In general, there are three class loaders:
 Bootstrap class loader: Every JVM implementation must have a bootstrap class loader, capable of loading
trusted classes. It loads core java API classes present in the “JAVA_HOME/jre/lib” directory. This path is
popularly known as the bootstrap path. It is implemented in native languages like C, C++.
 Extension class loader: It is a child of the bootstrap class loader. It loads the classes present in the extension
directories “JAVA_HOME/jre/lib/ext”(Extension path) or any other directory specified by the java.ext.dirs
system property. It is implemented in java by the sun.misc.Launcher$ExtCLassLoader class.
 System/Application class loader: It is a child of the extension class loader. It is responsible to load classes
from the application classpath. It internally uses Environment Variable which mapped to java.class.path. It is
also implemented in Java by the sun.misc.Launcher$AppClassLoader class.

// Java code to demonstrate Class Loader subsystem


public class Test {
public static void main(String[] args)
{
// String class is loaded by bootstrap loader, and
// bootstrap loader is not Java object, hence null
System.out.println(String.class.getClassLoader());

// Test class is loaded by Application loader


System.out.println(Test.class.getClassLoader());
}
}

Output:
null
jdk.internal.loader.ClassLoaders$AppClassLoader@8bcc55f

27
Note: JVM follows the Delegation-Hierarchy principle to load classes. System class loader delegate load request to
extension class loader and extension class loader delegate request to the bootstrap class loader. If a class found in
the boot-strap path, the class is loaded otherwise request again transfers to the extension class loader and then to
the system class loader. At last, if the system class loader fails to load class, then we get run-time exception
java.lang.ClassNotFoundException.

JVM Memory

1. Method area: In the method area, all class level information like class name, immediate parent class name,
methods and variables information etc. are stored, including static variables. There is only one method area
per JVM, and is a shared resource.
2. Heap area: Information of all objects is stored in the heap area. There is also one Heap Area per JVM. It is
also a shared resource.
3. Stack area: For every thread, JVM creates one run-time stack which is stored here. Every block of this stack is
called activation record/stack frame which stores methods calls. All local variables of that method are stored
in their corresponding frame. After a thread terminates, its run-time stack will be destroyed by JVM. It is not
a shared resource.
4. PC Registers: Store address of current execution instruction of a thread. Obviously, each thread has separate
PC Registers.
5. Native method stacks: For every thread, a separate native stack is created. It stores native method
information.

Execution Engine
Execution engine executes the “.class” (bytecode). It reads the byte-code line by line, uses data and information
present in various memory area and executes instructions. It can be classified into three parts:

28
 Interpreter: It interprets the bytecode line by line and then executes. The disadvantage here is that when
one method is called multiple times, every time interpretation is required.
 Just-In-Time Compiler(JIT): It is used to increase the efficiency of an interpreter. It compiles the entire
bytecode and changes it to native code so whenever the interpreter sees repeated method calls, JIT provides
direct native code for that part so re-interpretation is not required, thus efficiency is improved.
 Garbage Collector: It destroys un-referenced objects. For more on Garbage Collector, refer Garbage
Collector.

Java Native Interface (JNI):


It is an interface that interacts with the Native Method Libraries and provides the native libraries(C, C++) required for
the execution. It enables JVM to call C/C++ libraries and to be called by C/C++ libraries which may be specific to
hardware.

Native Method Libraries:


It is a collection of the Native Libraries(C, C++) which are required by the Execution Engine.

Link YouTube: How Java Works?

Java Identifiers

29
In programming languages, identifiers are used for identification purposes. In Java, an identifier can be a class name,
method name, variable name, or label.
For example:

public class Test


{
public static void main(String[] args)
{
int a = 20;
}
}

In the above java code, we have 5 identifiers namely:


 Test: class name.
 main: method name.
 String: predefined class name.
 args: variable name.
 a: variable name.

Rules for defining Java Identifiers


There are certain rules for defining a valid java identifier. These rules must be followed, otherwise we get compile-
time error. These rules are also valid for other languages like C,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 contain ‘@’ special character.
 Identifiers should not start with digits([0-9]). For example “123geeks” is a not valid java identifier.
 Java identifiers are case-sensitive.
 There is not limit on the length of the identifier but it is advisable to use an optimum length of 4 – 15 letter
only.
 Reserved Words can’t be used as an identifier. For example “int while = 20;” is an invalid statement as while
is a reserved word. There are 53 reserved words in Java.

Example of valid identifiers:

MyVariable
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
geeks123

Example of invalid identifiers:

My Variable // contains a space


30
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
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 a value.
Identifiers are used by symbol tables in various analyzing phases(like lexical, syntax, 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 version of Java.

Link Youtube: Java Identifiers

Variables in Java

31
Variable in Java is a data container that saves the data values during Java program execution. Every variable is
assigned a data type that designates the type and quantity of value it can hold. Variable is a memory location name
of the data.

A variable is a name given to a memory location. It is the basic unit of storage in a program.
 The value stored in a variable can be changed during program execution.
 A variable is only a name given to a memory location, all the operations done on the variable effects that
memory location.
 In Java, all the variables must be declared before use.

How to declare variables?


We can declare variables in Java as pictorially depicted below as a visual aid.

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: Type of data that can be stored in this variable.
2. Dataname: 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 variables?


It can be perceived with the help of 3 components that are as follows:
 datatype: Type of data that can be stored in this variable.
 variable_name: Name given to the variable.
 value: It is the initial value stored in the variable.

Illustrations:

float simpleInterest;
// Declaring float variable
int time = 10, speed = 20;
// Declaring and Initializing integer variable
char var = 'h';
// Declaring and Initializing character variable
32
Types of Variables in Java
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 variable been up here in detail.

1. Local Variables
A variable defined within a block or method or constructor is called a local variable.
 These variables are created when the block is entered, or the function is called and destroyed after
exiting from the block or when the call returns from the functions.
 The scope of these variables exists only within the block in which the variable is 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.

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


// Contributed by Shubham Jain
import java.io.*;

class GFG {
public static void main(String[] args)
{
int var = 10; // Declared a Local Variable
// This variable is local to this main method only
System.out.println("Local Variable: " + var);
}
}

Output:
Local Variable: 10

2. Instance Variables
Instance variables are non-static variables and are declared in a class outside 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 no specify any access
specifier, then the default access specifier will be used.
 Initialization of Instance Variable is not Mandatory. Its default value is 0.
 Instance Variable can be accessed only by creating objects.

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

import java.io.*;

class GFG {

33
public String geek; // Declared Instance Variable

public GFG()
{ // Default Constructor

this.geek = "Shubham Jain"; // instializing Instance Variable


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

// Object Creation
GFG name = new GFG();
// Displaying O/P
System.out.println("Geek name is: " + name.geek);
}
}

Output:
Geek name is: Shubham Jain

3. Static Variables
Static variables are also known as Class variables.
 These variables are declared similarly as instance variables. The difference is that static variables are
declared using the static keyword withing a class outside 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 Static Variable is not Mandatory. Its default value is 0.
 If we access the static variable like the Instance variable(through an object), the compiler will show the
warning message, which won’t halt the program. The compiler will replace the object name with class
name automatically.
 If we access the static variable without the class name, the compiler will automatically append the class
name.

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

import java.io.*;

class GFG {

public static String geek = "Shubham Jain"; //Declared static


variable

public static void main (String[] args) {

//geek variable can be accessed withod object creation


//Displaying O/P
//GFG.geek --> using the static variable
System.out.println("Geek Name is : "+GFG.geek);
}
}
Output:
Geek Name is: Shubham Jain

34
Differences between the Instance variable VS. the Static variables:
Now let us to discuss the differences between the Instance variable vs. the Static variables.
 Each object will have its copy of the instance variable, whereas We can only have one copy of a static
variable per class irrespective of how many objects we create.
 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 static, 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.

Syntax: Static and instance variables.

class GFG
{
// Static variable
static int a;

// Instance variable
int b;
}

Link YouTube: Variables in JAVA

Must READ:
 Rules of Variable Declaration in Java
 Scope of Variables in Java
 Comparison of static keyword in C++ and Java
 Are static local variables allowed in Java?
 Instance Variable Hiding in Java

Scope of Variables in Java

35
Scope of variable 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 determined at compile time and independent of function
call stack.
Java programs are organized in the form of classes. Every class is part of some package. Java scope rules can be
covered under following categories.

Member 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 with following rules.

Modifier Package Subclass World

public Yes Yes Yes

protected Yes Yes No

Default (no
modifier) Yes No No

private No No No

Local Variables(Method Level Scope)


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.

Here’s another example of method scope, except this time the variable got passed in as a parameter to the method:

class Test

36
{
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.

As an exercise, predict the output of following Java program.


public class Test
{
static int x = 11;
private int y = 33;
public void method1(int x)
{
Test t = new Test();
this.x = 22;
y = 44;

System.out.println("Test.x: " + Test.x);


System.out.println("t.x: " + t.x);
System.out.println("t.y: " + t.y);
System.out.println("y: " + y);
}

public static void main(String args[])


{
Test t = new Test();
t.method1(5);
}
}

Output:

Test.x: 22
t.x: 22
t.y: 33
y: 44
Loop Variables(Block Scope)
A variable declared inside pair of brackets “{“ and “}” in a method has scope withing the brackets only.

public class Test


{
public static void main(String args[])
{
{
// The variable x has scope within
// brackets
int x = 10;
System.out.println(x);
}

// Uncommenting below line would produce


37
// error since variable x is out of scope.

// System.out.println(x);
}
}

Output:
10

As another example, consider following program with a for loop.

class Test
{
public static void main(String args[])
{
for (int x = 0; x < 4; x++)
{
System.out.println(x);
}

// Will produce error


System.out.println(x);
}
}

Output:
11: error: cannot find symbol
System.out.println(x);

The right way of doing above is,

// Above program after correcting the error


class Test
{
public static void main(String args[])
{
int x;
for (x = 0; x < 4; x++)
{
System.out.println(x);
}

System.out.println(x);
}
}

Output:
0
1
2
3
4

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.

38
class Test
{
public static void main(String args[])
{
int a = 5;
for (int a = 0; a < 5; a++)
{
System.out.println(a);
}
}
}

Output:
6: error: variable a is already defined in method go(int)
for (int a = 0; a < 5; a++)
^
1 error

Note: - In C++, it 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.

As an exercise, predict the output of the following Java program.

class Test
{
public static void main(String args[])
{
{
int x = 5;
{
int x = 10;
System.out.println(x);
}
}
}
}

Q. From the above knowledge, tell whether the below code will run or not.

class Test {
public static void main(String args[])
{
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
int i = 20;
System.out.println(i);
}
}

Output:

1
39
2
3
4
5
6
7
8
9
10
20

Yes, it will run!


See the program carefully, inner loop will terminate before the outer loop variable is declared. So the inner loop
variable is destroyed first and then the new variable of same name has been created.

Some 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 define 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.

Data types in Java

40
There are majorly two types of language:
 First, one is Statically typed language where each variable and expression type is already known at compile
time. Once a variable is declared to be of a certain data type, it cannot hold values of another data types.
Example: C, C++, Java.
 The other is Dynamically typed languages. These languages can receive different data types over time.
Example: Ruby, Python.

Java 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 apart of the programming language and all
constants of variables defined for a given program must be described with one of the data types.

Data Types in Java

Java has two categories of data:


 Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double.
 Non-Primitive Data Types or object Data type: such as String, Array, etc.

Primitive Data Type


Primitive data are only single values and have no special capabilities.

Types of Primitive Datatypes

41
There are 8 primitive data types. These are:
1. boolean: boolean data type represent only one bit of information either true or false, but the size of the
boolean data type is virtual machine-dependent. Values of type boolean are not converted implicitly or
explicitly (with casts) to any other type. But the programmer can easily write conversion code.

Syntax:
boolean booleanVar;

Size:
virtual machine dependent

Values:
true, false

Default Value:
false

// Java program to demonstrate boolean data type

class GeeksforGeeks {
public static void main(String args[])
{
boolean b = true;
if (b == true)
System.out.println("Hi Geek");
}
}

Output
Hi Geek

2. byte: 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 )

Values:
-128 to 127

Default Value:
0

// Java program to demonstrate byte data type in Java

class GeeksforGeeks {
public static void main(String args[])
{
byte a = 126;

// byte is 8 bit value

42
System.out.println(a);

a++;
System.out.println(a);

// It overflows here because


// byte can hold values from -128 to 127
a++;
System.out.println(a);

// Looping back within the range


a++;
System.out.println(a);
}
}

Output
126
127
-128
-127

3. short: The short data type is a 16-bit signed who’s complement integer. similar to byte, use a short to save
memory in large arrays, in situations where the memory savings actually matters.

Syntax:
short shortVar;

Size:
2 byte ( 16 bits )

Values:
-32, 768 to 32, 767 (inclusive)

Default Value:
0

4. int: It is a 32-bit signed two’s complement integer.

Syntax:
int intVar;

Size:
4 byte ( 32 bits )

Values:
-2, 147, 483, 648 to 2, 147, 483, 647 (inclusive)

Default Value:
0

Note: 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, 232-1]. Use the Integer class to use the int data type as an unsigned integer.
5. long: The long data type is a 64-bit two’s complement integer.

43
Syntax:
long longVar;

Values:
-9, 223, 372, 036, 854, 775, 808
to
9, 223, 372, 036, 854, 775, 807
(inclusive)

Default Value:
0

Note: 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 maximum value of 2 66-1. The Long class also contains methods like comparing Unsigned,
divide Unsigned, etc to support arithmetic operations for unsigned long.

6. float: The float data type is a single-precision 32-bit IEEE 754 floating-point. Use float (instead of double) if
you need to save memory in large arrays of floating-point numbers.

Syntax:
float floatVar;

Size:
4 byte ( 32 bits )

Values:
upto 7 decimal digits

Default Value:
0.0

7. double: The double data type is a a double-precision 64-bit IEEE 754 floating-point. For decimal values, this
data type is generally the default choice.

Syntax:
double doubleVar;

Size:
8 byte ( 64 bits )

Values:
upto 16 decimal digits

Default Value:
0.0

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. Please see this for details: Rounding off errors in Java

8. char: The char data type is a single 16-bit Unicode character.


Syntax:
char charVar;

44
Size:
2 byte ( 16 bits )

Values:
'\u0000' (0) to '\uffff' (65535)

Default Value:
'\u0000'

Why is the size of char is 2 bytes in java...?


In other languages like C/C++ uses only ASCII characters and to represent all ASCII characters 8-bits is enough.
But java uses the Unicode system not the ASCII code system and to represent Unicode system 8 bit is not enough to
represent all characters so java uses 2 bytes for characters.
Unicode define a fully international character set that can represent most of the world’s written languages. It is a
unification of dozens of characters sets, such as Latin, Greeks, Cyrillic, Katakana, Arabic, and many more.


// Java program to demonstrate
// primitive data types in Java

class GeeksforGeeks {
public static void main(String args[])
{
// declaring character
char a = 'G';

// Integer data type is generally


// used for numeric values
int i = 89;

// use byte and short

short s = 56;

// this will give error as number is


// larger than short range
// short s1 = 87878787878;

// by default fraction value


// is double in java
double d = 4.355453532;

// for float use 'f' as suffix


float f = 4.7333434f;

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


System.out.println("integer: " + i);
System.out.println("byte: " + b);
System.out.println("short: " + s);
System.out.println("float: " + f);
System.out.println("double: " + d);
}
}
Output:
char: G

45
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532

Non-Primitive Data type or Reference Data Types

The Reference Data Type will contain a memory address of variable values because the reference types won’t store
the variable value directly in memory. There are strings, objects, arrays, etc.

 String: Strings are defined as an array of characters. The difference between a character array and a string in
Java is, 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. Below is the basic syntax for declaring a
string in Java programming language.

Syntax:
<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");

1. 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:
a. Modifiers: A class can be public or has default access (Refer to Access specifiers for classes or interfaces
in Java for details).
b. Class name: The name should begin with an initial letter (capitalized by convention).
c. 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.
d. 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.
e. Body: The class body surrounded by braces, { }.
2. Object: It 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:
a. State: It is represented by attributes of an object. It also reflects the properties of an object.
b. Behavior: It is represented by the methods of an object. It also reflects the response of an object with
other objects.
c. Identity: It gives a unique name to an object and enables one object to interact with other objects.
3. Interface: Like a class, and interface can have methods and variables, but the method declared in an
interface are by default abstract (only method signature, nobody).
 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.
 It 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.

46
 A Java library example is Comparator Interface. If a class implements this interface, then it can be
used to sort a collection.
4. 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 from 0.
 Java array can be also be used as a static filed, a local variable, or a method parameter.
 The size of an array must be specified by an int value and no long or short.
 The direct superclass of an array type is Object.
 Every array type implements the interfaces Cloneable and java.io.Serializable.

YouTube link: Java programming Tutorial / Data types in Java


Quiz in Data Type in Java

47

You might also like