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

Java

Object-oriented programming (OOP) is fundamental to Java, organizing programs around data (objects) and their interactions rather than just code. Key OOP concepts include abstraction, encapsulation, inheritance, and polymorphism, which enhance code reusability, organization, and maintainability. Java's features, such as platform independence and security, further support its use in developing robust applications.

Uploaded by

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

Java

Object-oriented programming (OOP) is fundamental to Java, organizing programs around data (objects) and their interactions rather than just code. Key OOP concepts include abstraction, encapsulation, inheritance, and polymorphism, which enhance code reusability, organization, and maintainability. Java's features, such as platform independence and security, further support its use in developing robust applications.

Uploaded by

amit.ray455
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Object-Oriented Programming

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

Object-Oriented Programming or Java OOPs concept refers to programming languages that


use objects in programming. They use objects as a primary source to implement what is to
happen in the code. Objects are seen by the viewer or user, performing tasks you assign.

Object-oriented programming aims to implement real-world entities


like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOPs is to
bind together the data and the functions that operate on them so that no other part of the code
can access this data except that function.

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); }

public void sub() { System.out.println(a - b); }

public static void main(String[] args)


{
// Creating Instance of Class
// Object
Numbers obj = new Numbers();

// Assigning Values to the Properties


obj.a = 1;
obj.b = 2;

// Using the Methods


obj.sum();
obj.sub();
}
}

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

An Object is a basic unit of Object-Oriented Programming that represents real-life entities. A


typical Java program creates many objects, which as you know, interact by invoking methods.
The objects are what perform your code, they are the part of your code visible to the
viewer/user. An object mainly consists of:

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


object.
2. Behavior: It is represented by the methods of an object. It also reflects the response of an
object to other objects.
3. Identity: It is a unique name given to an object that enables it to interact with other objects.
4. Method: A method is a collection of statements that perform some specific task and return
the result to the caller. A method can perform some specific task without returning
anything. Methods allow us to reuse the code without retyping it, which is why they are
considered time savers. In Java, every method must be part of some class, which is
different from languages like C, C++, and Python.

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;
}

static void get() {


System.out.println("Employee name is: " +Employee_name );
System.out.println("Employee CTC is: " + Employee_salary);
}

// 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

4 Pillars of Java OOPs Concepts

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.

Ex: A car is viewed as a car rather than its individual components.


Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object, ignoring the irrelevant details. The properties and behaviors of an
object differentiate it from other objects of similar type and also help in classifying/grouping
the object.

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

// Employee class contains private data


// called employee id and employee name
class Employee {

private int empid;


private String ename;

// Setter methods
public void set_id(int empid) {
this.empid = empid;
}

public void set_name(String ename)


{
this.ename = ename;
}

// Getter methods
public int get_id() {
return empid;
}

public String get_name() {


return ename;
}
}

public class Geeks {

public static void main(String args[])


{
Employee e = new Employee();
e.set_id(78);
e.set_name("John");

System.out.println("Employee id: " + e.get_id());


System.out.println("Employee Name: "
+ e.get_name());
}
}
Output
Employee id: 78
Employee Name: John

3. Inheritance

Inheritance is an important pillar of OOP (Object Oriented Programming). It is the mechanism


in Java by which one class is allowed to inherit the features (fields and methods) of another
class. We are achieving inheritance by using extends keyword. Inheritance is also known as
“is-a” relationship.

Let us discuss some frequently used important terminologies:

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(){}
}

// derived class or child class or base class


class B extends A{ // Inherits parent class methods
// child class methods
void method3(){}
void method4(){}
}

4. Polymorphism

It refers to the ability of object-oriented programming languages to differentiate between


entities with the same name efficiently. This is done by Java with the help of the signature and
declaration of these entities. The ability to appear in many forms is called polymorphism.
Example:
sleep(1000) //millis
sleep(1000,2000) //millis,nanos
Types of Polymorphism
Polymorphism in Java is mainly of 2 types as mentioned below:
1. Method Overloading
2. Method Overriding

Method Overloading and Method Overriding

1. Method Overloading: Also, known as compile-time polymorphism, is the concept of


Polymorphism where more than one method share the same name with different
signature(Parameters) in a class. The return type of these methods can or cannot be same.

2. Method Overriding: Also, known as run-time polymorphism, is the concept of


