0% found this document useful (0 votes)
24 views69 pages

Object-Oriented Programming Overview

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views69 pages

Object-Oriented Programming Overview

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

LECTURE NOTES

ON
OBJECT ORIENTED PROGRAMMING

PREPARED BY-
DIBYASHA DAS
ASSISTANT PROFESSOR
CSE
MODULE 1
A programming language is a set of instructions and syntax used to create software programs. A programming
language is a formal language that specifies a set of instructions for a computer to perform specific tasks. It's
used to write software programs and applications, and to control and manipulate computer systems. Some of the
key features of programming languages include:
1. Syntax: The specific rules and structure used to write code in a programming language.
2. Data Types: The type of values that can be stored in a program, such as numbers, strings, and booleans.
3. Variables: Named memory locations that can store values.
4. Operators: Symbols used to perform operations on values, such as addition, subtraction, and
comparison.
5. Control Structures: Statements used to control the flow of a program, such as if-else statements, loops,
and function calls.
6. Libraries and Frameworks: Collections of pre-written code that can be used to perform common tasks
and speed up development.
Different types of programming language
5 major types of programming languages are-
1. Procedural programming languages
A procedural language follows a sequence of statements or commands to achieve a desired output. Each series
of steps is called a procedure, and a program written in one of these languages will have one or more
procedures within it. Common examples of procedural languages include:
• C and C++
• Java
• Pascal
• BASIC

2. Functional programming languages


Rather than focusing on the execution of statements, functional languages focus on the output of mathematical
functions and evaluations. Each function–a reusable module of code–performs a specific task and returns a
result. The result will vary depending on what data you input into the function. Some popular functional
programming languages include:
• Scala
• Erlang
• Haskell
• Elixir
• F#

3. Object-oriented programming languages


This type of language treats a program as a group of objects composed of data and program elements, known as
attributes and methods. Objects can be reused within a program or in other programs. This makes it a popular
language type for complex programs, as code is easier to reuse and scale. Some common object-oriented
programming (OOP) languages include:
• Java
• Python
• PHP
• C++
• Ruby

4. Scripting languages
Programmers use scripting languages to automate repetitive tasks, manage dynamic web content, or support
processes in larger applications. Some common scripting languages include:
• PHP
• Ruby
• Python
• bash
• Perl
• [Link]

5. Logic programming languages


Instead of telling a computer what to do, a logic programming language expresses a series of facts and rules to
instruct the computer on making decisions. Some examples of logic languages include:
• Prolog
• Absys
• Datalog
• Alma-0

Difference between Compiler and Interpreter


A language processor that converts a program written in high-level language into machine language, entire
program at once, is called a compiler. Thus, the input of a compiler is a high-level language code (called source
code), while its output is a machine language code (called object code).
A language translator that converts a high-level language program into a machine language program, one line at
a time, is referred to as an interpreter.

Parameter Compiler Interpreter

Program Compilers scan the entire The program is interpreted/translated one


scanning program in one go. line at a time.

As and when scanning is


performed, all the errors are One line of code is scanned, and errors
Error detection
shown in the end together, not encountered are shown.
line by line.

It is not preferred due to its slow speed.


The execution time of compiler Usually, interpreter is slow, and hence
Execution time
is less, hence it is preferred. takes more time to execute the object
code.

Need of source Compiler doesn't require the It requires the source code for execution
code source code for execution later. later.

Programming Programming languages that Programming languages that uses


languages use compilers include C, C++, interpreter include Python, Ruby, Perl,
C#, etc.. MATLAB, etc.

Size Compiler are larger in size. Interpreters are smaller in size.

Flexibility Compilers are not flexible. Interpreters are relatively flexible.

Efficiency Compilers are more efficient. Interpreters are less efficient.

Procedural Programming vs. Object-Oriented Programming

Procedural Programming Object-Oriented Programming

Procedural Programming focuses on the sequential Object-Oriented Programming focuses on the data
steps required to achieve a result. that is used for programming.

Functions and variables are the primary Classes and objects are the primary programming
programming tools. tools.

Does not provide data security. Provides data security.

It cannot model the real world effectively. It can model the real world effectively.

It is not suitable for large and complex apps. It is suitable for large and complex apps.

Procedural programming follows a top-down Object-oriented programming follows a bottom-up


approach. approach.

C, Basic, Fortran, Pascal, etc., are examples of C++, Java, Python, JavaScript, etc., are examples of
procedural languages. object-oriented languages.

Introduction to Object Oriented Programming:


