Java Documentatie
Java Documentatie
Java Documentatie
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.
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 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.
5
Example:
// Main class
public class GFG {
// 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.
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
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:
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.
8
Parameters Java C++
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.
It supports only method overloading and It supports both method and operator
Overloading
doesn’t allow operator overloading. overloading.
Libraries have a wide range of classes for C++ libraries have comparatively low-
Libraries
various high-level services. level functionalities.
Type Java is only an object-oriented programming C++ is both a procedural and an object-
9
Parameters Java C++
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.
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
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.
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.
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.
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
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.
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 */
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
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
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.
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.
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
In WINDOWS
In LINUX
20
▲
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.
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
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.
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.
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.
25
{
Student s1 = new Student();
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.
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.
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 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:
MyVariable
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
geeks123
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.
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.
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
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
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.
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.
import java.io.*;
class GFG {
33
public String geek; // Declared Instance Variable
public GFG()
{ // Default Constructor
// 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.
import java.io.*;
class GFG {
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.
class GFG
{
// Static variable
static int a;
// Instance variable
int b;
}
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
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.
Default (no
modifier) Yes No No
private No No No
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.
▲
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;
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.
// System.out.println(x);
}
}
Output:
10
class Test
{
public static void main(String args[])
{
for (int x = 0; x < 4; x++)
{
System.out.println(x);
}
Output:
11: error: cannot find symbol
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.
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
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.
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
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
class GeeksforGeeks {
public static void main(String args[])
{
byte a = 126;
42
System.out.println(a);
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
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
44
Size:
2 byte ( 16 bits )
Values:
'\u0000' (0) to '\uffff' (65535)
Default Value:
'\u0000'
▲
// Java program to demonstrate
// primitive data types in Java
class GeeksforGeeks {
public static void main(String args[])
{
// declaring character
char a = 'G';
short s = 56;
45
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
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";
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.
47