Polymorphism where method in the child class has the same name, return-type and parameters
as in parent class. The child class provides the implementation in the method already written.

Below is the implementation of both the concepts:


// Java Program to Demonstrate
// Method Overloading and Overriding

// 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

Advantage of OOPs over Procedure-Oriented Programming Language

Object-oriented programming (OOP) offers several key advantages over procedural


programming:

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

Key Features of Java


1. Platform Independent

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

2. Object-Oriented Programming
Java is an object-oriented language, promoting the use of objects and classes. Organizing
the program in the terms of a collection of objects is a way of object-oriented programming,
each of which represents an instance of the class.
The four main concepts of Object-Oriented programming are:
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

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


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

6. Distributed

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

7. Multithreading

Java supports multithreading, enabling the concurrent execution of multiple parts of a


program. This feature is particularly useful for applications that require high performance,
such as games and real-time simulations.

8. Portability

As we know, java code written on one machine can be run on another machine. The platform-
independent feature of java in which its platform-independent bytecode can be taken to any
platform for execution makes java portable. WORA(Write Once Run Anywhere) makes
java application to generates a ‘.class’ file that corresponds to our applications(program) but
contains code in binary format. It provides 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?

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

How Java Code Executes

1. Creating the Program


Java programs are written using a text editor or an Integrated Development Environment
(IDE) like IntelliJ IDEA, Eclipse, or NetBeans. The source code is saved with
a .java extension.
2. Compiling the Program
The Java compiler (javac) converts the source code into bytecode, which is stored in
a .class file. This bytecode is platform-independent and can be executed on any machine with
a JVM.
3. Running the Program
The JVM executes the compiled bytecode, translating it into machine code specific to the
operating system and hardware.
Example Program:
public class HelloWorld {
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
}

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.

1. Java Virtual Machine(JVM)

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

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

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

3. Java Development Kit(JDK)

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

4. Java Runtime Environment (JRE)

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

5. Garbage Collector

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

6. ClassPath

The Classpath is the file path where the java runtime and Java compiler look for .class files
to load. By default, JDK provides many libraries. If you want to include external libraries,
they should be added to the classpath.
Basically everything in java is represented in Class as an object including the main function.

Advantages of Java

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

1. Performance: Java can be slower compared to other programming languages, such as


C++, due to its use of a virtual machine and automatic memory management.
2. Memory management: Java’s automatic memory management can lead to slower
performance and increased memory usage, which can be a drawback for some
applications.

How JVM Works – JVM Architecture


JVM(Java Virtual Machine) runs Java applications as a run-time engine. JVM is the one that
calls the main method present in a Java code. JVM is a part of JRE(Java Runtime
Environment).
Java applications are called WORA (Write Once Run Anywhere). This means a programmer
can develop Java code on one system and 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 describe the whole JVM.

1. Class Loader Subsystem

It is mainly responsible for three activities.


 Loading
 Linking
 Initialization

Loading:

The Class loader reads the “.class” file, generate the corresponding binary data and save it in
the method area. For each “.class” file, JVM stores the following information in the method
area.

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

After loading the “.class” file, JVM creates 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;

// Java code to demonstrate use


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

// Getting hold of Class


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

// Printing type of object using c1.


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

// getting all methods in an array


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

// getting all fields in an array


Field f[] = c1.getDeclaredFields();
for (Field field : f)
System.out.println(field.getName());
}
}

// A sample class whose information


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

public String getName() { return name; }


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

Output
Student
getName
setName
getRoll_no
setRoll_no
name
roll_No
Note: For every loaded “.class” file, only one object of the class is created.
Student s2 = new Student();
// c2 will point to same object where
// c1 is pointing
Class c2 = s2.getClass();
System.out.println(c1==c2); // true

Linking

Performs verification, preparation, and (optionally) resolution.

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());

// Test class is loaded by Application loader


System.out.println(Test.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

There are three primary types of class loaders:

a) Bootstrap Class Loader: Loads core Java API classes from


the JAVA_HOME/lib directory. It is implemented in native code and is not a Java
object.
b) Extension Class Loader: Loads classes from the JAVA_HOME/jre/lib/ext directory
or any directory specified by the java.ext.dirs system property. It is implemented in
Java.
c) System/Application Class Loader: Loads classes from the application classpath,
which is specified by the java.class.path environment variable. It is also implemented
in Java.