• The word object-oriented is the combination of two words i.e. object and oriented. The dictionary
meaning of the object is an article or entity that exists in the real world. The meaning of oriented is
interested in a particular kind of thing or entity. In layman's terms, it is a programming pattern that
rounds around an object or entity are called object-oriented programming. The object-oriented
programming is basically a computer programming design philosophy or methodology that organizes/
models software design around data, or objects rather than functions and logic.
Advantages of OOP
• OOP is faster and easier to execute
• OOP provides a clear structure for the programs
• OOP makes it possible to create full reusable applications with less code and shorter development time
• By using objects and classes, you can create reusable components, leading to less duplication and more
efficient development.
• It provides a clear and logical structure, making the code easier to understand, maintain, and debug.
• OOP supports the DRY (Don't Repeat Yourself) [Link] principle encourages minimizing code
repetition, leading to cleaner, more maintainable code. Common functionalities are placed in a single
location and reused, reducing redundancy.
• By reusing existing code and creating modular components, OOP allows for quicker and more efficient
application development

Basic concepts of OOP

➢ Object
➢ Class
➢ Inheritance
➢ Polymorphism
➢ Abstraction
➢ Encapsulation

Object:
• Any entity that has state and behavior is known as an object. For example, a chair, pen, table, keyboard,
bike, etc.
• An object contains an address and takes up some space in memory. Objects can communicate
without knowing the details of each other's data or code. The only necessary thing is the type of
message accepted and the type of response returned by the objects.

Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like
wagging the tail, barking, eating, etc.

Class:
• Collection of objects is called class.
• Classes are user-defined datatypes.
• A class can also be defined as a blueprint from which you can create an individual object. Class doesn't
consume any space.
• A class is a group of objects which have common properties.
• A class is a collection of Data member and member functions.
• Variables declared in a class are called data member and functions declared in class are called member
functions or methods.
• Once a class has been defined, we can create any number of objects belonging to that class.
• If Fruit is a class, then apple, orange, banana etc. are the objects of the class Fruit.
Inheritance

• When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance.
• It is an important part of OOPs (Object Oriented programming system).
• It provides code reusability.
• Inheritance is also known as a parent-child relationship.
• The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class also.
• Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.

Terms used in Inheritance


• Class: A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created.
• Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived
class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is
also called a base class or a parent class.
• Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields
and methods of the existing class when you create a new class. You can use the same fields and methods
already defined in the previous class.
Polymorphism
• The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.
• A person at the same time can have different characteristics. Like a man at the same
time is a father, a husband, an employee. So the same person possesses different
behavior in different situations. This is called polymorphism.
• Polymorphism is considered one of the important features of Object-Oriented
Programming. Polymorphism allows us to perform a single action in different ways.
In other words, polymorphism allows you to define one interface and have multiple
implementations. The word “poly” means many and “morphs” means forms, So it
means many forms.
In Java, we use method overloading and method overriding to achieve polymorphism. In
Java polymorphism is mainly divided into two types:
1. Compile-time Polymorphism
2. Runtime Polymorphism

Abstraction
• Hiding internal or background details and showing the essential features is known as
abstraction. The unnecessary details are not displayed to the user.
• It allows to focus on what an object does rather than how it does it.
• For example, phone call, we don't know the internal processing.
• In Java, we use abstract class and interface to achieve abstraction.

Encapsulation
• Binding (or wrapping) code and data together into a single unit typically a class are
known as encapsulation.
• 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.
• 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.
• For example, a capsule, it is wrapped with different medicines.

What is Java?
• Java is a programming language and a platform.
• Platform: Any hardware or software environment in which a program runs, is known
as a platform. Since Java has a runtime environment (JRE) and Application
Programming Interface (API), it is called a platform.
• Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in
the year 1995.
• James Gosling is known as the father of Java.
• Before Java, its name was Oak.
• Since Oak was already a registered company, so James Gosling and his team changed
the Oak name to Java.
• Java is mostly used for building –

❖ Desktop Applications such as acrobat reader, media player, antivirus, etc,


❖ Web Applications such as [Link].
❖ Enterprise Applications such as banking applications.
❖ Mobile
❖ Embedded System
❖ Smart Card
❖ Robotics
❖ Games, etc.

Types of Java Applications


1. Standalone Application
Standalone applications are also known as desktop applications or window-based
applications. These are traditional software that we need to install on every machine.
Examples of standalone application are Media player, antivirus, etc. AWT and Swing are used
in Java for creating standalone applications.
2. Web Application
An application that runs on the server side and creates a dynamic page is called a web
application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are
used for creating web applications in Java.
3. Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called
enterprise application. In Java, Enterprise Java Beans (EJB) is used for creating enterprise
applications.
4. Mobile Application
An application which is created for mobile devices is called a mobile application. Currently,
Android and Java ME are used for creating mobile applications.
Java Platforms / Editions
1. Java SE (Java Standard Edition)
It is a Java programming platform. It includes Java programming APIs such as [Link],
[Link], [Link], [Link], [Link], [Link] etc. It includes core topics like OOPs, String,
Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing, etc.
2. Java EE (Java Enterprise Edition)
It is an enterprise platform which is mainly used to develop web and enterprise applications.
It is built on the top of the Java SE platform. It includes topics like Servlet, JSP, Web
Services, EJB etc.
3. Java ME (Java Micro Edition)
It is a micro platform which is mainly used to develop mobile applications.
4. JavaFX
It is used to develop rich internet applications. It uses a light-weight user interface API.
History behind Java
❖ James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers called Green Team.
❖ Initially designed for small, embedded systems in electronic appliances like set-top
boxes.
❖ Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
❖ After that, it was called Oak and was developed as a part of the Green project.
Why “Oak” and “Java”?
❖ The name Oak was used by Gosling after an oak tree that remained outside his
office. Also, Oak is an image of solidarity and was picked as a national tree of
numerous nations like the U.S.A., France, Germany, Romania, etc. But they had to
later rename it as JAVA as it was already a trademark by Oak
Technologies. “JAVA” Gosling and his team did a brainstorming session, and after
the session, they came up with several names such as JAVA, DNA, SILK, RUBY,
etc. The name " Java " was decided after much discussion since it was so unique.
❖ The name Java originates from a sort of espresso bean, Java. Gosling came up with
this name while having a coffee near his office. Java was created on principles
like Robust, Portable, Platform Independent, High Performance, Multithread,
etc., and was called one of the Ten Best Products of 1995 by TIME MAGAZINE.
Currently, Java is used in internet programming, mobile devices, games, e-
business solutions, etc.

Difference between C++ and Java

Features C++ Java


Platform Independence Platform-dependent Platform-independent
Interpreter and Compiler Compiled programming Compiled and interpreted
language language
Portability Not portable Portable
Memory Management Manual System-controlled
Multiple Inheritance Supports single Only supports single inheritance
inheritance and multiple
inheritance
Overloading Both operators and Allows only method
methods can be overloading
overloaded
Compatibility with Other Compatible with C Not compatible with any
Programming Languages language
Pointers Supports pointers Supports pointers with
restrictions
Documentation Comment Does not support documentation Has built-in documentation
comments comments support (/**…**/),
allowing Java files to have their
own documentation

Thread Support Does not support thread Has built-in thread support via
the “thread” class

Features of Java
• Simple
• Object-Oriented
• Open Source
• Portable
• Platform independent
• Secured
• Robust
• Architecture neutral
• Interpreted
• High Performance
• Multithreaded
• Distributed
• Dynamic

1. Simple
• Java syntax is based on C++ (so easier for programmers to learn it after C++).
• Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
• There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.

2. Object-oriented
• Java is an object-oriented programming language. Everything in Java is an object.
• Object-oriented means we organize our software as a combination of different types
of objects that incorporates both data and behavior.

3. Open Source
• The source code of java development is not limited to sun microsystem or oracle
corporation, it is freely available to any end user, according to requirement anyone
can customize it which is known as open source.
4. Platform Independent
• Java is platform independent because it is different from other languages like C,
C++, etc. which are compiled into platform specific machines
• Java is a write once, run anywhere.

5. Secured
• No explicit pointer means Java does not allow direct manipulation of memory through
pointers. This eliminates a class of vulnerabilities like buffer overflows and pointer
arithmetic errors, which are common sources of security exploits.
• Automatic memory management(Garbage Collection). Java's automatic garbage
collection handles memory allocation and deallocation, reducing the risk of memory
leaks and other memory-related errors that can lead to security vulnerabilities.
• Java Programs run inside a virtual machine sandbox i.e isolating the application from
direct access to the underlying operating system and hardware
• Bytecode Verifier: It checks the code fragments for illegal code that can violate
access right to objects.

6. Robust(Strong)
• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• There is automatic garbage collection in java which runs on the Java Virtual Machine
to get rid of objects which are not being used by a Java application anymore.
• There are exception handling and the type checking mechanism in Java. All these
points make Java robust.

7. Architecture-neutral
• The memory allocation and memory deallocation is totally same for all
environment(Windows,Linux), for example, the size of primitive types is fixed.
• In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture.
• It occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
8. Portable
• Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.

9. High-performance
• Java is faster than other traditional interpreted programming languages.
• It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted
language that is why it is slower than compiled languages, e.g., C, C++, etc.

10. Distributed
• Java is distributed because it facilitates users to create distributed applications in
Java.
• This feature of Java makes us able to access files by calling the methods from
any machine on the internet.

11. Multi-threaded
• A thread is like a separate program, executing concurrently.
• We can write Java programs that deal with many tasks at once by defining multiple
threads.
• The main advantage of multi-threading is that it doesn't occupy memory for each
thread.
• It shares a common memory area.
• Threads are important for multi-media,Web applications, etc.

12. Dynamic
• Java is a dynamic language. It supports dynamic loading of classes. It means classes
are loaded on demand.
• It also supports functions from its native languages, i.e., C and C++.
• Java supports dynamic compilation and automatic memory management (garbage
collection).

Requirements to write a java program


Install the JDK
Set path of the jdk/bin directory.
Create the java program
Compile and run the java program

class Simple{
public static void main(String args[])
{
[Link]("Hello Java");
}
}
save this file as [Link]
To compile: javac [Link]
To execute: java Simple
class Simple{
public static void main(String args[])
{
[Link]("Hello Java");
}
}
• class keyword is used to declare a class in java.
• public keyword is an access modifier which represents visibility. It means it is visible
to all.
• static is a keyword. If we declare any method as static, it is known as the static
method. The core advantage of the static method is that there is no need to create an
object to invoke the static method. The main method is executed by the JVM, so it
doesn't require to create an object to invoke the main method. So it saves memory.
• void is the return type of the method. It means it doesn't return any value.
• main represents the starting point of the program.
• String[] args is used for command line argument.
• [Link]() is used to print statement. Here, System is a class, out is the
object of PrintStream class, println() is the method of PrintStream class.

How many ways can we write a Java program


• By changing the sequence of the modifiers, method prototype is not changed in Java.
static public void main(String args[])

• The subscript notation in Java array can be used after type, before the variable or after
the variable.
public static void main(String[] args)

• You can provide [] args support to the main method by passing 3 ellipses (dots)
public static void main(String... args)

• Having a semicolon at the end of class is optional in Java.


class A{
static public void main(String... args)
{ [Link]("hello java4");
}
};

• Valid java main method signature


public static void main(String[] args)
public static void main(String args[])
public static void main(String... args)
static public void main(String[] args)
public static final void main(String[] args)
final public static void main(String[] args)
• Invalid java main method signature
public void main(String[] args)
static void main(String[] args)
public void static main(String[] args)

What happens at compile time?


At compile time, java file is compiled by Java Compiler (It does not interact with OS)
and converts the java code into bytecode.

What happens at runtime?


At runtime, following steps are performed:
Classloader: is the subsystem of JVM that is used to load class files.
Bytecode Verifier: checks the code fragments for illegal code that can violate access right to
objects.
Interpreter: read bytecode stream then execute the instructions.
Can we save a java source file by other name than the class name?
Yes, if the class is not public.
To Compile- javac [Link]
To execute- java Simple

Can we have multiple classes in a java source file?


Yes

JVM
• 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.
• It is a specification that provides a runtime environment in which Java bytecode can
be executed.
• JVMs are available for many hardware and software platforms. JVM, JRE, and JDK
are platform dependent because the configuration of each OS is different from each
other.
• However, Java is platform independent.
The JVM performs the following main tasks:
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
Architecture of JVM

Core Components Of 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.

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


• Verification: It ensures the correctness of the .class file i.e. it checks whether this file
is properly formatted and generated by a valid compiler or not. If verification fails, we
get run-time exception [Link]. This activity is done by the component
ByteCodeVerifier. Once this activity is completed then the class file is ready for
compilation.
• Preparation: JVM allocates memory for class static variables and initializing the
memory to default values.
• Resolution: It is the process of replacing symbolic references from the type with
direct references. It is done by searching into the method area to locate the referenced
entity.
❖ Initialization: In this phase, all static variables are assigned with their values defined
in the code and static block(if any). This is executed from top to bottom in a class and
from parent to child in the class hierarchy.

2. JVM Memory Areas


• 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.
• 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.
• 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.
• PC Registers: Store address of current execution instruction of a thread. Obviously,
each thread has separate PC Registers.
• Native method stacks: For every thread, a separate native stack is created. It stores
native method information.

3. 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:
• Interpreter: It interprets the bytecode line by line and then executes. The
disadvantage here is that when one method is called multiple times, every time
interpretation is required.
• Just-In-Time Compiler(JIT): It is used to increase the efficiency of an interpreter. It
compiles the entire bytecode and changes it to native code so whenever the interpreter
sees repeated method calls, JIT provides direct native code for that part so re-
interpretation is not required, thus efficiency is improved.
• Garbage Collector: It destroys un-referenced objects.
4. Java Native Interface (JNI)
• Java Native Interface (JNI) is a framework which provides an interface to
communicate with another application written in another language like C,
C++, Assembly etc.
• Java uses JNI framework to send output to the Console or interact with
OS libraries.
5. Native Method Libraries
• These are collections of native libraries required for executing native methods. They
include libraries written in languages like C and C++.
JRE
• JRE is an acronym for Java Runtime Environment.
• The Java Runtime Environment is a set of software tools which are used for
developing Java applications.
• It is used to provide the runtime environment.
• It is the implementation of JVM.

JDK
• JDK is an acronym for Java Development Kit.
• The Java Development Kit (JDK) is a software development environment which is
used to develop Java applications and applets.
• The JDK contains a private Java Virtual Machine (JVM) and a few other resources
such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a
documentation generator (Javadoc), etc. to complete the development of a Java
Application.

Comments: They can either be multi-line or single line comments.


• /* This is a simple Java program. Call this file "[Link]". */
This is a multiline comment. This type of comment must begin with /* and end with */.
• For single line you may directly use // as in C/C++.
Variables in Java
In Java, variables are containers that store data in memory. Understanding variables plays a
very important role as it defines how data is stored, accessed, and manipulated.
Key Components of Variables in Java:
A variable in Java has three components, which are listed below:
• Data Type: Defines the kind of data stored (e.g., int, String, float).
• Variable Name: A unique identifier following Java naming rules.
• Value: The actual data assigned to the variable.
How to Initialize Java Variables?

// Demonstrating how to intialize variables of different types in Java

class Geeks{
public static void main(String[] args) {
// Declaring and initializing variables

// Initializing float variable


float si = 5.5f;

// Initializing integer variables


int t = 10;
int s = 20;

// Initializing character variable


char var = 'h';

// Displaying the values of the variables


[Link]("Simple Interest: " + si);
[Link]("Speed: " + s);
[Link]("Time: " + t);
[Link]("Character: " + var);
}
}

Output
Simple Interest: 5.5
Speed: 20
Time: 10
Character: h

Types of Java Variables


• Local Variables
• Instance Variables
• Static Variables
1. Local Variables
A variable defined within a block or method or constructor is called a local variable.
• The Local variable is created at the time of declaration and destroyed when the
function completed its execution.
• The scope of local variables exists only within the block in which they are declared.
• We first need to initialize a local variable before using it within its scope.

// Java Program to show the use of local variables import [Link].*;


class Geeks {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;

// This variable is local to this main method only


[Link]("Local Variable: " + var);
}
}
Output
Local Variable: 10

