Java
Java
Object-oriented programming (OOP) is at the core of Java. In fact, all Java programs are to at
least some extent object-oriented. OOP is so integral to Java that it is best to understand its
basic principles before you begin writing even simple Java programs. Therefore, this chapter
begins with a discussion of the theoretical aspects of OOP.
Two Paradigms
All computer programs consist of two elements: code and data. Furthermore, a program can
be conceptually organized around its code or around its data. That is, some programs are written
around “what is happening” and others are written around “who is being affected.” These
are the two paradigms that govern how a program is constructed. The first way is called the
process-oriented model. This approach characterizes a program as a series of linear steps (that
is, code). The process-oriented model can be thought of as code acting on data. Procedural
languages such as C employ this model to considerable success. However, as mentioned in
Chapter 1, problems with this approach appear as programs grow larger and more complex. To
manage increasing complexity, the second approach, called object-oriented programming, was
conceived. Object-oriented programming organizes a program around its data (that is, objects)
and a set of well-defined interfaces to that data. An object-oriented program can be
characterized as data controlling access to code. As you will see, by switching the controlling
entity to data, you can achieve several organizational benefits.
Java OOP (Object Oriented Programming) Concepts
Example:
// Use of Object and Classes in Java
import java.io.*;
class Numbers {
// Properties
private int a;
private int b;
// Methods
public void sum() { System.out.println(a + b); }
Output
3
-1
It is a simple example showing a class Numbers containing two variables which can be
accessed and updated only by instance of the object created.
Java 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. Using classes, you
can create multiple objects with the same behavior instead of writing their code multiple times.
This includes classes for objects occurring more than once in your code. In general, class
declarations can include these components in order:
1. Modifiers: A class can be public or have default access (Refer to this for details).
2. Class name: The class name should begin with the initial letter capitalized by convention.
3. Body: The class body is surrounded by braces, { }.
Java Object
Example:
// Java Program to demonstrate
// Use of Class and Objects
// Class Declared
public class GFG {
// Properties Declared
static String Employee_name;
static float Employee_salary;
// Methods Declared
static void set(String n, float p) {
Employee_name = n;
Employee_salary = p;
}
// Main Method
public static void main(String args[]) {
GFG.set("Rathod Avinash", 10000.0f);
GFG.get();
}
}
Output
Employee name is: Rathod Avinash
Employee CTC is: 10000.0
Method and Method Passing
A method is a collection of statements that perform specific tasks and return a result to the
caller. It can be declared with or without arguments, depending on the requirements. A method
can take input values, perform operations, and return a result.
// Class Method and Method Passing
import java.io.*;
class Student {
// Properties Declared
int id;
String name;
// Printing Student
public void printStudent()
{
System.out.println("Id:" + id);
System.out.println("Name:" + name);
}
}
class GFG {
public static void main(String[] args)
{
Student obj = new Student();
obj.id = 1;
obj.name = "ABC";
obj.printStudent();
}
}
Output
Id:1
Name:ABC
1. Abstraction
Data Abstraction is the property by virtue of which only the essential details are displayed to
the user. The trivial or non-essential units are not displayed to the user.
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the car speed or applying brakes will stop the car, but he does not
know how on pressing the accelerator, the speed is actually increasing. He does not know about
the inner mechanism of the car or the implementation of the accelerators, brakes etc. in the car.
This is what abstraction is.
Note: In Java, abstraction is achieved by interfaces and abstract classes. We can achieve 100%
abstraction using interfaces.
Example:
// abstract class
abstract class GFG {
// abstract methods declaration
abstract void add();
abstract void mul();
abstract void div();
}
2. Encapsulation
It is defined as the wrapping up of data under a single unit. It is the mechanism that binds
together the code and the data it manipulates. Another way to think about encapsulation is that
it is a protective shield that prevents the data from being accessed by the code outside this
shield.
a) Technically, in encapsulation, the variables or the data in a class is hidden from any
other class and can be accessed only through any member function of the class in which
they are declared.
b) In encapsulation, the data in a class is hidden from other classes, which is similar to
what data-hiding does. So, the terms “encapsulation” and “data-hiding” are used
interchangeably.
c) Encapsulation can be achieved by declaring all the variables in a class as private and
writing public methods in the class to set and get the values of the variables.
Example:
// Encapsulation using private modifier
// Setter methods
public void set_id(int empid) {
this.empid = empid;
}
// Getter methods
public int get_id() {
return empid;
}
3. Inheritance
a) Superclass: The class whose features are inherited is known as superclass (also known
as base or parent class).
b) Subclass: The class that inherits the other class is known as subclass (also known as
derived or extended or child class). The subclass can add its own fields and methods in
addition to the superclass fields and methods.
c) Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to
create a new class and there is already a class that includes some of the code that we
want, we can derive our new class from the existing class. By doing this, we are reusing
the fields and methods of the existing class.
Example:
// base class or parent class or super class
class A{
// parent class methods
void method1(){}
void method2(){}
}
4. Polymorphism
// Parent Class
class Parent {
// Method Declared
public void func(){
System.out.println("Parent Method func");
}
// Method Overloading
public void func(int a){
System.out.println("Parent Method func " + a);
}
}
// Child Class
class Child extends Parent {
// Method Overriding
@Override
public void func(int a){
System.out.println("Child Method " + a);
}
}
// Main Method
public class Main {
public static void main(String args[]){
Parent obj = new Child();
obj.func(4);
}
}
Output
Child Method 4
a) OOP promotes code reusability: By using objects and classes, you can create reusable
components, leading to less duplication and more efficient development.
b) OOP enhances code organization: It provides a clear and logical structure, making
the code easier to understand, maintain, and debug.
c) OOP supports the DRY (Don’t Repeat Yourself) principle: This principle
encourages minimizing code repetition, leading to cleaner, more maintainable code.
Common functionalities are placed in a single location and reused, reducing
redundancy.
d) OOP enables faster development: By reusing existing code and creating modular
components, OOP allows for quicker and more efficient application development
Compiler converts source code to byte code and then the JVM executes the bytecode
generated by the compiler. This byte code can run on any platform be it Windows, Linux, or
macOS which means if we compile a program on Windows, then we can run it on Linux and
vice versa. Each operating system has a different JVM, but the output produced by all the
OS is the same after the execution of the byte code. That is why we call java a platform-
independent language.
2. Object-Oriented Programming
Java is an object-oriented language, promoting the use of objects and classes. Organizing
the program in the terms of a collection of objects is a way of object-oriented programming,
each of which represents an instance of the class.
The four main concepts of Object-Oriented programming are:
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism
3. Simplicity
Java’s syntax is simple and easy to learn, especially for those familiar with C or C++. It
eliminates complex features like pointers and multiple inheritances, making it easier to write,
debug, and maintain code.
4. Robustness
Java language is robust which means reliable. It is developed in such a way that it puts a
lot of effort into checking errors as early as possible, that is why the java compiler is able to
detect even those errors that are not easy to detect by another programming language. The
main features of java that make it robust are garbage collection, exception handling, and
memory allocation.
5. Security
6. Distributed
We can create distributed applications using the java programming language. Remote
Method Invocation and Enterprise Java Beans are used for creating distributed applications
in java. The java programs can be easily distributed on one or more systems that are
connected to each other through an internet connection.
7. Multithreading
8. Portability
As we know, java code written on one machine can be run on another machine. The platform-
independent feature of java in which its platform-independent bytecode can be taken to any
platform for execution makes java portable. WORA(Write Once Run Anywhere) makes
java application to generates a ‘.class’ file that corresponds to our applications(program) but
contains code in binary format. It provides architecture-neutral ease, as bytecode is
independent of any machine architecture. It is the primary reason java is used in the
enterprising IT industry globally worldwide.
9. High Performance
Java architecture is defined in such a way that it reduces overhead during the runtime and
at some times java uses Just In Time (JIT) compiler where the compiler compiles code on-
demand basis where it only compiles those methods that are called making applications to
execute faster.
How Java Code Executes?
Write your first Java program with ‘First Java Program: Hello World‘.
Essential Java Terminologies You Need to Know
Before learning Java, one must be familiar with these common terms of Java.
The JVM is an integral part of the Java platform, responsible for executing Java bytecode.
It ensures that the output of Java programs is consistent across different platforms.
Bytecode is the intermediate representation of Java code, generated by the Java compiler. It
is platform-independent and can be executed by the JVM.
While we were using the term JDK when we learn about bytecode and JVM. So, as the name
suggests, it is a complete Java development kit that includes everything
including compiler, Java Runtime Environment (JRE), Java Debuggers, Java Docs, etc.
For the program to execute in java, we need to install JDK on our computer in order to create,
compile and run the java program.
JDK includes JRE. JRE installation on our computers allows the java program to run,
however, we cannot compile it. JRE includes a browser, JVM, applet support, and plugins.
For running the java program, a computer needs JRE.
5. Garbage Collector
In Java, programmers can’t delete the objects. To delete or recollect that memory JVM has a
program called Garbage Collector. Garbage Collectors can recollect the objects that are not
referenced. So Java makes the life of a programmer easy by handling memory
management. However, programmers should be careful about their code whether they
are using objects that have been used for a long time. Because Garbage cannot recover
the memory of objects being referenced.
6. ClassPath
The Classpath is the file path where the java runtime and Java compiler look for .class files
to load. By default, JDK provides many libraries. If you want to include external libraries,
they should be added to the classpath.
Basically everything in java is represented in Class as an object including the main function.
Advantages of Java
a) Platform independent: Java code can run on any platform that has a Java Virtual
Machine (JVM) installed, which means that applications can be written once and run
on any device.
b) Object-Oriented: Java is an object-oriented programming language, which means
that it follows the principles of encapsulation, inheritance, and polymorphism.
c) Security: Java has built-in security features that make it a secure platform for
developing applications, such as automatic memory management and type checking.
d) Large community: Java has a large and active community of developers, which
means that there is a lot of support available for learning and using the language.
e) Enterprise-level applications: Java is widely used for developing enterprise-level
applications, such as web applications, e-commerce systems, and database systems.
Disadvantages of Java
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 an 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 this 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;
Output
Student
getName
setName
getRoll_no
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
a) 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. If 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.
b) Preparation: JVM allocates memory for class static variables and initializing the
memory to default values.
c) 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/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 extensions 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());
Output
null
jdk.internal.loader.ClassLoaders$AppClassLoader@8bcc55f
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.
2. Class Loaders
Example:
public class Test {
public static void main(String[] args) {
System.out.println(String.class.getClassLoader());
System.out.println(Test.class.getClassLoader());
}
}
a) 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 it is a shared
resource.
b) 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.
c) 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.
d) PC Registers: Store address of current execution instruction of a thread. Obviously,
each thread has separate PC Registers.
e) Native method stacks: For every thread, a separate native stack is created. It stores
native method information.
4. 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:
1. 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.
2. 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.
3. Garbage Collector: It destroys un-referenced objects. For more on Garbage Collector,
refer Garbage Collector.
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.
These are collections of native libraries required for executing native methods. They include
libraries written in languages like C and C++.
Java Syntax
Java is an object-oriented programming language that is known for its simplicity, portability,
and robustness. The syntax of Java programming language is very closely aligned with C and
C++, which makes it easier to understand.
Java Syntax refers to a set of rules that defines how Java programs are written and interpreted
by the compiler. These rules ensure that your code is readable, logically correct, and error-free.
Now, let’s understand the Syntax and Structure of Java Programs with a basic “Hello World”
program.
Output
Hello World
Explanation: The above program shows the basic Java program that contains Class
declaration, Main Method, Statements, etc. Let’s try to understand them one by one.
Note: In the above code, although we did not explicitly import any package, the java.lang
package is automatically imported by default in every Java program. This package contains
essential classes like System, Math, and String, which is why we can use
System.out.println(“Hello World”); without any additional imports.
1. Class Declaration: Every Java program starts with a class declaration using the class
keyword. “A class is a blueprint of an object” and we can also define class as a logical
template that shares common properties and methods.
2. Object: The object is an instance of a class. It is an entity that has behavior and state.
a) Example: Dog, Cat, Monkey etc. are the object of the “Animal” class.
b) BehaviourJava: Running on the road.
3. Main Method: The public static void main(String args[]) method is the entry point where
the program starts execution.
4. Statements: Each line of code inside the method must end with a semicolon(;)
Steps to Compile and Run a Java Program in a Console
1. Run the javac command to compile the Java Program
javac Geeks.java
The Java compiler(javac) reads the source code(Geeks.java) and generates a bytecode
file(Geeks.class) in the same directory
2. Use the java command to execute the compiled bytecode
java Geeks
Java is one of the most popular and widely used programming languages and platforms. In this
article, we will learn how to write a simple Java Program. This Java Hello World article
will guide you through writing, compiling, and running your first Java program. Learning
Java helps to develop applications for web, mobile, and enterprise solutions.
In this article, we will learn:
How to create your first Java program
How to compile and run Java code
Understanding the Hello World program structure
Java programs can be written in a text editor (Notepad, VS Code) or an IDE (IntelliJ, Eclipse,
NetBeans).
To compile the program, we must run the Java compiler (javac), with the name of the source
file on the “command prompt” (Windows) or “Terminal” (Mac/Linux) as follows:
javac HelloWorld.java
Note: Before running the command, make sure you navigate to the directory where your .java
file is saved.
If everything is OK, the “javac” compiler creates a file called “HelloWorld.class” containing
the byte code of the program.
We need to use the Java Interpreter to run a program. Execute and compile Java program with
below command:
java HelloWorld
Output:
Hello, World
Note: 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++).
Implementation of Java Hello World
The below-given program is the most simple program of Java printing “Hello World” to the
screen. Let us try to understand every bit of code step by step.
// Simple Java program
// FileName: "HelloWorld.java"
class HelloWorld {
Output
Hello, World
This line uses the keyword class to declare that a new class is being defined.
class HelloWorld {
//
//Statements
}
2. HelloWorld
It is an identifier that is the name of the class. The entire class definition, including all of its
members, will be between the opening curly brace ” { ” and the closing curly brace ” } “.
3. main Method
In the Java programming language, every application must contain a main method. The main
function(method) is the entry point of your Java application, and it’s mandatory in a Java
program. whose signature in Java is:
public static void main(String[] args)
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”);
a) System: It is the predefined class which is present in the java.lang package which
provides the system resources for input and output.
b) out: It is a static field of type PrintStream in the System class used to represent the
standard output stream on the console.
c) . (dot): It is the member access operator also known as link operator used to access the
members of class or objects i.e fields and methods.
d) println(): It is the method of PrintStream class which is used to print the message on
the new line written inside as string”” (enclosed with double quotes).
Comments
They can either be multiline or single-line comments.
// Simple Java program
// FileNmae: “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:
a) 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.
b) 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.
c) Every Java program must have a class definition that matches the filename (class name
and file name should be same).
After successfully setting up the environment, we can open a terminal in both Windows/Unix
and go to the directory where the file – HelloWorld.java is present. Now, to compile the
HelloWorld program, execute the compiler – javac, to specify the name of the source file on
the command line, as shown:
javac HelloWorld.java
The compiler creates a HelloWorld.class (in the current working directory) that contains the
bytecode version of the program. Now, to execute our program, JVM (Java Virtual Machine)
needs to be called using Java, specifying the name of the class file on the command line, as
shown:
java HelloWorld
Output:
1. In Windows,
Java Identifiers
An identifier in Java is the name given to Variables, Classes, Methods, Packages, Interfaces,
etc. These are the unique names and every Java Variables must be identified with unique
names.
Example:
public class Test
{
public static void main(String[] args)
{
int a = 20;
}
}
MyVariable
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
geeks123
Any programming language reserves some words to represent functionalities defined by that
language. These words are called reserved words. They can be briefly categorized into two
parts: keywords(50) and literals(3). Keywords define functionalities and literals define value.
Identifiers are used by symbol tables in various analyzing phases(like lexical, syntax, and
semantic) of a compiler architecture.
Java Keywords
In Java, Keywords are the Reserved words in a programming language that are used for some
internal process or represent some predefined actions. These words are therefore not allowed
to use as variable names or objects.
Example :
// Java Program to demonstrate Keywords
class GFG
{
public static void main(String[] args)
{
// Using final and int keyword
final int x = 10;
Output
Succesful Demonstration of keywords
Java contains a list of keywords or reserved words which are also highlighted with different
colors be it an IDE or editor in order to segregate the differences between flexible words and
reserved words. They are listed below in the table with the primary action associated with them.
Keyword Usage
boolean A data type that can hold True and False values only
Example: Using the keywords as variables name. It will give an error as shown.
// Java Program to illustrate what if
// we use the keywords as the variable name
class GFG
{
public static void main(String[] args)
{
// Note "this" is a reserved
// word in java
String this = "Hello World!";
System.out.println(this);
}
}
Output:
./HelloWorld.java:6: error: not a statement
String this = "Hello World!"; System.out.println(this);
^
./HelloWorld.java:6: error: ';' expected
String this = "Hello World!"; System.out.println(this);
^
2 errors
Important Points:
The keywords const and goto are reserved, even though they are not currently in use.
Currently, they are no longer supported in Java.
true, false, and null look like keywords, but in actuality they are literals. However, they
still can’t be used as identifiers in a program.
Data types in Java are of different sizes and values that can be stored in the variable that is
made as per convenience and circumstances to cover up all test cases. Java has two categories
in which data types are segregated
1. Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double. The
Boolean with uppercase B is a wrapper class for the primitive data type boolean in Java.
2. Non-Primitive Data Type or Object Data type: such as String, Array, etc.
Example:
class GFG
{
public static void main (String[] args)
{
// declaring two int variables
int a = 10;
int b = 20;
System.out.println( a + b );
}
}
Output
30
Now, let us explore different types of primitive and non-primitive data types.
Example
Type Description Default Size Literals Range of values
8
true or false false true, false true, false
boolean bits
twos-
8
complement 0 (none) -128 to 127
bits
byte integer
twos-
16
complement 0 (none) -32,768 to 32,767
bits
short integer
twos- -2,147,483,648
32
complement 0 -2,-1,0,1,2 to
bits
int intger 2,147,483,647
twos- -
64 -2L,- 9,223,372,036,854,775,808
complement 0
bits 1L,0L,1L,2L to
long integer
9,223,372,036,854,775,807
The boolean data type represents a logical value that can be either true or false. Conceptually,
it represents a single bit of information, but the actual size used by the virtual machine is
implementation-dependent and typically at least one byte (eight bits) in practice. Values of the
boolean type are not implicitly or explicitly converted to any other type using casts. However,
programmers can write conversion code if needed.
Syntax:
boolean booleanVar;
The byte data type is an 8-bit signed two’s complement integer. The byte data type is useful
for saving memory in large arrays.
Syntax:
byte byteVar;
The short data type is a 16-bit signed two’s complement integer. Similar to byte, a short is used
when memory savings matter, especially in large arrays where space is constrained.
Syntax:
short shortVar;
Syntax:
int intVar;
Remember: In Java SE 8 and later, we can use the int data type to represent an unsigned 32-
bit integer, which has a value in the range [0, 2 32 -1]. Use the Integer class to use the int data
type as an unsigned integer.
The long data type is a 64-bit signed two’s complement integer. It is used when an int is not
large enough to hold a value, offering a much broader range.
Syntax:
long longVar;
Remember: In Java SE 8 and later, you can use the long data type to represent an unsigned
64-bit long, which has a minimum value of 0 and a maximum value of 2 64 -1. The Long class
also contains methods like comparing Unsigned, divide Unsigned, etc to support arithmetic
operations for unsigned long.
6. float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float (instead of
double) if you need to save memory in large arrays of floating-point numbers. The size of the
float data type is 4 bytes (32 bits).
Syntax:
float floatVar;
Size : 4 bytes (32 bits)
7. double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating-point. For decimal values,
this data type is generally the default choice. The size of the double data type is 8 bytes or 64
bits.
Syntax:
double doubleVar;
Note: Both float and double data types were designed especially for scientific calculations,
where approximation errors are acceptable. If accuracy is the most prior concern then, it is
recommended not to use these data types and use BigDecimal class instead.
It is recommended to go through rounding off errors in java.
The char data type is a single 16-bit Unicode character with the size of 2 bytes (16 bits).
Syntax:
char charVar;
Unlike languages such as C or C++ that use the ASCII character set, Java uses the Unicode
character set to support internationalization. Unicode requires more than 8 bits to represent a
wide range of characters from different languages, including Latin, Greek, Cyrillic, Chinese,
Arabic, and more. As a result, Java uses 2 bytes to store a char, ensuring it can represent
any Unicode character.
Example:
// Java Program to Demonstrate Char Primitive Data Type
class GFG
{
public static void main(String args[])
{
short s = 56;
Output
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121
The Non-Primitive (Reference) Data Types will contain a memory address of variable values
because the reference types won’t store the variable value directly in memory. They are strings,
objects, arrays, etc.
1. Strings
Strings are defined as an array of characters. The difference between a character array and a
string in Java is, that the string is designed to hold a sequence of characters in a single variable
whereas, a character array is a collection of separate char-type entities. Unlike C/C++, Java
strings are not terminated with a null character.
Example:
2. Class
A Class is a user-defined blueprint or prototype from which objects are created. It represents
the set of properties or methods that are common to all objects of one type. In general, class
declarations can include these components, in order:
1. Modifiers : A class can be public or has default access. Refer to access specifiers for
classes or interfaces in Java
2. Class name: The name should begin with an initial letter (capitalized by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
5. Body: The class body is surrounded by braces, { }.
3. Object
4. Interface
Like a class, an interface can have methods and variables, but the methods declared in an
interface are by default abstract (only method signature, no body).
a) Interfaces specify what a class must do and not how. It is the blueprint of the class.
b) 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.
c) If a class implements an interface and does not provide method bodies for all functions
specified in the interface, then the class must be declared abstract.
d) A Java library example is Comparator Interface . If a class implements this interface,
then it can be used to sort a collection.
5. Array
An Array is a group of like-typed variables that are referred to by a common name. Arrays in
Java work differently than they do in C/C++. The following are some important points about
Java arrays.
a) Strong Typing: Java enforces strict type checking at compile-time, reducing runtime
errors.
b) Memory Efficiency: Choosing the right data type based on the range and precision
needed helps in efficient memory management.
c) Immutability of Strings: Strings in Java cannot be changed once created, ensuring
safety in multithreaded environments.
d) Array Length: The length of arrays in Java is fixed once declared, and it can be
accessed using the length attribute
Understanding Java’s data types is fundamental to efficient programming. Each data type has
specific use cases and constraints, making it essential to choose the right type for the task at
hand. This ensures optimal memory usage and program performance while leveraging Java’s
strong typing system to catch errors early in the development process.
Primitive data types are the types in java that can store a single value and do not provide any
special capability.
Java Variables
Variables are the containers for storing the data values or you can also call it a memory location
name for the data. Every variable has a:
Data Type – The kind of data that it can hold. For example, int, string, float, char, etc.
Variable Name – To identify the variable uniquely within the scope.
Value – The data assigned to the variable.
There are three types of variables in Java – Local, Instance, and Static.
Example:
From the image, it can be easily perceived that while declaring a variable, we need to take care
of two things that are:
1. datatype: In Java, a data type define the type of data that a variable can hold.
2. data_name: Name was given to the variable.
In this way, a name can only be given to a memory location. It can be assigned values in two
ways:
Variable Initialization
Assigning value by taking input
Example:
// Declaring float variable
float simpleInterest;
Now let us discuss different types of variables which are listed as follows:
1. Local Variables
2. Instance Variables
3. Static Variables
Let us discuss the traits of every type of variable listed here in detail.
1. Local Variables
a) The Local variable is created at the time of declaration and destroyed after exiting from
the block or when the call returns from the function.
b) The scope of these variables exists only within the block in which the variables are
declared, i.e., we can access these variables only within that block.
c) Initialization of the local variable is mandatory before using it in the defined scope.
Example 1:
// Java Program to show the use of local variables
import java.io.*;
class GFG {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;
Output
Local Variable: 10
Example 2:
// Java Program to show the use of
// Local Variables
import java.io.*;
public class GFG {
public static void main(String[] args)
{
// x is a local variable
int x = 10;
if (x > 5) {
// result is a
// local variable
String result = "x is greater than 5";
System.out.println(result);
}
Output
x = 10
message = Hello, world!
x is greater than 5
Iteration 0
Iteration 1
Iteration 2
2. Instance Variables
Instance variables are non-static variables and are declared in a class outside of any method,
constructor, or block.
a) 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.
b) Unlike local variables, we may use access specifiers for instance variables. If we do not
specify any access specifier, then the default access specifier will be used.
c) Initialization of an instance variable is not mandatory. Its default value is dependent on
the data type of variable. For String it is null, for float it is 0.0f, for int it is 0, for
Wrapper classes like Integer it is null, etc.
d) Scope of instance variables are throughout the class except the static contexts.
e) Instance variables can be accessed only by creating objects.
f) We initialize instance variables using constructors while creating an object. We can
also use instance blocks to initialize the instance variables.
Example:
// Java Program to show the use of
// Instance Variables
import java.io.*;
class GFG {
// 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);
System.out.println("Default value for int is "+ name.i);
Output
Geek name is: Shubham Jain
Default value for int is 0
Default value for Integer is null
3. Static Variables
a) These variables are declared similarly to instance variables. The difference is that static
variables are declared using the static keyword within a class outside of any method,
constructor, or block.
b) Unlike instance variables, we can only have one copy of a static variable per class,
irrespective of how many objects we create.
c) Static variables are created at the start of program execution and destroyed
automatically when execution ends.
d) Initialization of a static variable is not mandatory. Its default value is dependent on the
data type of variable. For String it is null, for float it is 0.0f, for int it is 0, for Wrapper
classes like Integer it is null, etc.
e) If we access a static variable like an instance variable (through an object), the compiler
will show a warning message, which won’t halt the program. The compiler will replace
the object name with the class name automatically.
f) If we access a static variable without the class name, the compiler will automatically
append the class name. But for accessing the static variable of a different class, we must
mention the class name as 2 different classes might have a static variable with the same
name.
g) Static variables cannot be declared locally inside an instance method.
h) Static blocks can be used to initialize static variables.
Example:
// Java Program to show the use of
// Static variables
import java.io.*;
class GFG {
// Declared static variable
public static String geek = "Shubham Jain";
// static int c = 0;
// above line, when uncommented,
// will throw an error as static variables cannot be
// declared locally.
}
}
Output
Geek Name is : Shubham Jain
Now let us discuss the differences between the Instance variables and the Static variables:
a) Each object will have its own copy of an instance variable, whereas we can only have
one copy of a static variable per class, irrespective of how many objects we create.
Thus, static variables are good for memory management.
b) Changes made in an instance variable using one object will not be reflected in other
objects as each object has its own copy of the instance variable. In the case of a static
variable, changes will be reflected in other objects as static variables are common to all
objects of a class.
c) We can access instance variables through object references, and static variables can be
accessed directly using the class name.
d) Instance variables are created when an object is created with the use of the keyword
‘new’ and destroyed when the object is destroyed. Static variables are created when the
program starts and destroyed when the program stops.
Syntax: Static and instance variables
class GFG
{
// Static variable
static int a;
// Instance variable
int b;
}
Java Variables
data_type variable_name;
Example:
These variables must be declared inside class (outside any function). They can be directly
accessed anywhere in class.
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.
private No No No
Static Variable is a type of class variable shared across instances. Static Variables are the
variables which once declared can be used anywhere even outside the class without initializing
the class. Unlike Local variables it scope is not limited to the class or the block.
Example:
// Using Static variables
import java.io.*;
class Test{
// static variable in Test class
static int var = 10;
}
class Geeks
{
public static void main (String[] args) {
// accessing the static variable
System.out.println("Static Variable : "+Test.var);
}
}
Output
Static Variable : 10
Variables declared inside a method have method level scope and can’t be accessed outside the
method.
Here’s another example of method scope, except this time the variable got passed in as a
parameter to the method:
class Test {
private int x;
The above code uses this keyword to differentiate between the local and class variables.
// Instance Variable
private int y = 33;
// Main Method
public static void main(String args[]) {
Geeks t = new Geeks();
t.testFunc(5);
}
}
Output
Geeks.x: 22
t.x: 22
t.y: 33
y: 44
A variable declared inside pair of brackets “{” and “}” in a method has scope within the
brackets only.
Example:
// Using Block Scope
public class Test
{
public static void main(String args[])
{
// Block Level Scope
{
// The variable x has scope within
// brackets
int x = 10;
System.out.println(x);
}
// System.out.println(x);
}
}
Output:
10
Let’s look at tricky example of loop scope. Predict the output of following program. You may
be surprised if you are regular C/C++ programmer.
Programs:
Case 1Case 2
class Test
{
public static void main(String args[])
{
// local variable declared
int a = 5;
/*
Output:
/*
Output:
11: error: cannot find symbol
System.out.println(x);
*/
/ Correcting the error
class Test
{
public static void main(String args[])
{
int x;
for (x = 0; x < 4; x++) {
System.out.print(x + " ");
}
System.out.println(x);
}
}
Output:
01234
The Java Class Library is a set of predefined classes, interfaces, and methods that come with
Java to help developers perform common tasks. These libraries are bundled within the Java
API (Application Programming Interface) and are part of the Java Standard Edition (Java
SE).
Java provides a large number of classes grouped into different packages. The core Java
libraries are primarily found in the java.lang, java.util, java.io, java.nio, java.net, and java.sql
packages.
This package is automatically imported in every Java program and provides fundamental
classes.
Example:
This package provides collections, date/time utilities, random number generation, and other
utility functions.
The java.io package provides classes for file handling and input/output streams.
Example:
Introduced in Java NIO (New I/O), this package provides faster and more flexible
input/output operations.
Example:
E. java.net (Networking)
Java supports networking operations like socket programming and HTTP requests.
Example:
Example:
4. Summary
1. Introduction
Java is a strongly typed language, meaning every variable must have a defined data type.
Understanding data types, variables, and arrays is crucial for writing efficient and error-free
Java programs.
2. Data Types in Java
Primitive data types store simple values and are not objects. Java has 8 primitive types:
Example:
int a = 10;
double b = 20.5;
boolean flag = true;
Reference types store the memory address of an object instead of actual values.
Example:
3. Variables in Java
A. Declaring Variables
dataType variableName = value;
Example:
B. Types of Variables
Example:
class Employee {
String name; // Instance variable
static String company = "TechCorp"; // Static variable
void display() {
int age = 30; // Local variable
System.out.println(name + " works at " + company);
}
}
Example:
Example:
double pi = 3.14159;
int x = (int) pi; // Explicit casting
System.out.println(x); // Output: 3
5. Constants in Java
Example:
6. Arrays in Java
Example:
Example:
D. Multi-Dimensional Arrays
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(matrix[1][2]); // Output: 6
7. Summary
Concept Description
Primitive Data Types Basic types like int, double, char, etc.
Reference Types Objects, Arrays, and Strings.
Variables Named memory locations (Local, Instance, Static).
Type Conversion Widening (Automatic) and Narrowing (Explicit).
Constants Declared with final, cannot be changed.
Arrays Stores multiple values of the same type.