Example:
public class Test {
public static void main(String[] args) {
System.out.println(String.class.getClassLoader());
System.out.println(Test.class.getClassLoader());
}
}

3. JVM Memory Areas

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.

5. Java Native Interface (JNI)

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

6. Native Method Libraries

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.

Structure of Java Program


A basic Java program consists of several components that create a functional application. We
can learn about basic Java Syntax using the following program:
// FileName : "Geeks.java".

public class Geeks {


// Program begins with a call to main() method
// main method is the entry point of a Java Program
public static void main(String args[])
{

// Prints "Hello World" to the console


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

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.

Terminologies of a Basic Java Program

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 Hello World Program


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

Steps to Implement Java Program


The implementation of a Java program involves the following steps. They include:

1. Creating the program


2. Compiling the program
3. Running the program

1. Create a Java Program

Java programs can be written in a text editor (Notepad, VS Code) or an IDE (IntelliJ, Eclipse,
NetBeans).

// Simple Java Hello World Program


class HelloWorld
{
public static void main(String[] args)
{
System.out.println(“Hello, World”);
}
}
Save the file as HelloWorld.java

2. Compile the Java Program

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.

3. Run the Java 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 {

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


// Prints "Hello, World" to the terminal window.
public static void main(String[] args)
{
System.out.println("Hello, World");
}
}

Output
Hello, World

Understanding the Java Hello World Code


1. Class Definition

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

class HelloWorld {
//
//Statements
}
2. HelloWorld

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

3. main Method

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

Explanation of the above syntax:

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


b) static: The main method is to be called without an object. The modifiers are public and
static can be written in either order.
c) void: The main method doesn’t return anything.
d) main(): Name configured in the JVM. The main method must be inside the class
definition. The compiler executes the codes starting always from the main function.
e) 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”);

Explanation of the above syntax:


This line is used to print the Hello, World on the console Here is the brief description of the
above code:

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

Compiling the Program

After successfully setting up the environment, we can open a terminal in both Windows/Unix
and go to the directory where the file – HelloWorld.java is present. Now, to compile the
HelloWorld program, execute the compiler – javac, to specify the name of the source file on
the command line, as shown:

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

java HelloWorld

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

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;
}
}

In the above Java code, we have 5 identifiers as follows:

a) Test: Class Name


b) main: Method Name
c) String: Predefined Class Name
d) args: Variable Name
e) a: Variable Name

Rules For Naming Java Identifiers


There are certain rules for defining a valid Java identifier. These rules must be followed,
otherwise, we get a compile-time error. These rules are also valid for other languages like C,
and C++.
a) The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-
z],[0-9]), ‘$‘(dollar sign) and ‘_‘ (underscore). For example “geek@” is not a valid Java
identifier as it contains a ‘@’ a special character.
b) Identifiers should not start with digits([0-9]). For example “123geeks” is not a valid
Java identifier.
c) Java identifiers are case-sensitive.
d) There is no limit on the length of the identifier but it is advisable to use an optimum
length of 4 – 15 letters only.
e) Reserved Words can’t be used as an identifier. For example “int while = 20;” is an
invalid statement as a while is a reserved word. There are 53 reserved words in Java.

Examples of Valid Identifiers:

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

Examples of Invalid Identifiers:

My Variable // contains a space


123geeks // Begins with a digit
a+c // plus sign is not an alphanumeric character
variable-2 // hyphen is not an alphanumeric character
sum_&_difference // ampersand is not an alphanumeric character

Reserved Words in Java

Any programming language reserves some words to represent functionalities defined by that
language. These words are called reserved words. They can be briefly categorized into two
parts: keywords(50) and literals(3). Keywords define functionalities and literals define value.
Identifiers are used by symbol tables in various analyzing phases(like lexical, syntax, and
semantic) of a compiler architecture.

abstract continue for protected transient

Assert Default Goto public Try


abstract continue for protected transient

Boolean Do If Static throws

break double implements strictfp Package

byte else import super Private

case enum Interface Short switch

Catch Extends instanceof return void

Char Final Int synchronized volatile

class finally long throw Date

const float Native This while

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;

// Using if and else keywords


if(x>10){
System.out.println("Failed");
}
else{
System.out.println("Succesful Demonstration"
+" of keywords");
}
}
}

Output
Succesful Demonstration of keywords

Java Keywords List