[Link] Variables
• Instance variables are known as non-static variables and are declared in a class but
outside of any method, constructor, or block.
• Instance variables are created when an object of the class is created and destroyed
when the object is destroyed.
• Unlike local variables, we may use access specifiers for instance variables. If we do
not specify any access specifier, then the default access specifier will be used.
• Initialization of an instance variable is not mandatory. Its default value is dependent
on the data type of variable. For String it is null, for float it is 0.0f, for int it is 0,
for Wrapper classes like Integer it is null, etc.
• Instance variables can be accessed only by creating objects.

// Java Program to show the use of Instance Variables


import [Link].*;

class Geeks {

// Declared Instance Variable


public String geek;
public int i;
public Integer I;
public Geeks()
{
// Default Constructor initializing Instance Variable
[Link] = "Sweta Dash";
}

// Main Method
public static void main(String[] args)
{
// Object Creation
Geeks name = new Geeks();

// Displaying O/P
[Link]("Geek name is: " + [Link]);
[Link]("Default value for int is "+ name.i);

// toString() called internally


[Link]("Default value for Integer is: "+ name.I);
}
}
Output
Geek name is: Sweta Dash
Default value for int is 0
Default value for Integer is: null

3. Static Variables
• Static variables are also known as class variables.
• These variables are declared similarly to instance variables. The difference is that
static variables are declared using the static keyword within a class outside of any
method, constructor, or block.
• Unlike instance variables, we can only have one copy of a static variable per class,
irrespective of how many objects we create.
• Static variables are created at the start of program execution and destroyed
automatically when execution ends.
• Initialization of a static variable is not mandatory. Its default value is dependent on the
data type of variable. For String it is null, for float it is 0.0f, for int it is 0, for Wrapper
classes like Integer it is null, etc.
• If we access a static variable like an instance variable (through an object), the
compiler will show a warning message, which won't halt the program. The compiler
will replace the object name with the class name automatically.
• If we access a static variable without the class name, the compiler will automatically
append the class name. But for accessing the static variable of a different class, we
must mention the class name as 2 different classes might have a static variable with
the same name.
• Static variables cannot be declared locally inside an instance method.
• Static blocks can be used to initialize static variables.
// Java Program to show the use of Static variables
import [Link].*;

class Geeks {

// Declared static variable


public static String geek = "Sweta Dash";

public static void main(String[] args)


{

// geek variable can be accessed without object


// creation Displaying O/P [Link] --> using the static variable
[Link]("Geek Name is: " + [Link]);

// static int c = 0;
// above line, when uncommented,will throw an error as static variables cannot be
declared locally.
}
}
Output
Geek Name is: Sweta Dash

Java Data Types


• In Java, compiler knows exactly what types each variable holds and enforces correct
usage during compilation. For example "int x = "GfG";" gives compiler error in Java
as we are trying to store string in an integer type.
• Data types in Java are of different sizes and values that can be stored in a variable that
is made as per convenience and circumstances to handle different scenarios or data
requirements.

Java Data Type Categories


Java has two categories in which data types are segregated
1. Primitive Data Type: These are the basic building blocks that store simple values directly
in memory. Examples of primitive data types are
• boolean
• char
• byte
• short
• int
• long
• float
• double
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.

Syntax:
boolean booleanVar;

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

// Demonstrating boolean data type


public class Geeks {
public static void main(String[] args) {
boolean b1 = true;
boolean b2 = false;

[Link]("Is Java fun? " + b1);


[Link]("Is fish tasty? " + b2);
}
}

Output
Is Java fun? true
Is fish tasty? False

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)

// Demonstrating byte data type


public class Geeks {
public static void main(String[] args) {
byte a = 25;
byte t = -10;

[Link]("Age: " + a);


[Link]("Temperature: " + t);
}
}
Output
Age: 25
Temperature: -10

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)

// Demonstrating short data types


public class Geeks {
public static void main(String[] args) {
short num = 1000;
short t = -200;

[Link]("Number of Students: " + num);


[Link]("Temperature: " + t);
}
}
Output
Number of Students: 1000
Temperature: -200

4. int Data Type


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

Syntax:
int intVar;

Size : 4 bytes ( 32 bits )

// Demonstrating int data types


public class Geeks {
public static void main(String[] args) {
int p = 2000000;
int d = 150000000;

[Link]("Population: " + p);


[Link]("Distance: " + d);
}
}
Output
Population: 2000000
Distance: 150000000

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)

// Demonstrating long data type