Java contains a list of keywords or reserved words which are also highlighted with different
colors be it an IDE or editor in order to segregate the differences between flexible words and
reserved words. They are listed below in the table with the primary action associated with them.

Keyword Usage

Specifies that a class or method will be implemented


abstract
later, in a subclass

Assert describes a predicate placed in a Java program


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

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

break A control statement for breaking out of loops.

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

case Used in switch statements to mark blocks of text

catch Catches exceptions generated by try statements

A data type that can hold unsigned 16-bit Unicode


char
characters
Keyword Usage

class Declares a new class

continue Sends control back outside a loop

Specifies the default block of code in a switch


default
statement

do Starts a do-while loop

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


double
numbers

else Indicates alternative branches in an if statement

A Java keyword is used to declare an enumerated


enum
type. Enumerations extend the base class.

Indicates that a class is derived from another class or


extends
interface

Indicates that a variable holds a constant value or


final
that a method will not be overridden

Indicates a block of code in a try-catch structure that


finally
will always be executed

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


float
number

for Used to start a for loop


Keyword Usage

Tests a true/false expression and branches


if
accordingly

implements Specifies that a class implements an interface

import References other classes

Indicates whether an object is an instance of a


instanceof
specific class or implements an interface

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

interface Declares an interface

long A data type that holds a 64-bit integer

Specifies that a method is implemented with native


native
(platform-specific) code

new Creates new objects

This indicates that a reference does not refer to


null
anything

package Declares a Java package

An access specifier indicating that a method or


private variable may be accessed only in the class it’s
declared in
Keyword Usage

An access specifier indicating that a method or


variable may only be accessed in the class it’s
protected
declared in (or a subclass of the class it’s declared in
or other classes in the same package)

An access specifier used for classes, interfaces,


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

Sends control and possibly a return value back from


return
a called method

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

Indicates that a variable or method is a class method


static
(rather than being limited to one particular object)

A Java keyword is used to restrict the precision and


strictfp rounding of floating-point calculations to ensure
portability.

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


super
class constructor)

switch A statement that executes code based on a test value

Specifies critical sections or methods in


synchronized
multithreaded code

Refers to the current object in a method or


this
constructor
Keyword Usage

throw Creates an exception

Indicates what exceptions may be thrown by a


throws
method

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


transient
persistent state

Starts a block of code that will be tested for


try
exceptions

void Specifies that a method does not have a return value

This indicates that a variable may change


volatile
asynchronously

while Starts a while loop

The sealed keyword is used to declare a class as


sealed “sealed,” meaning it restricts which classes can
extend it.

The permits keyword is used within a sealed class


permits declaration to specify the subclasses that are
permitted to extend it.

Example: Using the keywords as variables name. It will give an error as shown.
// Java Program to illustrate what if
// we use the keywords as the variable name

class GFG
{
public static void main(String[] args)
{
// Note "this" is a reserved
// 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.

Java Data Types


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

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

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

Example:

// Java Program to demonstrate int data-type


import java.io.*;

class GFG
{
public static void main (String[] args)
{
// declaring two int variables
int a = 10;
int b = 20;

System.out.println( a + b );
}
}
Output
30

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

Data Types in JAVA

Primitive Data Types in Java


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

Example
Type Description Default Size Literals Range of values

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

twos-
8
complement 0 (none) -128 to 127
bits
byte integer

‘a’, ‘\u0041’, characters representation of


Unicode 16
\u0000 ‘\101’, ‘\\’, ASCII values
character bits
char ‘\’, ‘\n’, ‘β’ 0 to 255
Example
Type Description Default Size Literals Range of values

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

IEEE 754 1.23e100f , -


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

IEEE 754 1.23456e300d


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

Primitive Data Types

1. boolean Data Type

The boolean data type represents a logical value that can be either true or false. Conceptually,
it represents a single bit of information, but the actual size used by the virtual machine is
implementation-dependent and typically at least one byte (eight bits) in practice. Values of the
boolean type are not implicitly or explicitly converted to any other type using casts. However,
programmers can write conversion code if needed.

Syntax:

boolean booleanVar;

Size: Virtual machine dependent (typically 1 byte, 8 bits)


2. byte Data Type

The byte data type is an 8-bit signed two’s complement integer. The byte data type is useful
for saving memory in large arrays.

Syntax:

byte byteVar;

Size: 1 byte (8 bits)

3. short Data Type

The short data type is a 16-bit signed two’s complement integer. Similar to byte, a short is used
when memory savings matter, especially in large arrays where space is constrained.

Syntax:

short shortVar;

Size: 2 bytes (16 bits)

4. int Data Type

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

Syntax:

int intVar;

Size: 4 bytes ( 32 bits )

Remember: In Java SE 8 and later, we can use the int data type to represent an unsigned 32-
bit integer, which has a value in the range [0, 2 32 -1]. Use the Integer class to use the int data
type as an unsigned integer.

5. long Data Type

The long data type is a 64-bit signed two’s complement integer. It is used when an int is not
large enough to hold a value, offering a much broader range.

Syntax:

long longVar;

Size: 8 bytes (64 bits)

Remember: In Java SE 8 and later, you can use the long data type to represent an unsigned
64-bit long, which has a minimum value of 0 and a maximum value of 2 64 -1. The Long class
also contains methods like comparing Unsigned, divide Unsigned, etc to support arithmetic
operations for unsigned long.
6. float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float (instead of
double) if you need to save memory in large arrays of floating-point numbers. The size of the
float data type is 4 bytes (32 bits).
Syntax:
float floatVar;
Size : 4 bytes (32 bits)
7. double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating-point. For decimal values,
this data type is generally the default choice. The size of the double data type is 8 bytes or 64
bits.

Syntax:

double doubleVar;

Size: 8 bytes (64 bits)

Note: Both float and double data types were designed especially for scientific calculations,
where approximation errors are acceptable. If accuracy is the most prior concern then, it is
recommended not to use these data types and use BigDecimal class instead.
It is recommended to go through rounding off errors in java.

8. char Data Type

The char data type is a single 16-bit Unicode character with the size of 2 bytes (16 bits).

Syntax:

char charVar;

Size: 2 bytes (16 bits)

Why is the Size of char 2 bytes in Java?

Unlike languages such as C or C++ that use the ASCII character set, Java uses the Unicode
character set to support internationalization. Unicode requires more than 8 bits to represent a
wide range of characters from different languages, including Latin, Greek, Cyrillic, Chinese,
Arabic, and more. As a result, Java uses 2 bytes to store a char, ensuring it can represent
any Unicode character.

Example:
// Java Program to Demonstrate Char Primitive Data Type

class GFG
{
public static void main(String args[])
{

// Creating and initializing custom character


char a = 'G';

// Integer data type is generally


// used for numeric values
int i = 89;

// use byte and short


// if memory is a constraint
byte b = 4;

// this will give error as number is


// larger than byte range
// byte b1 = 7888888955;

short s = 56;

// this will give error as number is


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

// by default fraction value


// is double in java
double d = 4.355453532;

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


float f = 4.7333434f;

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


// this data type
long l = 12121;

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


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

Output
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121

Non-Primitive (Reference) Data Types

The Non-Primitive (Reference) Data Types will contain a memory address of variable values
because the reference types won’t store the variable value directly in memory. They are strings,
objects, arrays, etc.

1. Strings

Strings are defined as an array of characters. The difference between a character array and a
string in Java is, that the string is designed to hold a sequence of characters in a single variable
whereas, a character array is a collection of separate char-type entities. Unlike C/C++, Java
strings are not terminated with a null character.

Syntax: Declaring a string

<String_Type> <string_variable> = “<sequence_of_string>”;

Example:

// Declare String without using new operator


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

2. Class

A Class is a user-defined blueprint or prototype from which objects are created. It represents
the set of properties or methods that are common to all objects of one type. In general, class
declarations can include these components, in order:

1. Modifiers : A class can be public or has default access. Refer to access specifiers for
classes or interfaces in Java
2. Class name: The name should begin with an initial letter (capitalized by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
5. Body: The class body is surrounded by braces, { }.
3. Object

An Object is a basic unit of Object-Oriented Programming and represents real-life entities. A


typical Java program creates many objects, which as you know, interact by invoking methods.
An object consists of:

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


object.
2. Behavior : It is represented by the methods of an object. It also reflects the response of an
object to other objects.
3. Identity : It gives a unique name to an object and enables one object to interact with other
objects.

4. Interface

Like a class, an interface can have methods and variables, but the methods declared in an
interface are by default abstract (only method signature, no body).

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) In Java, all arrays are dynamically allocated. (discussed below)


b) 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.
c) A Java array variable can also be declared like other variables with [] after the data
type.
d) The variables in the array are ordered and each has an index beginning with 0.
e) Java array can also be used as a static field, a local variable, or a method parameter.
f) The size of an array must be specified by an int value and not long or short.
g) The direct superclass of an array type is Object.
h) Every array type implements the interfaces Cloneable and java.io.Serializable.