public class Geeks {
public static void main(String[] args) {
long w = 7800000000L;
long l = 9460730472580800L;

[Link]("World Population: " + w);


[Link]("Light Year Distance: " + l);
}
}
Output
World Population: 7800000000
Light Year Distance: 9460730472580800

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)

// Demonstrating float data type


public class Geeks {
public static void main(String[] args) {
float pi = 3.14f;
float gravity = 9.81f;

[Link]("Value of Pi: " + pi);


[Link]("Gravity: " + gravity);
}
}
Output
Value of Pi: 3.14
Gravity: 9.81

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)

// Demonstrating double data type


public class Geeks {
public static void main(String[] args) {
double pi = 3.141592653589793;
double an = 6.02214076e23;

[Link]("Value of Pi: " + pi);


[Link]("Avogadro's Number: " + an);
}
}
Output
Value of Pi: 3.141592653589793
Avogadro's Number: 6.02214076E23

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)

// Demonstrating char data type


public class Geeks{
public static void main(String[] args) {
char g = 'A';
char s = '$';

[Link]("Grade: " + g);


[Link]("Symbol: " + s);
}
}

Output
Grade: A
Symbol: $

Example
Type Description Default Size Literals Range of values

JVM-
dependent
true or false false true, false true, false
(typically
boolean 1 byte)

8-bit signed
0 1 byte (none) -128 to 127
byte integer

'a',
Unicode
'\u0041',
character(16 \u0000 2 bytes 0 to 65,535 (unsigned)
'\101', '\\',
bit)
char '\', '\n', 'β'

16-bit
signed 0 2 bytes (none) -32,768 to 32,767
short integer

32-bit -2,147,483,648
signed 0 4 bytes -2,0,1 to
int integer 2,147,483,647

-
64-bit
9,223,372,036,854,775,808
signed 0L 8 bytes -2L,0L,1L
to
integer
long 9,223,372,036,854,775,807

32-bit IEEE
754 3.14f, - ~6-7 significant decimal
0.0f 4 bytes
floating- 1.23e-10f digits
float point

64-bit IEEE 3.1415d, ~15-16 significant decimal


0.0d 8 bytes
double 754 1.23e100d digits
Example
Type Description Default Size Literals Range of values

floating-
point

2. Non-Primitive Data Types (Object Types): It will contain a memory address of variable
values because the reference types won’t store the variable value directly in memory.
Examples of Non-primitive data types are
• String
• Array
• Class
• Interface
• Object

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.

// Demonstrating String data type


public class Geeks {
public static void main(String[] args) {
String n = "Geek1";
String m = "Hello, World!";

[Link]("Name: " + n);


[Link]("Message: " + m);
}
}
Output
Name: Geek1
Message: Hello, World!

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.

// Demonstrating how to create a class


class Car {
String model;
int year;

Car(String model, int year) {


[Link] = model;
[Link] = year;
}

void display() {
[Link](model + " " + year);
}
}

public class Geeks {


public static void main(String[] args) {
Car myCar = new Car("Toyota", 2020);
[Link]();
}
}
Output
Toyota 2020

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.

// Define the Car class


class Car {
String model;
int year;

// Constructor to initialize the Car object


Car(String model, int year) {
[Link] = model;
[Link] = year;
}
}

// Main class to demonstrate object creation


public class Geeks {
public static void main(String[] args) {
// Create an object of the Car class
Car myCar = new Car("Honda", 2021);

// Access and print the object's properties


[Link]("Car Model: " + [Link]);
[Link]("Car Year: " + [Link]);
}
}
Output
Car Model: Honda
Car Year: 2021

4. Interface
Like a class, an interface can have methods and variables, but the methods declared in an
interface are by default abstract (only method signature, no body).
• Interfaces specify what a class must do and not how. It is the blueprint of the class.
• An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move(). So it specifies a set
of methods that the class has to implement.
• If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then the class must be declared abstract.

// Demonstrating the working of interface


interface Animal {
void sound();
}

class Dog implements Animal {


public void sound() {
[Link]("Woof");
}
}

public class InterfaceExample {


public static void main(String[] args) {
Dog myDog = new Dog();
[Link]();
}
}
Output
Woof

5. Array
An Array is a group of like-typed variables that are referred to by a common name. In Java,
all arrays are dynamically allocated. (discussed below)
• Since arrays are objects in Java, we can find their length using member length. This is
different from C/C++ where we find length using size.
• A Java array variable can also be declared like other variables with [] after the data
type.
• The variables in the array are ordered and each has an index beginning with 0.
• Java array can also be used as a static field, a local variable, or a method parameter.
• The size of an array must be specified by an int value and not long or short.
• The direct superclass of an array type is Object.
// Demonstrating how to create an array
public class Geeks {
public static void main(String[] args) {
int[] num = {1, 2, 3, 4, 5};
String[] arr = {"Geek1", "Geek2", "Geek3"};

[Link]("First Number: " + num[0]);


[Link]("Second Fruit: " + arr[1]);
}
}

Output
First Number: 1
Second Fruit: Geek2

Java Tokens

In Java, Tokens are the smallest elements of a program that is meaningful to the compiler.
They are also known as the fundamental building blocks of the program. Tokens can be
classified as follows:

1. Keywords
2. Identifiers
3. Constants/Literals
4. Operators
5. Separators

1. Keyword
Keywords are pre-defined or reserved words in a programming language. Each keyword is
meant to perform a specific function in a program. Since keywords are referred names for a
compiler, they can’t be used as variable names because by doing so, we are trying to assign a
new meaning to the keyword which is not allowed. Java language supports the following
keywords:
2. Identifiers
Identifiers are used as the general terminology for naming of variables, functions and arrays.
These are user-defined names consisting of an arbitrarily long sequence of letters and digits
with either a letter or the underscore (_) as a first character. Identifier names must differ in
spelling and case from any keywords. You cannot use keywords as identifiers; they are
reserved for special use. Once declared, you can use the identifier in later program statements
to refer to the associated value.

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
3. Constants/Literals
Constants are also like normal variables. But the only difference is, their values cannot be
modified by the program once they are defined. Constants refer to fixed values. They are also
called as literals. Constants may belong to any of the data type.

Syntax:
final data_type variable_name;

import [Link].*;

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

// Here final keyword is used to define the constant PI


final double PI = 3.14; // Use double instead of int

// Example usage of PI
[Link]("The value of PI is: " + PI);
}
}

[Link]
Java provides many types of operators which can be used according to the need. They are
classified based on the functionality they provide. Some of the types are-
• Arithmetic Operators
• Unary Operators
• Assignment Operator
• Relational Operators
• Logical Operators
• Ternary Operator
• Bitwise Operators
• Shift Operators
• instance of operator
• Precedence and Associativity

5. Separators
Separators are used to separate different parts of the codes. It tells the compiler about
completion of a statement in the program. The most commonly and frequently used separator
in java is semicolon (;).
int variable; //here the semicolon (;) ends the declaration of the variable
import [Link].*;
class GFG {
public static void main (String[] args) {

//Here the semicolon (;) used to


// end the print statement
[Link]("GFG!");
}
}

Java Operators
Java operators are special symbols that perform operations on variables or values. These
operators are essential in programming as they allow you to manipulate data efficiently.
Some of the types are-
• Arithmetic Operators
• Unary Operators
• Assignment Operator
• Relational Operators
• Logical Operators
• Ternary Operator
• Bitwise Operators
• Shift Operators
• instance of operator

1. Arithmetic Operators
They are used to perform simple arithmetic operations on primitive and non primitive data
types.
* : Multiplication
/ : Division
% : Modulo
+ : Addition
– : Subtraction

// Java Program to show the use of Arithmetic Operators


import [Link].*;

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

// Arithmetic operators on integers


int a = 10;
int b = 3;

// Arithmetic operators on Strings


String n1 = "15";
String n2 = "25";
// Convert Strings to integers
int a1 = [Link](n1);
int b1 = [Link](n2);

[Link]("a + b = " + (a + b));


[Link]("a - b = " + (a - b));
[Link]("a * b = " + (a * b));
[Link]("a / b = " + (a / b));
[Link]("a % b = " + (a % b));
[Link]("a1 + b1 = " + (a1 + b1));

}
}
Output
a + b = 13
a-b=7
a * b = 30
a/b=3
a%b=1
a1 + b1 = 40

2. Unary Operators
Unary operators need only one operand. They are used to increment, decrement or negate a
value.
– : Unary minus, used for negating the values.
++ : Increment operator, used for incrementing the value by 1.
-- : Decrement operator, used for decrementing the value by 1.
There are two varieties of increment operator.
• Post-Increment : Value is first used for computing the result and then incremented.
• Pre-Increment : Value is incremented first and then result is computed.

There are two varieties of decrement operator.


• Post-decrement : Value is first used for computing the result and then decremented.
• Pre-Decrement : Value is decremented first and then result is computed.

! : Logical not operator, used for inverting a boolean value.

// Java Program to show the use of Unary Operators


import [Link].*;

// Driver Class
class Geeks {
// main function
public static void main(String[] args)
{
// Interger declared
int a = 10;
int b = 10;

// Using unary operators


[Link]("Postincrement : " + (a++));
[Link]("Preincrement : " + (++a));

[Link]("Postdecrement : " + (b--));


[Link]("Predecrement : " + (--b));
}
}
Output
Postincrement : 10
Preincrement : 11
Postdecrement : 10
Predecrement : 9

3. Assignment Operator
“ =” Assignment operator is used to assign a value to any variable.
It has a right to left associativity, i.e value given on right hand side of operator is assigned to
the variable on the left and therefore right hand side value must be declared before using it or
should be a constant.
Syntax :
variable = value;

In many cases assignment operator can be combined with other operators to build a shorter
version of statement called Compound Statement.
For example, instead of a = a+5, we can write a += 5.
+=, for adding left operand with right operand and then assigning it to variable on the left.
-=, for subtracting left operand with right operand and then assigning it to variable on the left.
*=, for multiplying left operand with right operand and then assigning it to variable on the
left.
/=, for dividing left operand with right operand and then assigning it to variable on the left.
%=, for assigning modulo of left operand with right operand and then assigning it to variable
on the left.
// Java Program to show the use of Assignment Operators
import [Link].*;
// Driver Class
class Geeks {
// Main Function
public static void main(String[] args)
{

// Assignment operators
int f = 7;
[Link]("f += 3: " + (f += 3));
[Link]("f -= 2: " + (f -= 2));
[Link]("f *= 4: " + (f *= 4));
[Link]("f /= 3: " + (f /= 3));
[Link]("f %= 2: " + (f %= 2));

}
}
Output
f += 3: 10
f -= 2: 8
f *= 4: 32
f /= 3: 10
f %= 2: 0

4. Relational Operators
These operators are used to check for relations like equality, greater than, less than.
They return boolean result after the comparison and are extensively used in looping
statements as well as conditional if else statements.
Syntax : variable relation_operator value
==, Equal to : returns true if left hand side is equal to right hand side.
!=, Not Equal to : returns true if left hand side is not equal to right hand side.
<, less than : returns true if left hand side is less than right hand side.
<=, less than or equal to : returns true if left hand side is less than or equal to right hand
side.
>, Greater than : returns true if left hand side is greater than right hand side.
>=, Greater than or equal to: returns true if left hand side is greater than or equal to right
hand side.

// Java Program to show the use of Relational Operators


import [Link].*;

// Driver Class
class Geeks {

// main function
public static void main(String[] args)
{
// Comparison operators
int a = 10;
int b = 3;
int c = 5;

[Link]("a > b: " + (a > b));


[Link]("a < b: " + (a < b));
[Link]("a >= b: " + (a >= b));
[Link]("a <= b: " + (a <= b));
[Link]("a == c: " + (a == c));
[Link]("a != c: " + (a != c));
}
}
Output
a > b: true
a < b: false
a >= b: true
a <= b: false
a == c: false
a != c: true

5. Logical Operators
These operators are used to perform “logical AND” and “logical OR” operation, i.e. the
function similar to AND gate and OR gate in digital electronics.
The second condition is not evaluated if the first one is false.
Conditional operators are-
• &&, Logical AND: returns true when both conditions are true.
• ||, Logical OR: returns true if at least one condition is true.
• !, Logical NOT: returns true when a condition is false and vice-versa
// Java Program to show the use of Logical operators
import [Link].*;

class Geeks {

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

// Logical operators
boolean x = true;
boolean y = false;
[Link]("x && y: " + (x && y));
[Link]("x || y: " + (x || y));
[Link]("!x: " + (!x));
}
}
Output
x && y: false
x || y: true
!x: false

6. Ternary operator

The Ternary Operator is a shorthand version of the if-else statement. It has three operands
and hence the name Ternary. The general format is,

condition ? if true : if false

The above statement means that if the condition evaluates to true, then execute the
statements after the '?' else execute the statements after the ':'.

// Java program to illustrate max of three numbers using ternary operator.


public class Geeks {

public static void main(String[] args)


{
int a = 20, b = 10, c = 30, result;

// result holds max of three numbers


result = (a > b) ? a : c;
[Link]("Max of three numbers = "+ result);
}
}
Output
Max of three numbers = 30