Key Points to Remember

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.

Check Out: Quiz on Data Type in Java

Java Data Types


What are Data Types in Java?
Data types 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.
What are the 8 Data Types that use in Java?
There are 8 main primitive data types in java as mentioned below:
 boolean
 byte
 char
 short
 int
 long
 float
 double

Which is a Primitive Type in Java?

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:

int age = 27; // integer variable having value 27

String name = "gfg" // string variable


How to Declare Java Variables?

We can declare variables in Java as pictorially depicted below:

From the image, it can be easily perceived that while declaring a variable, we need to take care
of two things that are:

1. datatype: In Java, a data type define the type of data that a variable can hold.
2. data_name: Name was given to the variable.
In this way, a name can only be given to a memory location. It can be assigned values in two
ways:

 Variable Initialization
 Assigning value by taking input

How to Initialize Java Variables?

It can be perceived with the help of 3 components explained above:

Example:
// Declaring float variable
float simpleInterest;

// Declaring and initializing integer variable


int time = 10, speed = 20;

// Declaring and initializing character variable


char var = 'h';

Types of Java Variables

Now let us discuss different types of variables which are listed as follows:

1. Local Variables
2. Instance Variables
3. Static Variables

Let us discuss the traits of every type of variable listed here in detail.

1. Local Variables

A variable defined within a block or method or constructor is called a local variable.

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;

// This variable is local to this main method only


System.out.println("Local Variable: " + var);
}
}

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;

// message is also a local


// variable
String message = "Hello, world!";

System.out.println("x = " + x);


System.out.println("message = " + message);

if (x > 5) {
// result is a
// local variable
String result = "x is greater than 5";
System.out.println(result);
}

// Uncommenting the line below will result in a


// compile-time error System.out.println(result);

for (int i = 0; i < 3; i++) {


String loopMessage
= "Iteration "
+ i; // loopMessage is a local variable
System.out.println(loopMessage);
}

// Uncommenting the line below will result in a


// compile-time error
// System.out.println(loopMessage);
}
}

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 {

// Declared Instance Variable


public String geek;
public int i;
public Integer I;
public GFG()
{
// Default Constructor
// initializing Instance Variable
this.geek = "Shubham Jain";
}

// 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);

// toString() called internally


System.out.println("Default value for Integer is "+ name.I);
}
}

Output
Geek name is: Shubham Jain
Default value for int is 0
Default value for Integer is null

3. Static Variables

Static variables are also known as class variables.

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";

public static void main(String[] args)


{

// geek variable can be accessed without object


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

// 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

Instance Variables vs Static Variables

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

What are variables in Java?


Variables are the containers in Java that can store data values inside them.

What are the 3 types of variables in Java?

There are three types of variables in Java are mentioned below:


1. Local Variables
2. Static Variables
3. Instance Variables

How to declare variables in Java examples?

We can declare variables in java with syntax as mentioned below:

data_type variable_name;

Example:

// Integer datatype with var1 name


int var1;

Scope of Variables in Java


The scope of variables is the part of the program where the variable is accessible. Like C/C++,
in Java, all identifiers are lexically (or statically) scoped, i.e. scope of a variable can be
determined at compile time and independent of the function call stack. In this article, we will
learn about Java Scope Variables.

Java Scope of Variables

Java Scope Rules can be covered under the following categories.


1. Instance Variables
2. Static Variables
3. Local Variables
4. Parameter Scope
5. Block Scope
Now we will discuss all these Scopes and variables according to them.
1. Instance Variables – Class Level Scope

These variables must be declared inside class (outside any function). They can be directly
accessed anywhere in class.

Let’s take a look at an example:

public class Test {


// All variables defined directly inside a class
// are member variables
int a;
private String b;

void method1() {….}


int method2() {….}

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

Access Modifiers and Member Variable Scope

Modifier Package Subclass World

public Yes Yes Yes

protected Yes Yes No

Default (no modifier) Yes No No

private No No No

2. Static Variables – Class Level Scope

Static Variable is a type of class variable shared across instances. Static Variables are the
variables which once declared can be used anywhere even outside the class without initializing
the class. Unlike Local variables it scope is not limited to the class or the block.

Example:
// 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

3. Method Level Scope – Local Variable

Variables declared inside a method have method level scope and can’t be accessed outside the
method.

public class Test {


void method1()
{
// Local variable (Method level scope)
int x;
}
}

Note: Local variables don’t exist after method’s execution is over.

4. Parameter Scope – Local Variable

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

class Test {
private int x;

public void setX(int x) {


this.x = x;
}
}

The above code uses this keyword to differentiate between the local and class variables.

Example of Method and Parameter Scope:

// Using Method Scope and Parameter Scope


public class Geeks
{
// Class Scope variable
static int x = 11;

// Instance Variable
private int y = 33;

// Parameter Scope (x)


public void testFunc(int x) {
// Method Scope (t)
Geeks t = new Geeks();
this.x = 22;
y = 44;

// Printing variables with different scopes


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

// 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

5. Block Level Scope

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);
}

// Uncommenting below line would produce


// error since variable x is out of scope.

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

10

Incorrect Usage of Local Variables

1. For Block Level Cases which are wrong

Let’s look at tricky example of loop scope. Predict the output of following program. You may
be surprised if you are regular C/C++ programmer.

Programs:
Case 1Case 2
class Test
{
public static void main(String args[])
{
// local variable declared
int a = 5;

// for loop variable declared


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++, Program 1 will run. But in Java it is an error because in Java, the name of the
variable of inner and outer loop must be different. A similar program in C++ works.
2. Incorrect Way to use Local Variable – Block Scope
IncorrectCorrect
class Test
{
public static void main(String args[])
{
for (int x = 0; x < 4; x++)
{
System.out.println(x);
}

// Will produce error


System.out.println(x);
}
}

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

*/
/ 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

Important Points about Variable Scope in Java

a) In general, a set of curly brackets { } defines a scope.


b) In Java we can usually access a variable as long as it was defined within the same set
of brackets as the code we are writing or within any curly brackets inside of the curly
brackets where the variable was defined.
c) Any variable defined in a class outside of any method can be used by all member
methods.
d) When a method has the same local variable as a member, “this” keyword can be used
to reference the current class variable.
e) For a variable to be read after the termination of a loop, It must be declared before the
body of the loop.

The Java Class Libraries

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

1. Core Java Class Libraries

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.

2. Important Java Packages and Their Functionality

A. java.lang (Fundamental Classes)

This package is automatically imported in every Java program and provides fundamental
classes.

a) Object – The root class of all Java classes.


b) String – Immutable sequence of characters.
c) Math – Provides mathematical operations.
d) System – Provides system-related operations like I/O and garbage collection.
e) Thread – Supports multithreading.

Example:

System.out.println(Math.sqrt(25)); // Output: 5.0

B. java.util (Utility Classes & Data Structures)

This package provides collections, date/time utilities, random number generation, and other
utility functions.

a) ArrayList, LinkedList, HashMap, HashSet – Data structures.


b) Collections – Utility class for collection operations.
c) Date, Calendar, TimeZone – Date and time handling.
d) Random – Random number generation.
Example:

ArrayList<String> list = new ArrayList<>();


list.add("Java");
list.add("Python");
System.out.println(list); // Output: [Java, Python]

C. java.io (File Handling and Streams)

The java.io package provides classes for file handling and input/output streams.

a) File – Represents files and directories.


b) FileInputStream, FileOutputStream – Byte stream classes.
c) BufferedReader, BufferedWriter – Character stream classes.

Example:

File file = new File("test.txt");


if (file.exists()) {
System.out.println("File found");
} else {
System.out.println("File not found");
}

D. java.nio (New Input/Output)

Introduced in Java NIO (New I/O), this package provides faster and more flexible
input/output operations.

a) Path – Represents file paths.


b) Files – Utility class for file operations.
c) ByteBuffer, CharBuffer – Buffer classes for handling binary and character data.

Example:

Path path = Paths.get("test.txt");


Files.write(path, "Hello World!".getBytes());

E. java.net (Networking)

Java supports networking operations like socket programming and HTTP requests.

a) Socket, ServerSocket – Used for TCP/IP networking.