7. Bitwise Operators
Bitwise Operators are used to perform the manipulation of individual bits of a number and
with any of the integer types. They are used when performing update and query operations of
the Binary indexed trees.
• & (Bitwise AND): returns bit-by-bit AND of input values.
• | (Bitwise OR): returns bit-by-bit OR of input values.
• ^ (Bitwise XOR): returns bit-by-bit XOR of input values.
• ~ (Bitwise Complement): inverts all bits (one's complement).
// Java Program to show the use of bitwise operators
import [Link].*;

class Geeks
{
public static void main(String[] args)
{
// Bitwise operators
int d = 0b1010;
int e = 0b1100;

[Link]("d & e : " + (d & e));


[Link]("d | e : " + (d | e));
[Link]("d ^ e : " + (d ^ e));
[Link]("~d : " + (~d));
Output
d&e:8
d | e : 14
d^e:6
~d : -11

8. Shift Operators
Shift Operators are used to shift the bits of a number left or right, thereby multiplying or
dividing the number by two, respectively. They can be used when we have to multiply or
divide a number by two. The general format ,

number shift_op number_of_places_to_shift;

• << (Left shift): Shifts bits left, filling 0s (multiplies by a power of two).
• >> (Signed right shift): Shifts bits right, filling 0s (divides by a power of two), with
the leftmost bit depending on the sign.
• >>> (Unsigned right shift): Shifts bits right, filling 0s, with the leftmost bit always 0.

// Java Program to show the use of shift operators


import [Link].*;

class Geeks
{
public static void main(String[] args)
{
int a = 10;

// Using left shift


[Link]("a<<1 : " + (a << 1));

// Using right shift


[Link]("a>>1 : " + (a >> 1));
}
}
Output
a<<1 : 20
a>>1 : 5

9. instanceof Operator

The instanceof operator is used for type checking. It can be used to test if an object is an
instance of a class, a subclass, or an interface. The general format,

object instance of class/subclass/interface

Example: This example demonstrates the use of the instanceof operator to check if an
object is an instance of a specific class or interface

// Java program to show the use of Instance of operator


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

Person obj1 = new Person();


Person obj2 = new Boy();

// As obj1 is of type person, it is not an instance of Boy or interface


[Link]("obj1 instanceof Person: "
+ (obj1 instanceof Person));
[Link]("obj1 instanceof Boy: "
+ (obj1 instanceof Boy));
[Link]("obj1 instanceof MyInterface: "
+ (obj1 instanceof MyInterface));

// Since obj2 is of type boy, whose parent class is person and it implements the interface
Myinterface it is instance of all of these classes
[Link]("obj2 instanceof Person: "
+ (obj2 instanceof Person));
[Link]("obj2 instanceof Boy: "
+ (obj2 instanceof Boy));
[Link]("obj2 instanceof MyInterface: "
+ (obj2 instanceof MyInterface));
}
}

// Classes and Interfaces used are declared here


class Person {
}

class Boy extends Person implements MyInterface {


}

interface MyInterface {
}
Output
obj1 instanceof Person: true
obj1 instanceof Boy: false
obj1 instanceof MyInterface: false
obj2 instanceof Person: true
obj2 instanceof Boy: true
obj2 instanceof MyInterface: true

Typecasting in Java

In Java, typecasting is the process of converting one data type to another data type.

There are two types of Type Casting in Java:


• Widening Type Casting
• Narrow Type Casting

1. Widening Type Casting (Implicit Casting)

• A lower data type is transformed into a higher one by a process known as widening
type casting. Implicit type casting and casting down are some names for it.
• It occurs naturally. Since there is no chance of data loss, it is secure.
Widening Type casting occurs when:
• The target type must be larger than the source type.
• Both data types must be compatible with each other.

Syntax:larger_data_type variable_name = smaller_data_type_variable;

Example-
// Java program to demonstrate Widening TypeCasting
import [Link].*;
class Geeks {
public static void main(String[] args)
{
int i = 10;

// Wideing TypeCasting (Automatic Casting) from int to long


long l = i;

// Wideing TypeCasting (Automatic Casting) from int to double


double d = i;

[Link]("Integer: " + i);


[Link]("Long: " + l);
[Link]("Double: " + d);
}
}
Output
Integer: 10
Long: 10
Double: 10.0

2. Narrow Type Casting (Explicit Casting)

• The process of downsizing a bigger data type into a smaller one is known as
narrowing type casting. Casting up or explicit type casting are other names for it.
• It doesn't just happen by itself. If we don't explicitly do that, a compile-time error will
occur. Narrowing type casting is unsafe because data loss might happen due to the
lower data type's smaller range of permitted values.
• A cast operator assists in the process of explicit casting.

Syntax:smaller_data_type variable_name = (smaller_data_type)


larger_data_type_variable;

Example-
// Java Program to demonstrate Narrow type casting
import [Link].*;
class Geeks {
public static void main(String[] args)
{
double i = 100.245;

// Narrowing Type Casting


short j = (short)i;
int k = (int)i;

[Link]("Original Value before Casting"


+ i);
[Link]("After Type Casting to short "
+ j);
[Link]("After Type Casting to int "
+ k);
}
}
Output
Original Value before Casting100.245
After Type Casting to short 100
After Type Casting to int 100

Control Structure in Java


• In programming, we also face situations where we want a certain block of code to be
executed when some condition is fulfilled.
• A programming language uses control statements to control the flow of execution of a
program based on certain conditions.. Java provides several control statements to
manage program flow, including:
• Conditional Statements: if, if-else, nested-if, if-else-if
• Switch-Case: For multiple fixed-value checks
• Jump Statements: break, continue, return

Types of Decision-Making Statements


• if
• if-else
• nested-if
• if-else-if
• switch-case
• jump - break, continue, return

1. Java if Statement
The if statement is the most simple decision-making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e. if a certain condition is
true then a block of statements is executed otherwise not.
Syntax:
if(condition) {
// Statements to execute if condition is true
}

// Java program to illustrate if statement without curly block


import [Link].*;

class Geeks {
public static void main(String args[])
{
int i = 10;

if (i < 15)

// part of if block(immediate one statement after if condition)


[Link]("Inside If block");

// always executes as it is outside of if block


[Link]("10 is less than 15");

// This statement will be executed as if considers one statement by default again


// below statement is outside of if block
[Link]("I am Not in if");
}
}
Output
Inside If block
10 is less than 15
I am Not in if

2. Java if-else Statement


The if statement alone tells us that if a condition is true it will execute a block of statements
and if the condition is false it won't. But what if we want to do something else if the condition
is false? Here, comes the "else" statement. We can use the else statement with the if statement
to execute a block of code when the condition is false.

Syntax:
if(condition){
// Executes this block if condition is true
}else{
// Executes this block if condition is false
}

// Java program to demonstrate the working of if-else statement


import [Link].*;
class Geeks {
public static void main(String args[])
{
int i = 10;

if (i < 15)
[Link]("i is smaller than 15");
else
[Link]("i is greater than 15");
}
}
Output
i is smaller than 15

3. Java nested-if Statement


A nested if is an if statement that is the target of another if or else. Nested if statements mean
an if statement inside an if statement. Yes, java allows us to nest if statements within if
statements. i.e, we can place an if statement inside another if statement.

Syntax:
if (condition1) {
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

// Java program to demonstrate the working of nested-if statement

public class Test {


public static void main(String args[])
{
int x = 30;
int y = 10;

if( x == 30 )
{
if( y == 10 )
{
[Link]("X = 30 and Y = 10");
}
}
}
}
Output
X = 30 and Y = 10

4. Java if-else-if ladder


Here, a user can decide among multiple [Link] if statements are executed from the top
down. As soon as one of the conditions controlling the if is true, the statement associated with
that 'if' is executed, and the rest of the ladder is bypassed. If none of the conditions is true,
then the final else statement will be executed. There can be as many as 'else if' blocks
associated with one 'if' block but only one 'else' block is allowed with one 'if' block.

Syntax:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}

// Java program to demonstrate the working of if-else-if ladder


import [Link].*;

class Geeks {
public static void main(String args[])
{
int i = 20;

if (i == 10)
[Link]("i is 10");
else if (i == 15)
[Link]("i is 15");
else if (i == 20)
[Link]("i is 20");
else
[Link]("i is not present");
}
}
Output
i is 20

5. Java Switch Case


The switch statement is a multiway branch statement. It provides an easy way to dispatch
execution to different parts of code based on the value of the expression.
Syntax:
switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
// more cases...
default:
// code to be executed if no cases match
}

// Java program to demonstrates the working of switch statements


import [Link].*;

class Geeks {
public static void main(String[] args)
{
int num = 20;
switch (num) {
case 5:
[Link]("It is 5");
break;
case 10:
[Link]("It is 10");
break;
case 15:
[Link]("It is 15");
break;
case 20:
[Link]("It is 20");
break;
default:
[Link]("Not present");
}
}
}
Output
It is 20

6. jump Statements
Java supports three jump statements: break, continue and return. These three statements
transfer control to another part of the program.
• Break: In Java, a break is majorly used for:
o Terminate a sequence in a switch statement.
o To exit a loop.
o Used as a "civilized" form of goto.
• Continue: Sometimes it is useful to force an early iteration of a loop. That is, you
might want to continue running the loop but stop processing the remainder of the code
in its body for this particular iteration. This is, in effect, a goto just past the body of
the loop, to the loop's end. The continue statement performs such an action.

// Java program to demonstrates the use of continue in an if statement


public class Geeks
{
public static void main(String args[])
{
// For loop for iteration
for (int i = 0; i <=5; i++)
{
// Check condition for continue
// skip the execution of loop when i==3
if (i == 3)
continue;

[Link](i + " ");


}
}
}
Output
01245

Return Statement
The return statement is used to explicitly return from a method. That is, it causes program
control to transfer back to the caller of the method.

// Java program to demonstrate the use of return


import [Link].*;

public class Geeks {


public static void main(String args[])
{
boolean t = true;
[Link]("Before the return.");

if (t)
return;

// Compiler will bypass every statement after return


[Link]("This won't execute.");
}
}
Output
Before the return.

Java Loops

Loops in programming allow a set of instructions to run multiple times based on a condition.
In Java, there are three types of Loops, which are explained below:

1. for loop
The for loop is used when we know the number of iterations (we know how many times we
want to repeat a task). The for statement includes the initialization, condition, and
increment/decrement in one line.

Syntax:
for (initialization; condition; increment/decrement)
{
// code to be executed
}
• Initialization condition: Here, we initialize the variable in use. It marks the start of a
for loop. An already declared variable can be used or a variable can be declared, local
to loop only.
• Testing Condition: It is used for testing the exit condition for a loop. It must return a
boolean value. It is also an Entry Control Loop as the condition is checked prior to the
execution of the loop statements.
• Statement execution: Once the condition is evaluated to true, the statements in the
loop body are executed.
• Increment/ Decrement: It is used for updating the variable for next iteration.
• Loop termination: When the condition becomes false, the loop terminates marking
the end of its life cycle.

// Java program to demonstrates the working of for loop


import [Link].*;

class Geeks {
public static void main(String[] args)
{
for (int i = 0; i <= 10; i++) {
[Link](i + " ");
}
}
}

Output
0 1 2 3 4 5 6 7 8 9 10
[Link] Loop

A while loop is used when we want to check the condition before executing the loop body.

Syntax:
while (condition) {
// code to be executed
}

• While loop starts with the checking of Boolean condition. If it evaluated to true, then
the loop body statements are executed otherwise first statement following the loop is
executed. For this reason it is also called Entry control loop
• Normally the statements contain an update value for the variable being processed for
the next iteration.
• When the condition becomes false, the loop terminates which marks the end of its life
cycle.

// Java program to demonstrates the working of while loop


import [Link].*;

class Geeks {
public static void main(String[] args)
{
int i = 0;
while (i <= 10) {
[Link](i + " ");
i++;
}
}
}

Output
0 1 2 3 4 5 6 7 8 9 10

3. do-while Loop
The do-while loop ensures that the code block executes at least once before checking the
condition.

Syntax:
do {
// code to be executed
} while (condition);