b) URL, URLConnection – Used for web communication.
c) InetAddress – Represents IP addresses.

Example:

InetAddress address = InetAddress.getLocalHost();


System.out.println(address.getHostName());

F. java.sql (Database Connectivity)

The java.sql package provides JDBC (Java Database Connectivity) support.

a) Connection – Represents a connection to a database.


b) Statement, PreparedStatement – Used for executing SQL queries.
c) ResultSet – Stores query results.

Example:

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb",


"user", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
while (rs.next()) {
System.out.println(rs.getString("name"));
}

3. Java Class Library Extensions

In addition to core packages, Java provides several extended libraries, including:

a) javax.swing – GUI components.


b) javax.xml.parsers – XML parsing.
c) java.time – Modern date/time API.
d) java.security – Security-related classes.

4. Summary

a) Java provides a rich standard library covering essential functionalities.


b) The java.lang package is automatically imported and contains fundamental classes.
c) java.util provides collections, utilities, and date/time classes.
d) java.io and java.nio handle file I/O operations.
e) java.net supports networking.
f) java.sql enables database connectivity.

Data Types, Variables, and Arrays in Java

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

Java has two main categories of data types:

A. Primitive Data Types (e.g., int, float, char)


B. Reference Data Types (e.g., String, Arrays, Objects)

A. Primitive Data Types

Primitive data types store simple values and are not objects. Java has 8 primitive types:

Data Type Size Default Value Example


byte 1 byte 0 byte b = 10;
short 2 bytes 0 short s = 100;
int 4 bytes 0 int num = 1000;
long 8 bytes 0L long l = 100000L;
float 4 bytes 0.0f float f = 10.5f;
double 8 bytes 0.0 double d = 99.99;
char 2 bytes '\u0000' char c = 'A';
boolean 1 bit false boolean isJavaFun = true;

Example:

int a = 10;
double b = 20.5;
boolean flag = true;

B. Reference Data Types

Reference types store the memory address of an object instead of actual values.

a) String – A sequence of characters.


b) Arrays – A collection of similar data types.
c) Classes & Objects – Custom data structures.

Example:

String name = "Java";


int[] numbers = {1, 2, 3, 4, 5};

3. Variables in Java

A variable is a named memory location used to store data.

A. Declaring Variables
dataType variableName = value;

Example:

int age = 25;


double salary = 50000.75;

B. Types of Variables

Java has three types of variables:

1. Local Variables – Declared inside a method or block.


2. Instance Variables – Defined inside a class but outside methods (belongs to an
object).
3. Static Variables – Defined using static keyword (shared by all instances).

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);
}
}

C. Variable Naming Rules

1. Must start with a letter, underscore (_), or dollar sign ($).


2. Cannot be a Java keyword (e.g., int, class).
3. Java is case-sensitive (Age and age are different).

4. Type Conversion & Type Casting

Java supports automatic and explicit type conversions.

A. Implicit Type Conversion (Widening)

Smaller data types are automatically converted into larger ones.

Example:

int num = 100;


double d = num; // int -> double (widening)
System.out.println(d); // Output: 100.0

B. Explicit Type Conversion (Narrowing)


Larger data types must be explicitly converted into smaller ones.

Example:

double pi = 3.14159;
int x = (int) pi; // Explicit casting
System.out.println(x); // Output: 3

5. Constants in Java

Constants are variables whose values cannot be changed.

 Declared using the final keyword.

Example:

final double PI = 3.1416;


PI = 3.14; // ❌ This will cause an error

6. Arrays in Java

An array is a collection of elements of the same data type.

A. Declaring and Initializing Arrays

dataType[] arrayName = new dataType[size];

Example:

int[] numbers = new int[5]; // Declares an array of size 5


int[] values = {10, 20, 30, 40, 50}; // Direct initialization

B. Accessing Array Elements

Array elements are accessed using indexing (starting from 0).

Example:

int[] arr = {5, 10, 15};


System.out.println(arr[0]); // Output: 5

C. Iterating Over an Array

Using a for loop:

for (int i = 0; i < arr.length; i++) {


System.out.println(arr[i]);
}

Using an enhanced for loop:

for (int num : arr) {


System.out.println(num);
}

D. Multi-Dimensional Arrays

Java supports 2D and 3D arrays.

Example (2D Array):

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.

You might also like