• do while loop starts with the execution of the statement. There is no checking of any
condition for the first time.
• After the execution of the statements, and update of the variable value, the condition
is checked for true or false value. If it is evaluated to true, next iteration of loop starts.
• When the condition becomes false, the loop terminates which marks the end of its life
cycle.
• It is important to note that the do-while loop will execute its statements atleast once
before any condition is checked, and therefore is an example of exit control loop.

// Java program to demonstrates the working of do-while loop


import [Link].*;

class Geeks {
public static void main(String[] args)
{
int i = 0;
do {
[Link](i + " ");
i++;
} while (i <= 10);
}
}

Output
0 1 2 3 4 5 6 7 8 9 10

Arrays in Java
In Java, an array is an important linear data structure that allows us to store multiple values of
the same type.
• Arrays in Java are objects, like all other objects in Java, arrays implicitly inherit from
the [Link] class. This allows you to invoke methods defined in Object (such
as toString(), equals() and hashCode()).
• Arrays have a built-in length property, which provides the number of elements in the
array

public class Geeks {


public static void main(String[] args) {

// initializing array
int[] arr = { 40,55,63,17,22,68,89,97,89};

// size of array
int n = [Link];

// traversing array
for (int i = 0; i < n; i++)
[Link](arr[i] + " ");
}
}

Output
40 55 63 17 22 68 89 97 89

Key features of Arrays


• Store Primitives and Objects: Java arrays can hold both primitive types (like int,
char, boolean, etc.) and objects (like String, Integer, etc.)
• Contiguous Memory Allocation When we use arrays of primitive types, the elements
are stored in contiguous locations. For non primitive types, references of items are
stored at contiguous locations.
• Zero-based Indexing: The first element of the array is at index 0.
• Fixed Length: After creating an array, its size is fixed; we can not change it.

Basics Operation on Arrays in Java

1. Declaring an Array
The general form of array declaration is
// Method 1:
int arr[];
// Method 2:
int[] arr;

2. Initialization an Array in Java


When an array is declared, only a reference of an array is created. We use new to allocate an
array of given size.

int arr[] = new int[size];


• Array Declaration is generally static, but if the size in not defined, the Array is
Dynamically sized.
• Memory for arrays is always dynamically allocated (on heap segment) in Java. This is
different from C/C++ where memory can either be statically allocated or dynamically
allocated.
• The elements in the array allocated by new will automatically be initialized to zero
(for numeric types), false (for boolean) or null (for reference types).

Array Literal in Java


In a situation where the size of the array and variables of the array are already known, array
literals can be used.
// Declaring array literal
int[] arr = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
• The length of this array determines the length of the created array.
• There is no need to write the new int[] part in the latest versions of Java.
3. Change an Array Element
To change an element, assign a new value to a specific index. The index begins with 0 and
ends at (total array size)-1.

// Changing the first element to 90


arr[0] = 90;

4. Array Length
We can get the length of an array using the length property:
// Getting the length of the array
int n = [Link];

5. Accessing and Updating All Array Elements


• All the elements of array can be accessed using Java for Loop.
• Each element in the array is accessed via its index.

Arrays of Objects in Java


An array of objects is created like an array of primitive-type data items

Example: Here we are taking a student class and creating an array of Student with five
Student objects stored in the array. The Student objects have to be instantiated using the
constructor of the Student class and their references should be assigned to the array elements.

class Student {
public int roll_no;
public String name;
Student(int roll_no, String name){
this.roll_no = roll_no;
[Link] = name;
}
}

public class Geeks {


public static void main(String[] args){

// declares an Array of Student


Student[] arr;

// allocating memory for 5 objects of type Student.


arr = new Student[5];

// initialize the elements of the array


arr[0] = new Student(1, "aman");
arr[1] = new Student(2, "vaibhav");
arr[2] = new Student(3, "shikar");
arr[3] = new Student(4, "dharmesh");
arr[4] = new Student(5, "mohit");

// accessing the elements of the specified array


for (int i = 0; i < [Link]; i++)
[Link]("Element at " + i + " : { "
+ arr[i].roll_no + " "
+ arr[i].name+" }");
}
}

Output
Element at 0 : { 1 aman }
Element at 1 : { 2 vaibhav }
Element at 2 : { 3 shikar }
Element at 3 : { 4 dharmesh }
Element at 4 : { 5 mohit }

Passing Arrays to Methods


Like variables, we can also pass arrays to methods. For example, the below program passes
the array to method sum to calculate the sum of the array's values.
Example:
public class Geeks {
// Driver method
public static void main(String args[])
{
int arr[] = { 3, 1, 2, 5, 4 };

// passing array to method m1


sum(arr);
}

public static void sum(int[] arr)


{
// getting sum of array values
int sum = 0;

for (int i = 0; i < [Link]; i++)


sum += arr[i];

[Link]("sum of array values : " + sum);


}
}

Output
sum of array values : 15

Explanation
• This Java program demonstrates how to pass an array to a method.
• An integer array arr is declared and initialized in the main method.
• The sum() method is called with arr as an argument.
• Inside the sum() method, all array elements are added using a for loop.
• The final sum is then printed to the console.

Returning Arrays from Methods


As usual, a method can also return an array. For example, the below program returns an array
from method m1.
Example:
class Geeks {
// Driver method
public static void main(String args[])
{
int arr[] = m1();

for (int i = 0; i < [Link]; i++)


[Link](arr[i] + " ");
}

public static int[] m1()


{
// returning array
return new int[] { 1, 2, 3 };
}
}
Output
123

Types of Arrays

1. Fixed Size Array


2. 1-Dimensional Array
3. Multi-Dimensional Array

1. Fixed Sized Arrays:


We cannot alter or update the size of this array. Here only a fixed size (i,e. the size that is
mentioned in square brackets []) of memory will be allocated for storage. In case, we don't
know the size of the array then if we declare a larger size and store a lesser number of
elements will result in a wastage of memory or we declare a lesser size than the number of
elements then we won't get enough memory to store all the elements. In such cases, static
memory allocation is not preferred.

// Fixed sized array examples


int[] arr1 = new int [5];

// Another way (Array creation and initialization both)


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

[Link]-dimensional array (1-D arrays):


You can imagine a 1d array as a row, where elements are stored one after another.

Syntax for Declaration of Single Dimensional Array


data_type array_name[array_size];

where,
• data_type: is a type of data of each array block.
• array_name: is the name of the array using which we can refer to it.
• array_size: is the number of blocks of memory array going to have.

For Example
int nums[5];
[Link] Multi-Dimensional Arrays
Multidimensional arrays are used to store the data in rows and columns, where each row can
represent another individual array are multidimensional array.

// Java Program to Demonstrate Multi Dimensional Array


import [Link].*;

public class Geeks


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

// Multidimensional array declaration


int[][] arr;

// Initializing the size of row and column respectively


arr = new int[1][3];

// Initializing the values


arr[0][0] = 3;
arr[0][1] = 5;
arr[0][2] = 7;

// Display the values using index


[Link]("arr[0][0] = " + arr[0][0]);
[Link]("arr[0][1] = " + arr[0][1]);
[Link]("arr[0][2] = " + arr[0][2]);
}
}

Output
arr[0][0] = 3
arr[0][1] = 5
arr[0][2] = 7

Syntax for Multi-Dimensional Array


data_type[1st dimension][2nd dimension][]..[Nth dimension] array_name = new
data_type[size1][size2]....[sizeN];

Parameters:
• data_type: Type of data to be stored in the array. For example: int, char, etc.
• dimension: The dimension of the array created. For example: 1D, 2D, etc.
• array_name: Name of the array
• size1, size2, ..., sizeN: Sizes of the dimensions respectively.
Examples:
// Two dimensional array:
int[][] arr2d = new int[3][5];
// Three dimensional array:
int[][][] arr3d = new int[3][5][7];

Size of Multidimensional Arrays: The size of the multidimensional array can be calculated
by multiplying the size of all dimensions of array foe example arrd have the dimensions 3*5
= 15
For example: array int[][][] x = new int[3][5][7] can store a total of (3*5*7) = 105
elements.
Java User Input
The most common way to take user input in Java is using the Scanner class. It is a part
of [Link] package. The scanner class can handle input from different places, like as we are
typing at the console, reading from a file, or working with data streams. This class was
introduced in Java 5. Before that, we used the BufferedReader class (introduced in Java
1.1).

Scanner Class in Java


In Java, the Scanner class is present in the [Link] package is used to obtain input for
primitive types like int, double, etc., and strings. We can use this class to read input from a
user or a file. In this article, we cover how to take different input values from the user using
the Scanner class.

Example 1: Taking input from the user using the Scanner class and displaying the output.

// Java program to demonstrate the use of Scanner class to take input from user
import [Link];

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

Scanner sc = new Scanner([Link]);


[Link]("Enter your name:");
String name = [Link]();

[Link]("Hello, " + name + " Welcome to the GeeksforGeeks.");

}
Output:
Explanation: In the above code example, we use the nextLine() of Scanner class to read the
line value which is entered by the user and print it in the console.

Steps To Use Scanner Class to Take Input

Step 1: First, import the [Link] package in top of the program file Without
importing this package, we cannot use the Scanner class. either we can import
the [Link].* by importing this package we can use all the classes present in the util
package.
import [Link]
public class Geeks{
public static void main(String [] args){
}
}

Step 2: Create the object of the Scanner class.


Scanner sc = new Scanner ([Link]);
Here "sc" is an object of the Scanner class. We can give it different names for our ease such
as in, var or obj etc. Using this object we can use the methods of the Scanner class.

Step 3: Create a variable and using scanner class object call the corresponding method to
take the input value.
int age = [Link]();

Java Scanner Input Types


The scanner class helps take the standard input stream in Java. So, we need some methods to
extract data from the stream. The methods used for extracting data are mentioned below:

Method Description

nextBoolean() Used for reading Boolean value

nextByte() Used for reading Byte value

nextDouble() Used for reading Double value

nextFloat() Used for reading Float value

nextInt() Used for reading Int value

nextLine() Used for reading Line value


Method Description

nextLong() Used for reading Long value

nextShort() Used for reading Short value

Example 2: Taking different inputs using Scanner class method such as nextInt(),
nextDouble and nextLine(), etc.
// Java program to read data of various types using Scanner class
import [Link];

// Driver Class
public class Geeks
{
// main function
public static void main(String[] args) {

// Declare the object and initialize with predefined standard input object
Scanner sc = new Scanner([Link]);

[Link]("Enter your name:");

// String input
String name = [Link]();

[Link]("Enter your gender (M/F): ");

// Character input
char gender = [Link]().charAt(0);

// Numerical data input byte, short and float can be read

[Link]("Enter your age: ");


int age = [Link]();

[Link]("Enter your cgpa: ");


double cgpa = [Link]();

// Print the values to check if the input was correctly obtained.


[Link]("Name: " + name);
[Link]("Gender: " + gender);
[Link]("Age: " + age);

[Link]("CGPA: " + cgpa);


}
}
Output:

Explanation: In the above code example, we use the Scanner class to take different types of
input values from user and print it in the console.

Sometimes, we have to check if the next value we read is of a certain type or if the input has
ended (EOF marker encountered). Then, we check if the scanner's input is of the type we
want with the help of hasNextDataType() functions where DataType is the type we are
interested in. The function returns true if the scanner has a token of that type, otherwise false.
For example, in the below code, we have used hasNextInt(). To check for a string, we use
hasNextLine(). Similarly, to check for a single character, we use hasNext().charAt(0).
• hasNextInt(): This method is used to check if the token is an integer.
• hasNextLine(): This method is used to check if there is an input in next line.

Example 3: Using the hasNext() and hasNextInt() method to take input from user without
specifying the limit of input values.

// Java program to read some values using Scanne class and print their mean.
import [Link];

public class Geeks


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

// Declare an object and initialize with predefined standard input object


Scanner sc = new Scanner([Link]);

// Initialize sum and count of input elements


int sum = 0, count = 0;

[Link]("Enter integers to calculate the mean (type 'done' to finish):");


// Loop to read input until "done" is entered
while ([Link]()) {
if ([Link]()) {

// Read an int value


int num = [Link]();
sum += num;
count++;
} else {
String input = [Link]();
if ([Link]("done")) {
break;
} else {
[Link]("Invalid input. Please enter an integer or type 'done' to
finish.");
}
}
}

// Calculate and display the mean


if (count > 0) {
// Use double for precise mean calculation

double mean = (double) sum / count;


[Link]("Mean: " + mean);
} else {
[Link]("No integers were input. Mean cannot be calculated.");
}

}
}
Output:

Explanation: In the above code example, we use the hasNext() and hasNextInt() method to
take the input values from user and then user give the input value they can specify that the
input value is ended and they can type "done" to find the mean value of given input.
Important Points:
• To create an object of Scanner class, we usually pass the predefined object [Link],
which represents the standard input stream. We may pass an object of class File if we
want to read input from a file.
• To read numerical values of a certain data type XYZ, the function to use is
nextXYZ(). For example, to read a value of type short, we can use nextShort()
• To read strings, we use nextLine().
• To read a single character, we use next().charAt(0). next() function returns the next
token/word in the input as a string and charAt(0) function returns the first character in
that string.
• Always close the Scanner object after use to avoid resource leaks.
• The Scanner class reads an entire line and divides the line into tokens. Tokens are
small elements that have some meaning to the Java compiler.
• For example, Suppose there is an input string: "How are you"
In this case, the scanner object will read the entire line and divides the string into
tokens: "How", "are" and "you". The object then iterates over each token and reads
each token using its different methods.

[Link] Class in Java

The BufferedReader class of Java is used to read the stream of characters from the specified
source (character-input stream). The constructor of this class accepts an InputStream object as
a parameter.
This class provides a method named read() and readLine() which reads and returns the
character and next line from the source (respectively) and returns them.
• Instantiate an InputStreamReader class bypassing your InputStream object as a
parameter.
• Then, create a BufferedReader, bypassing the above obtained InputStreamReader
object as a parameter.
• Now, read data from the current reader as String using the readLine() or read()
method.
Example
The following Java program demonstrates how to read integer data from the user using
the BufferedReader class.

import [Link];
import [Link];
import [Link];
class Employee{
String name;
int id;
int age;
Employee(String name, int age, int id){
[Link] = name;
[Link] = age;
[Link] = id;
}
public void displayDetails(){
[Link]("Name: "+[Link]);
[Link]("Age: "+[Link]);
[Link]("Id: "+[Link]);
}
}
public class ReadData {
public static void main(String args[]) throws IOException {
BufferedReader reader =new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Enter your age: ");
int age = [Link]([Link]());
[Link]("Enter your Id: ");
int id = [Link]([Link]());
Employee std = new Employee(name, age, id);
[Link]();
}
}

Output
Enter your name:
Krishna
Enter your age:
25
Enter your Id:
1233
Name: Krishna
Age: 25
Id: 1233

Command Line Arguments in Java

Java command-line argument is an argument, i.e., passed at the time of running the Java
program. Command-line arguments passed from the console can be received by the Java
program and used as input.

Example:
java Geeks Hello World

Note: Here, the words Hello and World are the command-line arguments. JVM will collect
these words and will pass these arguments to the main method as an array of strings called
args. The JVM passes these arguments to the program inside args[0] and args[1].
Example: In this example, we are going to print a simple argument in the command line.

// Java Program to Illustrate First Argument


class GFG{

public static void main(String[] args) {

// Printing the first argument


[Link](args[0]);
}
}

Output:

Explanation:
• Running java GFG GeeksForGeeks prints GeeksForGeeks because the argument is
passed to main(String[] args).
• If no arguments are given (e.g., java GFG), it throws
ArrayIndexOutOfBoundsException since args is empty.

Why Use Command Line Arguments?


• It is used because it allows us to provide input at runtime without modifying the
whole program.
• It helps to run programs automatically by giving them the needed information from
outside.

Working of Command-Line Arguments


• Command-line arguments in Java are space-separated values passed to the
main(String[] args) method.
• JVM wraps them into the args[] array, where each value is stored as a string (e.g.,
args[0], args[1], etc.).
• The number of arguments can be checked using [Link].

Example: Display Command-Line Arguments Passed to a Java Program


To compile and run a Java program in the command prompt, follow the steps written below.
• Save the program as [Link]
• Open the command prompt window and compile the program- javac [Link]
• After a successful compilation of the program, run the following command by writing
the arguments- java Hello
• For example - java Hello Geeks at GeeksforGeeks
• Press Enter and you will get the desired output.

class Geeks {

// Main driver method


public static void main(String[] args)
{
// Checking if length of args array is greater than 0
if ([Link] > 0) {

// Print statements
[Link]("The command line"
+ " arguments are:");

// Iterating the args array using for each loop


for (String val : args)

[Link](val);
}
else

[Link]("No command line "


+ "arguments found.");
}
}
Output:

You might also like