JAVA PROGRAMMING UNIT I

Download as pdf or txt
Download as pdf or txt
You are on page 1of 71

JAVA PROGRAMMING

UNIT I:

OOPs Concepts in Java


In this guide, you will learn the OOPs Concepts in Java. Object-oriented programming
System(OOPs) is a programming concept that is based on “objects”. The primary purpose of
object-oriented programming is to increase the readability, flexibility and maintainability of
programs.
Object oriented programming brings data and its behaviour together in a single entity
called objects. It makes the programming easier to understand. We will cover all the features of
OOPs such as inheritance, polymorphism, abstraction, encapsulation in detail so that you won’t
face any difficultly understanding OOPs in Java.
Popular programming languages that supports object oriented programming
are: Java, C++, Python, C#, Perl, JavaScript, Ruby, Smalltalk etc.

What is OOPs Concepts in Java


OOPs concepts includes following Object oriented programming concepts:
 Object
 Class
 Abstraction
 Encapsulation
 Inheritance
 Polymorphism

1. Object
An object can be represented as an entity that has state and behaviour. For example: A car
is an object that has states such as color, model, price and behaviour such as speed, start, gear
change, stop etc.

Let’s understand the difference between state and behaviour. The state of an object is a
data item that can be represented in value such as price of car, color, consider them as variables in
programming. The behaviour is like a method of the class, it is a group of actions that together
can perform a task. For example, gear change is a behaviour as it involves multiple subtasks such
as speed control, clutch, gear handle movement.
Let’s take few more examples of Objects:
Examples of states and behaviours
Example 1:
Class: House
State: address, color, area
Behaviour: Open door, close door
Let’s see how can we write these state and behaviours in a java program. States can be
represented as instance variables and behaviours as methods of the class.
class House {
String address;
String color;
double area;
void openDoor() {
//Write code here
}
void closeDoor() {
//Write code here
}
...
...}
Example 2:
Class: Car
State: color, brand, weight, model
Behaviour: Break, Accelerate, Slow Down, Gear change.
Note: As we have seen in the above example, the states and behaviours of an object can be
represented by variables and methods in the class.
2. Class
A class can be considered as a blueprint which you can use to create as many objects as
you like. For example, here we have a class Website that has two data members. This is just a
blueprint, it does not represent any website, however using this we can create Website objects that
represents the websites. We have created two objects, while creating objects we provided separate
properties to the objects using constructor.

public class Website {


//fields (or instance variable)
String webName;
int webAge;

// constructor
Website(String name, int age){
this.webName = name;
this.webAge = age;
}
public static void main(String args[]){
//Creating objects
Website obj1 = new Website("beginnersbook", 11);
Website obj2 = new Website("google", 28);

//Accessing object data through reference


System.out.println(obj1.webName+" "+obj1.webAge);
System.out.println(obj2.webName+" "+obj2.webAge);
}}
Output:
beginnersbook 11
google 28
3. Abstraction
Abstraction is a process where you show only “relevant” data and “hide” unnecessary details of
an object from the user. For example, when you login to your bank account online, you enter your
user_id and password and press login, what happens when you press login, how the input data
sent to server, how it gets verified is all abstracted away from the you. Read more about it
here: Abstraction in Java.
Abstract Class Example:
Here we have an abstract class Animal that has an abstract method animalSound(), since the
animal sound differs from one animal to another, there is no point in giving the implementation to
this method as every child class must override this method to give its own implementation details.
That’s why we made it abstract.
Now each animal must have a sound, by making this method abstract we made it compulsory to
the child class to give implementation details to this method. This way we ensures that every
animal has a sound.
//abstract classabstract class Animal{
//abstract method
public abstract void animalSound();}public class Dog extends Animal{

public void animalSound(){


System.out.println("Woof");
}
public static void main(String args[]){
Animal obj = new Dog();
obj.animalSound();
}}
Output:
Woof
4. Encapsulation
Encapsulation simply means binding object state(fields) and behaviour(methods) together. If you
are creating class, you are doing encapsulation.
Example
1) Make the instance variables private so that they cannot be accessed directly from outside the
class. You can only set and get values of these variables through the methods of the class.
2) Have getter and setter methods in the class to set and get the values of the fields.
class EmployeeCount{
private int numOfEmployees = 0;
public void setNoOfEmployees (int count)
{
numOfEmployees = count;
}
public double getNoOfEmployees ()
{
return numOfEmployees;
}}public class EncapsulationExample{
public static void main(String args[])
{
EmployeeCount obj = new EmployeeCount ();
obj.setNoOfEmployees(5613);
System.out.println("No Of Employees: "+(int)obj.getNoOfEmployees());
}}
Output:
No Of Employees: 5613
The class EncapsulationExample that is using the Object of class EmployeeCount will not able to
get the NoOfEmployees directly. It has to use the setter and getter methods of the same class to
set and get the value.
What is the benefit of using encapsulation in java programming?
Well, at some point of time, if you want to change the implementation details of the class
EmployeeCount, you can freely do so without affecting the classes that are using it.
5. Inheritance
The process by which one class acquires the properties and functionalities of another class is
called inheritance. Inheritance provides the idea of reusability of code and each sub class defines
only those features that are unique to it, rest of the features can be inherited from the parent class.
1. Inheritance is a process of defining a new class based on an existing class by extending its
common data members and methods.
2. Inheritance allows us to reuse of code, it improves reusability in your java application.
3. The parent class is called the base class or super class. The child class that extends the
base class is called the derived class or sub class or child class.
Note: The biggest advantage of Inheritance is that the code in base class need not be rewritten in
the child class.
The variables and methods of the base class can be used in the child class as well.
Syntax: Inheritance in Java
To inherit a class we use extends keyword. Here class A is child class and class B is parent class.
class A extends B{}

Generalization and Specialization:


In order to implement the concept of inheritance in an OOPs, one has to first identify the
similarities among different classes so as to come up with the base class.
This process of identifying the similarities among different classes is called Generalization.
Generalization is the process of extracting shared characteristics from two or more classes, and
combining them into a generalized superclass. Shared characteristics can be attributes or methods.
In contrast to generalization, specialization means creating new subclasses from an existing class.
If it turns out that certain attributes or methods only apply to some of the objects of the class, a
subclass can be created.
Inheritance Example
In this example, we have a parent class Teacher and a child class MathTeacher. In
the MathTeacher class we need not to write the same code which is already present in the present
class. Here we have college name, designation and does() method that is common for all the
teachers, thus MathTeacher class does not need to write this code, the common data members and
methods can inherited from the Teacher class.
class Teacher {
String designation = "Teacher";
String college = "Beginnersbook";
void does(){
System.out.println("Teaching");
}}public class MathTeacher extends Teacher{
String mainSubject = "Maths";
public static void main(String args[]){
MathTeacher obj = new MathTeacher();
System.out.println(obj.college);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.does();
}}
Output:
BeginnersbookTeacherMathsTeaching
Note: Multi-level inheritance is allowed in Java but multiple inheritance is not allowed as
shown in the following diagram.

Types of Inheritance:
Single Inheritance: refers to a child and parent class relationship where a class extends the
another class.
Multilevel inheritance: refers to a child and parent class relationship where a class extends the
child class. For example class A extends class B and class B extends class C.
Hierarchical inheritance: refers to a child and parent class relationship where more than one
classes extends the same class. For example, class B extends class A and class C extends class A.
Multiple Inheritance: refers to the concept of one class extending more than one classes, which
means a child class has two parent classes. Java doesn’t support multiple inheritance, read more
about it here.
Most of the new OO languages like Small Talk, Java, C# do not support Multiple
inheritance. Multiple Inheritance is supported in C++.
6. Polymorphism
Polymorphism is a object oriented programming feature that allows us to perform a single action
in different ways. For example, let’s say we have a class Animal that has a method animalSound(),
here we cannot give implementation to this method as we do not know which Animal class would
extend Animal class. So, we make this method abstract like this:
public abstract class Animal{
...
public abstract void animalSound();}
Now suppose we have two Animal classes Dog and Lion that extends Animal class. We can
provide the implementation detail there.
public class Lion extends Animal{...
@Override
public void animalSound(){
System.out.println("Roar");
}}
and
public class Dog extends Animal{...
@Override
public void animalSound(){
System.out.println("Woof");
}}
As you can see that although we had the common action for all subclasses animalSound() but
there were different ways to do the same action. This is a perfect example of polymorphism
(feature that allows us to perform a single action in different ways).
Types of Polymorphism
1) Static Polymorphism
2) Dynamic Polymorphism
Static Polymorphism:
Polymorphism that is resolved during compiler time is known as static polymorphism. Method
overloading can be considered as static polymorphism example.
Method Overloading: This allows us to have more than one methods with same name in a class
that differs in signature.
class DisplayOverloading{
public void disp(char c)
{
System.out.println(c);
}
public void disp(char c, int num)
{
System.out.println(c + " "+num);
}}public class ExampleOverloading{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}}
Output:
a
a 10
When I say method signature I am not talking about return type of the method, for
example if two methods have same name, same parameters and have different
return type, then this is not a valid method overloading example. This will throw
compilation error.
Dynamic Polymorphism
It is also known as Dynamic Method Dispatch. Dynamic polymorphism is a process in
which a call to an overridden method is resolved at runtime rather, thats why it is called runtime
polymorphism.
Example
class Animal{
public void animalSound(){
System.out.println("Default Sound");
}}public class Dog extends Animal{

public void animalSound(){


System.out.println("Woof");
}
public static void main(String args[]){
Animal obj = new Dog();
obj.animalSound();
}}
Output:
Woof
Since both the classes, child class and parent class have the same method animalSound. Which of
the method will be called is determined at runtime by JVM.
Few more overriding examples:
Animal obj = new Animal();
obj.animalSound();// This would call the Animal class method
Dog obj = new Dog();
obj.animalSound();// This would call the Dog class method
Animal obj = new Dog();
obj.animalSound();// This would call the Dog class method
History of Java
Java programming language was originally developed by Sun Microsystems which was
initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java
platform (Java 1.0 [J2SE]). History of even naming of the Java is very interesting. It went under
many names.
Java Name History
GreenTalk
James Gosling was leading a team named as 'Green' team. Target of this team was to
create a new project which can. Initially C++ was the original choice to develop the project.
James Gosling wanted to enhance C++ to achieve the target but due to high memory usage, that
idea was rejected and team started with a new language initially named as GreenTalk. The file
extension used as .gt. Later this language was termed as Oak and finally to Java.
Oak
James Gosling renamed language to Oak. There was an Oak tree in front of his office.
James Gosling used this name as Oak represents solidarity and Oak tree is the national tree of
multiple countries like USA, France, Romania etc. But Oak technologies already had Oak as a
trademark and James team had to brainstrom another title for the language.
Finally Java
Team put multiple names like DNA, Silk, Ruby and Java. Java was finalized by the team.
James Gosling tabled Java title based on type of espresso coffee bean. Java is an island in
Indonesia where new coffee was discovered termed as Java coffee. As per James Gosling, Java
was among the top choice along with Silk. Finally Java was selected as it was quite unique and
represented the essence of being dynamic,revolutionary and fun to say.
Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run
Anywhere (WORA), providing no-cost run-times on popular platforms.
On 13 November, 2006, Sun released much of Java as free and open source software under the
terms of the GNU General Public License (GPL).
On 8 May, 2007, Sun finished the process, making all of Java's core code free and open-source,
aside from a small portion of code to which Sun did not hold the copyright.
The latest release of the Java Standard Edition is Java SE 21. With the advancement of Java and
its widespread popularity, multiple configurations were built to suit various types of platforms.
For example: J2EE for Enterprise Applications, J2ME for Mobile Applications.

Learn Java in-depth with real-world projects through our Java certification course. Enroll and
become a certified expert to boost your career.

Java Versions History


Over the period of nearly 30 years, Java has seen many minor and major versions. Following is a
brief explaination of versions of java till date.
Sr.No. Version Date Description

JDK
1 1995 Initial Draft version
Beta

23
2 JDK 1.0 Jan A stable variant JDK 1.0.2 was termed as JDK 1
1996

19
Major features like JavaBeans, RMI, JDBC, inner
3 JDK 1.1 Feb
classes were added in this release.
1997

8 Swing, JIT Compiler, Java


4 JDK 1.2 Dec Modules, Collections were introduced to JAVA and
1998 this release was a great success.

8
HotSpot JVM, JNDI, JPDA, JavaSound and support
5 JDK 1.3 May
for Synthetic proxy classes were added.
2000

Image I/O API to create/read JPEG/PNG image were


6 Feb added. Integrated XML parser and XSLT processor
6 JDK 1.4
2002 (JAXP) and Preferences API were other important
updates.

JDK 1.5 30
Various new features were added to the language like
7 or J2SE Sep
foreach, var-args, generics etc.
5 2004

11 1. notation was dropped to SE and upgrades done to


JAVA
8 Dec JAXB 2.0, JSR 269 support and JDBC 4.0 support
SE 6
2006 added.

9 JAVA 7 Jul Support for dynamic languages added to JVM. Another


SE 7 2011 enhancements included string in switch case,
compressed 64 bit pointers etc.

18 Support for functional programming added. Lambda


JAVA
10 Mar expressions, streams, default methods, new date-
SE 8
2014 time APIs introduced.

21
JAVA Module system introduced which can be applied to
11 Sep
SE 9 JVM platform.
2017

Unicode language-tag extensions added. Root


20
JAVA certificates, threadlocal handshakes, support for heap
12 Mar
SE 10 allocation on alternate memory devices etc were
2018
introduced.

Dynamic class-file constants, Epsilon a no-op garbage


JAVA 5 Sep
13 collector, local-variable support in lambda parameters,
SE 11 2018
Low-overhead heap profiling support added.

19 Experimental Garbage Collector,Shenandoah: A Low-


JAVA
14 Mar Pause-Time Garbage Collector, Microbenchmark
SE 12
2019 Suite, JVM Constants API added.

17
JAVA Feature added - Text Blocks (Multiline strings),
15 Sep
SE 13 Enhanced Thread-local handshakes.
2019

17 Feature added - Records, a new class type for


JAVA
16 Mar modelling, Pattern Matching for instanceof,
SE 14
2020 Intuitive NullPointerException handling.

15
JAVA Feature added - Sealed Classes, Hidden Classes,
17 Sep
SE 15 Foreign Function and Memory API (Incubator).
2020

16 Feature added as preview - Records, Pattern Matching


JAVA
18 Mar for switch, Unix Domain Socket Channel (Incubator)
SE 16
2021 etc.

Feature added as finalized - Sealed Classes, Pattern


14
JAVA Matching for instanceof, Strong encapsulation of JDK
19 Sep
SE 17 internals by default. New macOS rendering pipeline
2021
etc.

Feature added - UTF-8 by Default, Code Snippets in


22
JAVA Java API Documentation, Vector API (Third
20 Mar
SE 18 incubator), Foreign Function, Memory API (Second
2022
Incubator) etc.

20
JAVA Feature added - Record pattern, Vector API (Fourth
21 Sep
SE 19 incubator), Structured Concurrency (Incubator) etc.
2022

JAVA 21 Feature added - Scoped Values (Incubator), Record


22
SE 20 Mar Patterns (Second Preview), Pattern Matching for
2023 switch (Fourth Preview),Foreign Function & Memory
API (Second Preview) etc.

19 Feature added - String Templates (Preview),


JAVA
22 Sep Sequenced Collections, Generational ZGC, Record
SE 21
2023 Patterns, Pattern Matching for switch etc.

Feature added - Region Pinning for G1 garbage


19 collector, foreign functions and memory APIs , multi-
Java SE
23 Mar file source code programs support, string templates,
22
2024 vector apis (seventh incubator), unnamed variables,
patterns, stream gatherers (first preview) etc.

Feature added - Primitive types in patterns, class file


17
Java SE APIs, vector APIs (Eighth incubator), stream gatherers
24 Sep
23 (second preview), ZDC, generation mode by default
2024
etc.
Buzzwords of Java

The inventors of Java wanted to design a language which could offer solutions to some of
the problems encountered in modern programming. They wanted the language to be not only
reliable, portable and distributed but also simple, compact and interactive. The authors of Java
have written an influential White Paper that explains the features of java by all of the following
buzzwords:

 Simple
 Object Oriented
 Platform Independent
 Distributed
 Robust
 Secure
 Architecture Neutral
 Portable
 Interpreted
 High Performance
 Multithreaded
 Dynamic

Simple
Java is an object-oriented programming language with syntax and keywords almost
identical to C++. When developing Java, its creators took all of the good features of the existing
object-oriented programming languages such as C++, Ada, and Smalltalk, and removed most of
their flaws and peculiarities. There are a lot of aspects of the Java language that are consistent and
make sense, thereby making it easier to learn.
If you are familiar with C++ you would know about clumsy features of C++: header files,
pointer arithmetic (or even pointer syntax), structures, unions, operator overloading, virtual base
classes, and so on. All these clumsy features are cleaned-up in java making it easier to learn.

Object Oriented
What is object oriented programming (OOP) language?
Any programming language if supports Encapsulation, Abstraction, Inheritance,
Polymorphism then that language is an object oriented programming language. E.g. java, C++
Define OOP concepts?
If you have just started learning java, definitely it is very hard to understand the Object
oriented programming (OOP) concepts. Once you learn java completely then you will understand
these concepts. Many java professional who are using these concepts in their daily life will fail to
define OOP (Object Oriented Programing) concepts. Below are the definitions of OOP concepts
which will surely help you when you are attending the java interviews.

Encapsulation: It is the Process of binding the data and methods together into a single unit.
Example: Binding private variables with setter and getter methods.
Abstraction: Showing Essential properties and methods of an object by hiding internal things is
called as Abstraction. Abstraction is possible if and only if there is encapsulation. Example: Java
is an abstraction layer over binary language. Hibernate is an abstraction layer over JDBC
Inheritance: Inheriting the properties and methods of one class (super class) into another class
(sub class) using IS a relationship. Example: Ferrari class inherits the features of Car class. Puppy
class inherit the features of Dog class, Dog class inherit the features of Animal class
Polymorphism: One form behaving differently in different situations is called polymorphism.
Animal class behaving differently for different objects like Dog, Cat etc...
Platform independent
Java can run in any system line windows, Linux, mac etc. You no need to write separate program
for individual platform/OS. Program written in Windows platform can run in Linux platform.
Output of java compiler (javac.exe in windows) is a bytecode (.calss file), but not native machine
code. This bytecode is interpreted by virtual machine (not by real computer) as real computer
interprets .exe files in C/C++. Such a virtual machine is called as Java Virtual Machine (JVM).
Translating java program into Byte code makes it much easier to run a program in wide variety of
platforms/Environments, because only JVM need to be implemented. Once bytecode is ready, we
can run it in windows, Linux, calculator, mobile, watch etc.., but one thing is all environments
require just JVM. Details of JVM differ from environment to environment. (Platform to Platform)

Distributed
 A technology is said to be distributed if it's business objects are geographically dispersed into
different locations and still communicating one another.

 Networking capabilities of java are strong and easy to use.

 Onerous tasks like opening a socket connection are simple in Java.

 An elegant mechanism, called servlets, makes server-side processing in Java extremely


efficient. Many popular web servers support servlets.
Robust
Programming language is robust when it is reliable and strong. Below capabilities make
java robust:

 Java has a garbage collector which will automatically clean up unused objects and memory.
No need to chase memory corruption.

 In java you do not use pointers to access strings, arrays, objects, even files. Nor do you need
to worry about memory allocation for them.

 Java has exception handling mechanism which is very useful in handling both compile and
run time errors. Without handling errors and exceptions, entire application would fail. With
exception handling it just stops the current flows even that are when failed, but rest all flows
still runs.

Secure
Java team has said that they will have a “zero tolerance” for security bugs and will
immediately go to work on fixing any bugs found. Java program will be first compiled to byte
code. This byte code will then be interpreted by Java Virtual Machine (JVM). JVM makes java
secure with below factors:

 JVM will not overrun the runtime stack.


 JVM will not corrupt memory outside its own process space.
 JVM will not read or write to local files when invoked through a security-conscious class
loader.
Architecture Neutral
The compiler generates architecture-neutral bytecode instructions which have nothing to
do with particular computer architecture. These bytecode instructions can be run by only JVM.
JVM is not same for platforms and architectures. Java will provide you different JVMs for
different platforms and architectures. So you just have to install different JVMs. A bytecode once
ready can be run by any JVM.
A program written in 32 bit operating system can be run by JVM in 64 bit operating system.
Portable
In C/C++ data size varies from platform to platform. For example integer can be a 16-bit
integer, a 32-bit integer, or any other size that the compiler vendor likes. In java has a fixed size
for data that eliminates a major porting headache. Binary data is stored and transmitted in a fixed
format, eliminating the “big endian/little endian” confusion. Strings are saved in a standard
Unicode format. Java does this by JVM. Java facilitates you to carry the Java bytecode to any
platform. It doesn't require write different program for different platforms line windows, Linux
etc…
Interpreted
Java Virtual Machine (JVM) is the java interpreter. The interpreter can execute Java
bytecodes directly on any machine to which the interpreter has been ported. Since installing JVM
is a lightweight process, the development process can be much more rapid and exploratory.
High Performance
When Java was still a new language, it was criticized for being slow: Since Java bytecode
was executed by an interpreter, it seemed that Java bytecode programs could never run as quickly
as programs compiled into native machine language (that is, the actual machine language of the
computer on which the program is running). However, this problem has been largely overcome by
the use of just-in-time compilers (JIT) for executing Java bytecode.

JIT is a part of JVM. A just-in-time compiler translates Java bytecode into native machine
language. It does this while it is executing the program. Just as for a normal interpreter, the input
to a just-in-time compiler is a Java bytecode program, and its task is to execute that program.
It is important to understand that it is not practical to compile an entire Java program into
executable code all at once, because Java performs various run-time checks that can be done only
at run time. Instead, a JIT compiler compiles code as it is needed, during execution. Furthermore,
not all sequences of bytecode are compiled—only those that will benefit from compilation. The
remaining code is simply interpreted. The translated parts of the program can then be executed
much more quickly than they could be interpreted. Since a given part of a program is often
executed many times as the program runs, a just-in-time compiler can significantly speed up the
overall execution time.
Even though dynamic compilation is applied to bytecode, the portability and safety
features still apply, because the JVM is still in charge of the execution environment.
Multithreaded
A thread is defined as a separate path of execution inside any process. It is done to use
CPU idle time. A process consists of the memory space allocated by the operating system that can
contain one or more threads. A thread cannot exist on its own; it must be a part of a process.
Whenever a thread is created within a program it will not occupy any separate space. It will share
the same memory space of the program. It will also not consume more resources.
Thread implementations on the major platforms differ widely, but Java makes no effort to
be platform independent in this regard. Only the code for calling multithreading remains the same
across machines; Java offloads the implementation of multithreading to the underlying operating
system or a thread library.

Dynamic
In a number of ways, Java is a more dynamic language than C or C++. It was designed to
adapt to an evolving environment. Libraries can freely add new methods and instance variables
without any effect on their clients. In Java, finding out run time type information is
straightforward. This is an important feature in those situations where code needs to be added to a
running program.

JVM (Java Virtual Machine) Architecture


The JVM (Java Virtual Machine) is a virtual machine, an abstract computer that has its own
ISA, memory, stack, heap, etc. It runs on the host OS and places its demands for resources on it.
The JVM (Java Virtual Machine) is a specification and can have different implementations, as
long as they adhere to the specs. The specs can be found in the below link
− https://docs.oracle.com
Oracle has its own JVM implementation (called the HotSpot JVM), the IBM has its own (the J9
JVM, for example).
The operations defined inside the spec are given below (source − Oracle JVM Specs)
 The 'class' file format
 Data types
 Primitive types and values
 Reference types and values
 Run-time data areas
 Frames
 Representation of objects
 Floating-point arithmetic
 Special methods
 Exceptions
 Instruction set summary
 Class libraries
 Public design, private implementation
JVM (Java Virtual Machine) Architecture
The architecture of the HotSpot JVM 3 is shown below −
The execution engine comprises the garbage collector and the JIT compiler. The JVM
comes in two flavors − client and server. Both of these share the same runtime code but differ in
what JIT is used. We shall learn more about this later. The user can control what flavor to use by
specifying the JVM flags -client or -server. The server JVM has been designed for long-running
Java applications on servers.
The JVM comes in 32b and 64b versions. The user can specify what version to use by
using -d32 or -d64 in the VM arguments. The 32b version could only address up to 4G of memory.
With critical applications maintaining large datasets in memory, the 64b version meets that need.

Components of JVM (Java Virtual Machine) Architecture


The following are the main components of JVM (Java Virtual Machine) architecture:
1. Class Loader
The JVM manages the process of loading, linking and initializing classes and interfaces in a
dynamic manner. During the loading process, the JVM finds the binary representation of a
class and creates it.
During the linking process, the loaded classes are combined into the run-time state of the
JVM so that they can be executed during the initialization phase. The JVM basically uses the
symbol table stored in the run-time constant pool for the linking process. Initialization consists of
actually executing the linked classes.
The following are the types of class loaders:
 BootStrap class loader: This class loader is on the top of the class loader hierarchy. It
loads the standard JDK classes in the JRE's lib directory.
 Extension class loader: This class loader is in the middle of the class loader hierarchy and
is the immediate child of the bootstrap class loader and loads the classes in the JRE's
lib\ext directory.
 Application class loader: This class loader is at the bottom of the class loader hierarchy
and is the immediate child of the application class loader. It loads the jars and classes
specified by the CLASSPATH ENV variable.
2. Linking and Initialization
The linking process consists of the following three steps −
 Verification − This is done by the Bytecode verifier to ensure that the generated .class
files (the Bytecode) are valid. If not, an error is thrown and the linking process comes to a
halt.
 Preparation − Memory is allocated to all static variables of a class and they are initialized
with the default values.
 Resolution − All symbolic memory references are replaced with the original references.
To accomplish this, the symbol table in the run-time constant memory of the method area
of the class is used.
Initialization is the final phase of the class-loading process. Static variables are assigned original
values and static blocks are executed.
3. Runtime Data Areas
The JVM spec defines certain run-time data areas that are needed during the execution of
the program. Some of them are created while the JVM starts up. Others are local to threads and
are created only when a thread is created (and destroyed when the thread is destroyed). These are
listed below −
PC (Program Counter) Register
It is local to each thread and contains the address of the JVM instruction that the thread is
currently executing.
Stack
It is local to each thread and stores parameters, local variables and return addresses during
method calls. A StackOverflow error can occur if a thread demands more stack space than is
permitted. If the stack is dynamically expandable, it can still throw OutOfMemoryError.
Heap
It is shared among all the threads and contains objects, classes' metadata, arrays, etc., that
are created during run-time. It is created when the JVM starts and is destroyed when the JVM
shuts down. You can control the amount of heap your JVM demands from the OS using certain
flags (more on this later). Care has to be taken not to demand too less or too much of the memory,
as it has important performance implications. Further, the GC manages this space and continually
removes dead objects to free up the space.
Method Area
This run-time area is common to all threads and is created when the JVM starts up. It
stores per-class structures such as the constant pool (more on this later), the code for constructors
and methods, method data, etc. The JLS does not specify if this area needs to be garbage collected,
and hence, implementations of the JVM may choose to ignore GC. Further, this may or may not
expand as per the application's needs. The JLS does not mandate anything with regard to this.
Run-Time Constant Pool
The JVM maintains a per-class/per-type data structure that acts as the symbol table (one of
its many roles) while linking the loaded classes.
Native Method Stacks
When a thread invokes a native method, it enters a new world in which the structures and
security restrictions of the Java virtual machine no longer hamper its freedom. A native method
can likely access the runtime data areas of the virtual machine (it depends upon the native method
interface), but can also do anything else it wants.
4. Execution Engine
The execution engine is responsible for executing the bytecode, it has three different
components:
Garbage Collection
The JVM manages the entire lifecycle of objects in Java. Once an object is created, the
developer need not worry about it anymore. In case the object becomes dead (that is, there is no
reference to it anymore), it is ejected from the heap by the GC using one of the many algorithms –
serial GC, CMS, G1, etc.
Read also: Garbage Collection in Java
During the GC process, objects are moved in memory. Hence, those objects are not usable
while the process is going on. The entire application has to be stopped for the duration of the
process. Such pauses are called 'stop-the-world' pauses and are a huge overhead. GC algorithms
aim primarily to reduce this time.
Interpreter
The interpreter Interprets the bytecode. It interprets the code fast but it's slow in execution.
JIT Complier
The JIT stands for Just-In-Time. The JIT compiler is a main part of the Java runtime
environment and it compiles bytecodes to machine code at runtime.
5. Java Native Interface (JNI)
Java Native Interface (JNI) interacts with the native method libraries which are essential
for the execution.
6. Native Method Libraries
Native method libraries are the collection of C and C++ libraries (native libraries) which
are essential for the execution.
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
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.
Understanding and effectively using these data types is crucial for writing efficient and error-free
Java code. If you’re aiming to master Java, exploring detailed resources or Java Programming
Course can help you gain a strong command over data types and other essential Java concepts

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:
Type Description Default Size Example Range of values
Literals

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

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

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


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

short twos-
16
complement 0 (none) -32,768 to 32,767
bits
integer

int twos- -2,147,483,648


32
complement 0 -2,-1,0,1,2 to
bits
intger 2,147,483,647

long
-
twos-
64 -2L,- 9,223,372,036,854,775,808
complement 0
bits 1L,0L,1L,2L to
integer
9,223,372,036,854,775,807

float IEEE 754 1.23e100f , -


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

double IEEE 754 1.23456e300d ,


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

Let us discuss and implement each one of the following data types that are as follows:
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
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, use a
short to save memory in large arrays, in situations where the memory savings actually matters.
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 range of a long is quite large. The long data type is a 64-bit two’s complement integer
and is useful for those occasions where an int type is not large enough to hold the desired value.
The size of the Long Datatype is 8 bytes (64 bits).
Syntax:
long longVar;
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;
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;
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;
EXAMPLE PROGRAM:
class DataTypes{
public static void main(String args[]){
byte byteVar = 5;
short shortVar = 20;
int intVar = 30;
long longVar = 60;
float floatVar = 20;
double doubleVar = 20.123;
boolean booleanVar = true;
char charVar ='W';

System.out.println("Value Of byte Variable is " + byteVar);


System.out.println("Value Of short Variable is " + shortVar);
System.out.println("Value Of int Variable is " + intVar);
System.out.println("Value Of long Variable is " + longVar);
System.out.println("Value Of float Variable is " + floatVar);
System.out.println("Value Of double Variable is " + doubleVar);
System.out.println("Value Of boolean Variable is " + booleanVar);
System.out.println("Value Of char Variable is " + charVar);
}
}
OUTPUT:
Value Of byte Variable is 5
Value Of short Variable is 20
Value Of int Variable is 30
Value Of long Variable is 60
Value Of float Variable is 20.0
Value Of double Variable is 20.123
Value Of boolean Variable is true
Value Of char Variable is W

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).
 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.
 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.
 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.
 A 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.
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: Type of data that can be stored in this variable.
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

Example:
// Declaring float variable
float simpleInterest;

// Declaring and initializing integer variable


int time = 10, speed = 20;

// Declaring and initializing character variable


char var = 'h';
Variables are the basic units of storage in Java. For a deeper understanding of variable types,
scope, and memory management, the Java Programming Course provides a thorough exploration
with hands-on coding tasks.
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.
 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.
 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.
 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

2. Instance Variables
Instance variables are non-static variables and are declared in a class outside of any method,
constructor, or block.
 As instance variables are declared in a class, these variables are created when an object
of the class is created and destroyed when the object is destroyed.
 Unlike local variables, we may use access specifiers for instance variables. If we do 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.
 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.
 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.
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

Scope and lifetime of variables in Java


Scope of a variable refers to in which areas or sections of a program can the variable be accessed
and lifetime of a variable refers to how long the variable stays alive in memory.

General convention for a variable’s scope is, it is accessible only within the block in which it is
declared. A block begins with a left curly brace { and ends with a right curly brace }.

As we know there are three types of variables: 1) instance variables, 2) class variables and 3) local
variables, we will look at the scope and lifetime of each of them now.
Instance Variables

A variable which is declared inside a class and outside all the methods and blocks is an instance
variable.

General scope of an instance variable is throughout the class except in static methods. Lifetime
of an instance variable is until the object stays in memory.
Class Variables

A variable which is declared inside a class, outside all the blocks and is marked static is known as
a class variable.

General scope of a class variable is throughout the class and the lifetime of a class variable is
until the end of the program or as long as the class is loaded in memory.

Local Variables

All other variables which are not instance and class variables are treated as local variables
including the parameters in a method.

Scope of a local variable is within the block in which it is declared and the lifetime of a local
variable is until the control leaves the block in which it is declared.
Nested Scope

In Java, we can create nested blocks – a block inside another block. In case of nested blocks what
is the scope of local variables?

All the local variables in the outer block are accessible within the inner block but vice versa is not
true i.e., local variables within the inner block are not accessible in the outer block. Consider the
following example:
class Sample
{
public static void main(String[] args)
{
int x;
//Begining of inner block
{
int y = 100;
x = 200;
System.out.println("x = "+x);
}
//End of inner block
System.out.println("x = "+x);
y = 200; //Error as y is not accessible in the outer block
}
}

The summary of scope and lifetime of variables is as shown below:

Java Arrays
An array is typically a grouping of elements of the same kind that are stored in a single,
contiguous block of memory.
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where we
store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.
In contrast to C/C++, the length member allows us to obtain the array's length. We must utilise the
sizeof operator in C/C++.
An object of a dynamically formed class is called an array in Java. Java arrays implement the
Serializable and Cloneable interfaces and derive from the Object class. In Java, an array can hold
objects or primitive values. Java allows us to create single- or multi-dimensional arrays, just like
C/C++ does.
Additionally, C/C++ does not support the anonymous array functionality that Java does.

Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: Arrays have a fixed size and do not grow dynamically at runtime.

Types of Array in java


There are two types of array.
o Single Dimensional Array
o Multidimensional Array
Single-Dimensional Array in Java
A single-dimensional array in Java is a linear collection of elements of the same data type. It is
declared and instantiated using the following syntax:

. dataType[] arr; (or)


. dataType []arr; (or)
. dataType arr[];
Instantiation of an Array in Java

. arrayRefVar=new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are going to declare, instantiate, initialize
and traverse an array.

. //Java Program to illustrate how to declare, instantiate, initialize


. //and traverse the Java array.
. class Testarray{
. public static void main(String args[]){
. int a[]=new int[5];//declaration and instantiation
. a[0]=10;//initialization
. a[1]=20;
. a[2]=70;
. a[3]=40;
. a[4]=50;
. //traversing array
. for(int i=0;i<a.length;i++)//length is the property of array
. System.out.println(a[i]);
. }}
Output:

10
20
70
40
50

Declaration, Instantiation and Initialization of Java Array


In Java, you can declare, instantiate, and initialize an array in a single line, as demonstrated below:

. int a[]={33,3,4,5};//declaration, instantiation and initialization


Let's see the simple example to print this array.

. //Java Program to illustrate the use of declaration, instantiation


. //and initialization of Java array in a single line
. class Testarray1{
. public static void main(String args[]){
. int a[]={33,3,4,5};//declaration, instantiation and initialization
. //printing array
. for(int i=0;i<a.length;i++)//length is the property of array
. System.out.println(a[i]);
. }}
Output:

33
3
4
5

For-each Loop for Java Array


We can also print the Java array using for-each loop. The Java for-each loop prints the array
elements one by one. It holds an array element in a variable, then executes the body of the loop.
The syntax of the for-each loop is given below:

. for(data_type variable:array){
. //body of the loop
. }
Let's see the example of printing the elements of the Java array using the for-each loop.
Testarray1.java

. //Java Program to print the array elements using for-each loop


. class Testarray1{
. public static void main(String args[]){
. int arr[]={33,3,4,5};
. //printing array using for-each loop
. for(int i:arr)
. System.out.println(i);
. }}
Output:

33
3
4
5

Passing Array to a Method in Java


We can pass the Java array to the method so that we can reuse the same logic on any array. When
we pass an array to a method in Java, we are essentially passing a reference to the array. It means
that the method will have access to the same array data as the calling code, and any modifications
made to the array within the method will affect the original array.
Let's see the simple example to get the minimum number of an array using a method.
Testarray2.java

. //Java Program to demonstrate the way of passing an array


. //to method.
. class Testarray2{
. //creating a method which receives an array as a parameter
. static void min(int arr[]){
. int min=arr[0];
. for(int i=1;i<arr.length;i++)
. if(min>arr[i])
. min=arr[i];
.
. System.out.println(min);
. }
.
. public static void main(String args[]){
. int a[]={33,3,4,5};//declaring and initializing an array
. min(a);//passing array to method
. }}
Output:

Explanation
This Java program demonstrates the concept of passing an array to a method. The min method
takes an integer array arr as a parameter and finds the minimum element in the array using a
simple iterative loop. In the main method, an integer array a is declared and initialized with values
{33, 3, 4, 5}, and then the min method is called with this array as an argument. The min method
iterates through the array to find the minimum element and prints it to the console.

Anonymous Array in Java


Java's anonymous arrays eliminate the requirement for separate declarations of array variables by
enabling developers to build and initialize arrays directly within method calls or other expressions.
When working with temporary arrays that are just needed for a single job and don't need a
persistent reference within the program, this is quite helpful.
Java supports the feature of an anonymous array, so we do not need to declare the array while
passing an array to the method.
TestAnonymousArray.java

. //Java Program to demonstrate the way of passing an anonymous array


. //to method.
. public class TestAnonymousArray{
. //creating a method which receives an array as a parameter
. static void printArray(int arr[]){
. for(int i=0;i<arr.length;i++)
. System.out.println(arr[i]);
. }
.
. public static void main(String args[]){
. printArray(new int[]{10,22,44,66});//passing anonymous array to method
. }}
Output:

10
22
44
66

Explanation
In this example, the printArray method takes an integer array as a parameter and prints each
element of the array. In the main method, an anonymous array {10, 20, 30} is directly passed as
an argument to the printArray method. This concise syntax demonstrates the usage of anonymous
arrays in Java, allowing for more streamlined code without the need for intermediate variable
declarations.
Returning Array from the Method
In Java, methods are not limited to returning simple data types or objects; they can also return
arrays. This feature allows for more flexibility in method design and enables developers to
encapsulate complex logic for generating arrays within methods.
TestReturnArray.java

. //Java Program to return an array from the method


. class TestReturnArray{
. //creating method which returns an array
. static int[] get(){
. return new int[]{10,30,50,90,60};
. }
.
. public static void main(String args[]){
. //calling method which returns an array
. int arr[]=get();
. //printing the values of an array
. for(int i=0;i<arr.length;i++)
. System.out.println(arr[i]);
. }}
Output:

10
30
50
90
60

Explanation
The example demonstrates how to return an array from a method in Java and subsequently use the
returned array in the calling code. By encapsulating array creation and initialization logic within
the get method, the code becomes more modular and reusable.
ArrayIndexOutOfBoundsException
In Java, the ArrayIndexOutOfBoundsException is a runtime exception thrown by the Java Virtual
Machine (JVM) when attempting to access an invalid index of an array. This exception occurs if
the index is negative, equal to the size of the array, or greater than the size of the array while
traversing the array.
TestArrayException.java

. //Java Program to demonstrate the case of


. //ArrayIndexOutOfBoundsException in a Java Array.
. public class TestArrayException{
. public static void main(String args[]){
. int arr[]={50,60,70,80};
. for(int i=0;i<=arr.length;i++){
. System.out.println(arr[i]);
. }
. }}
Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4


at TestArrayException.main(TestArrayException.java:5)
50
60
70
80

Multidimensional Array in Java


A multidimensional array in Java is an array of arrays where each element can be an array itself. It
is useful for storing data in row and column format.
Syntax to Declare Multidimensional Array in Java

. dataType[][] arrayRefVar; (or)


. dataType [][]arrayRefVar; (or)
. dataType arrayRefVar[][]; (or)
. dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java

. int[][] arr=new int[3][3];//3 row and 3 column


Example to initialize Multidimensional Array in Java

. arr[0][0]=1;
. arr[0][1]=2;
. arr[0][2]=3;
. arr[1][0]=4;
. arr[1][1]=5;
. arr[1][2]=6;
. arr[2][0]=7;
. arr[2][1]=8;
. arr[2][2]=9;
Example of Multidimensional Java Array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
TestMultiArray.java

. class TestMultiArray {
. public static void main(String args[]) {
. int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // 3x3 matrix
. // Printing the 2D array
. for (int i = 0; i < 3; i++) {
. for (int j = 0; j < 3; j++) {
. System.out.print(arr[i][j] + " ");
. }
. System.out.println();
. }
. }
. }
Output:

123
456
789

Explanation
This Java program initializes and prints a 2D array, representing a 3x3 matrix. Initially, a
2D array named arr is declared and initialized with values using array initializer syntax. The array
consists of three rows, each containing three columns. The program then iterates through each
row and column of the array using nested loops. Within the loops, it prints the value of each
element, separated by a space. After printing all the elements of a row, a newline character is
printed to move to the next line. This process continues until all elements of the array are printed.
As a result, the program outputs the 3x3 matrix with each element displayed in its respective row
and column.
These examples demonstrate the declaration, instantiation, initialization, and traversal of
both single-dimensional and multidimensional arrays in Java.
Jagged Arrays in Java
In Java, a jagged array is an array of arrays where each row of the array can have a
different number of columns. This contrasts with a regular two-dimensional array, where each
row has the same number of columns.
Declaring and Initializing a Jagged Array
To declare a jagged array in Java, you first declare the array of arrays, and then you
initialize each row separately with its own array of columns.

. int arr[][] = new int[3][];


. arr[0] = new int[3];
. arr[1] = new int[4];
. arr[2] = new int[2];
TestJaggedArray.java

. //Java Program to illustrate the jagged array


. class TestJaggedArray{
. public static void main(String[] args){
. //declaring a 2D array with odd columns
. int arr[][] = new int[3][];
. arr[0] = new int[3];
. arr[1] = new int[4];
. arr[2] = new int[2];
. //initializing a jagged array
. int count = 0;
. for (int i=0; i<arr.length; i++)
. for(int j=0; j<arr[i].length; j++)
. arr[i][j] = count++;
.
. //printing the data of a jagged array
. for (int i=0; i<arr.length; i++){
. for (int j=0; j<arr[i].length; j++){
. System.out.print(arr[i][j]+" ");
. }
. System.out.println();//new line
. }
. }
. }

012
3456
78

Explanation
This Java program demonstrates the concept of a jagged array, where an array of arrays is created,
with each inner array having a different number of columns. Initially, a 2D array named arr is
declared with 3 rows, but with each row having a different number of columns: the first row has 3
columns, the second row has 4 columns, and the third row has 2 columns. The program then
initializes the jagged array by filling it with sequential values starting from 0. Finally, it iterates
through the array and prints out each element, row by row, separated by a space, with a newline
character indicating the end of each row.
What is the class name of a Java array?
In Java, an array is an object. However, arrays have a special feature in Java where the JVM
generates a proxy class for each array object. This proxy class represents the runtime type of the
array. To obtain the class name of a Java array, you can use the getClass().getName() method,
which is available on all Java objects. This method returns a String representing the fully qualified
name of the class of the object, including any package information.
Testarray.java

. //Java Program to get the class name of array in Java


. class Testarray{
. public static void main(String args[]){
. //declaration and initialization of array
. int arr[]={4,4,5};
. //getting the class name of Java array
. Class c=arr.getClass();
. String name=c.getName();
. //printing the class name of Java array
. System.out.println(name);
.
. }}
Output:
I
Explanation
This Java program demonstrates how to retrieve the class name of an array in Java using the
getClass().getName() method. It initializes an array arr with integer values, obtains the runtime
class of the array using getClass(), and retrieves the class name using getName(). The obtained
class name, typically represented by a single character followed by square brackets, reflects the
dimensionality and type of elements in the array.
Copying a Java Array
Copying an array in Java can be achieved using the arraycopy() method of the System class. This
method allows you to copy elements from a source array to a destination array with a specified
starting position and length.
Syntax of arraycopy method

. public static void arraycopy(


. Object src, int srcPos,Object dest, int destPos, int length
. )
Here, src is the source array, srcPos is the starting position in the source array, dest is the
destination array, destPos is the starting position in the destination array, and length is the number
of elements to be copied.
TestArrayCopy.java

. //Java Program to copy a source array into a destination array in Java


. class TestArrayCopy {
. public static void main(String[] args) {
. //declaring a source array
. char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
. 'i', 'n', 'a', 't', 'e', 'd' };
. //declaring a destination array
. char[] copyTo = new char[7];
. //copying array using System.arraycopy() method
. System.arraycopy(copyFrom, 2, copyTo, 0, 7);
. //printing the destination array
. System.out.println(String.valueOf(copyTo));
. }
. }
Output:
caffein
Explanation
The Java program initializes two character arrays, copyFrom and copyTo, with predefined values.
It then utilizes the System.arraycopy() method to copy a portion of the copyFrom array into the
copyTo array, starting from index 2 and copying 7 elements. Finally, it prints the contents of the
copyTo array, resulting in the output "caffein".

Cloning an Array in Java


In Java, arrays implement the Cloneable interface, allowing us to create clones of arrays. If we
create a clone of a single-dimensional array, it creates a deep copy of the Java array. It means it
will copy the actual value. But, if we create the clone of a multidimensional array, it creates a
shallow copy of the Java array, which means it copies the references.
This distinction is important because modifying elements in a shallow copied multidimensional
array will affect both the original and cloned arrays, while in a deep copied single-dimensional
array, modifications will not impact the original.
TestarrayClone.java

. //Java Program to clone the array


. class TestarrayClone{
. public static void main(String args[]){
. int arr[]={33,3,4,5};
. System.out.println("Printing original array:");
. for(int i:arr)
. System.out.println(i);
. System.out.println("Printing clone of the array:");
. int carr[]=arr.clone();
. for(int i:carr)
. System.out.println(i);
. System.out.println("Are both equal?");
. System.out.println(arr==carr);
. }
. }
Output:

Printing original array:


33
3
4
5
Printing clone of the array:
33
3
4
5
Are both equal?
False

Explanation
An integer array called arr is initialised with the numbers {33, 3, 4, 5} in this Java programme,
and its elements are printed. Then, it uses the clone() method to duplicate arr, assigns the result to
carr, and prints the items of the duplicated array. The last line of the programme compares arr and
carr using the == operator; the result evaluates to false, meaning that arr and carr are distinct array
objects. The elements in both arrays, though, are the same.
Addition of Two Matrices in Java
A fundamental operation in linear algebra and computer science, matrix addition is frequently
utilised in a variety of applications, including scientific computing, computer graphics, and image
processing. To create a new matrix with the same dimensions as the original, matching elements
from each matrix must be added when adding two matrices in Java. This Java program shows how
to add matrices effectively by using stacked loops to do a basic example of the process.
Let's see a simple example that adds two matrices.
ArrayAddition.java

. //Java Program to demonstrate the addition of two matrices in Java


. class ArrayAddition{
. public static void main(String args[]){
. //creating two matrices
. int a[][]={{1,3,4},{3,4,5}};
. int b[][]={{1,3,4},{3,4,5}};
.
. //creating another matrix to store the sum of two matrices
. int c[][]=new int[2][3];
.
. //adding and printing addition of 2 matrices
. for(int i=0;i<2;i++){
. for(int j=0;j<3;j++){
. c[i][j]=a[i][j]+b[i][j];
. System.out.print(c[i][j]+" ");
. }
. System.out.println();//new line
. }
.
. }}
Output:
268
5 8 10
Explanation
This Java program demonstrates matrix addition by adding two predefined matrices, a and
b, element-wise and storing the result in matrix c. The matrices a and b are initialized with values,
and matrix c is created to store the sum. It iterates through each element of the matrices using
nested loops, adding corresponding elements from a and b and storing the result in the
corresponding position in c. Finally, it prints the resulting matrix c. The output displays the
element-wise addition of the two matrices, with each element in the resulting matrix c being the
sum of the corresponding elements in a and b.
Multiplication of Two Matrices in Java
Matrix multiplication is a crucial operation in mathematics and computer science, often
utilized in various applications such as graphics rendering, optimization algorithms, and scientific
computing. In Java, multiplying two matrices involves a systematic process where each element
in the resulting matrix is computed by taking the dot product of a row from the first matrix and a
column from the second matrix.

Let's see a simple example to multiply two matrices of 3 rows and 3 columns.
MatrixMultiplicationExample.java

. //Java Program to multiply two matrices


. public class MatrixMultiplicationExample{
. public static void main(String args[]){
. //creating two matrices
. int a[][]={{1,1,1},{2,2,2},{3,3,3}};
. int b[][]={{1,1,1},{2,2,2},{3,3,3}};
.
. //creating another matrix to store the multiplication of two matrices
. int c[][]=new int[3][3]; //3 rows and 3 columns
.
. //multiplying and printing multiplication of 2 matrices
. for(int i=0;i<3;i++){
. for(int j=0;j<3;j++){
. c[i][j]=0;
. for(int k=0;k<3;k++)
. {
. c[i][j]+=a[i][k]*b[k][j];
. }//end of k loop
. System.out.print(c[i][j]+" "); //printing matrix element
. }//end of j loop
. System.out.println();//new line
. }
. }}
Output:
666
12 12 12
18 18 18

Explanation
This Java program computes the multiplication of two 3x3 matrices, 'a' and 'b', storing the result
in matrix 'c'. It initializes matrices 'a' and 'b' with predefined values and creates matrix 'c' to store
the result. Using nested loops, it iterates through each element of the resulting matrix 'c',
calculating the dot product of corresponding row and column elements from matrices 'a' and 'b'.
The computed result for each element is accumulated in the corresponding position of 'c'.
Operators in Java
Last Updated : 04 Oct, 2024
Java provides many types of operators which can be used according to the need. They are
classified based on the functionality they provide. In this article, we will learn about Java
Operators and learn all their types.
What are the Java Operators?
Operators in Java are the symbols used for performing specific operations in Java. Operators
make tasks like addition, multiplication, etc which look easy although the implementation of these
tasks is quite complex.
Operators are the building blocks of Java expressions, allowing you to perform calculations,
comparisons, and more. For a deeper exploration of all types of operators and how to use them
effectively, the Java Programming Course covers everything from basic arithmetic to advanced
bitwise operations.
Types of Operators in Java
There are multiple types of operators in Java all are mentioned below:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. 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
Example:
// Java Program to implement
// Arithmetic Operators
import java.io.*;

// Drive Class
class GFG {
// Main Function
public static void main (String[] args) {

// Arithmetic operators on integers


int a = 10;
int b = 3;

// Arithmetic operators on Strings


String num1 = "15";
String num2 = "25";

// Convert Strings to integers


int a1 = Integer.parseInt(num1);
int b1 = Integer.parseInt(num2);

System.out.println("a + b = " + (a + b));


System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));
System.out.println("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.
 + : Unary plus indicates the positive value (numbers are positive without this, however).
It performs an automatic conversion to int when the type of its operand is the byte, char, or
short. This is called unary numeric promotion.
 ++ : Increment operator, used for incrementing the value by 1. There are two varieties
of increment operators.
o Post-Increment: Value is first used for computing the result and then
incremented.
o Pre-Increment: Value is incremented first, and then the result is computed.
 – – : Decrement operator, used for decrementing the value by 1. There are two
varieties of decrement operators.
o Post-decrement: Value is first used for computing the result and then
decremented.
o Pre-Decrement: The value is decremented first, and then the result is computed.
 ! : Logical not operator, used for inverting a boolean value.
Example:
// Java Program to implement
// Unary Operators
import java.io.*;

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

// Using unary operators


System.out.println("Postincrement : " + (a++));
System.out.println("Preincrement : " + (++a));

System.out.println("Postdecrement : " + (b--));


System.out.println("Predecrement : " + (--b));
}
}
Output
Postincrement : 10
Preincrement : 12
Postdecrement : 10
Predecrement : 8
3. Assignment Operator
‘=’ Assignment operator is used to assign a value to any variable. It has right-to-left
associativity, i.e. value given on the right-hand side of the 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.
The general format of the assignment operator is:
variable = value;
In many cases, the assignment operator can be combined with other operators to build a shorter
version of the statement called a Compound Statement. For example, instead of a = a+5, we
can write a += 5.
 +=, for adding the left operand with the right operand and then assigning it to the
variable on the left.
 -=, for subtracting the right operand from the left operand and then assigning it to the
variable on the left.
 *=, for multiplying the left operand with the right operand and then assigning it to the
variable on the left.
 /=, for dividing the left operand by the right operand and then assigning it to the variable
on the left.
 %=, for assigning the modulo of the left operand by the right operand and then assigning
it to the variable on the left.
// Java Program to implement
// Assignment Operators
import java.io.*;

// Driver Class
class GFG {
// Main Function
public static void main(String[] args)
{

// Assignment operators
int f = 7;
System.out.println("f += 3: " + (f += 3));
System.out.println("f -= 2: " + (f -= 2));
System.out.println("f *= 4: " + (f *= 4));
System.out.println("f /= 3: " + (f /= 3));
System.out.println("f %= 2: " + (f %= 2));
System.out.println("f &= 0b1010: " + (f &= 0b1010));
System.out.println("f |= 0b1100: " + (f |= 0b1100));
System.out.println("f ^= 0b1010: " + (f ^= 0b1010));
System.out.println("f <<= 2: " + (f <<= 2));
System.out.println("f >>= 1: " + (f >>= 1));
System.out.println("f >>>= 1: " + (f >>>= 1));
}
}
Output
f += 3: 10
f -= 2: 8
f *= 4: 32
f /= 3: 10
f %= 2: 0
f &= 0b1010: 0
f |= 0b1100: 12
f ^= 0b1010: 6
f <<= 2: 24
f >>= 1: 12
f >>>= 1: 6
4. Relational Operators
These operators are used to check for relations like equality, greater than, and less than. They
return boolean results after the comparison and are extensively used in looping statements as
well as conditional if-else statements. The general format is,
variable relation_operator value
Some of the relational operators are-
 ==, Equal to returns true if the left-hand side is equal to the right-hand side.
 !=, Not Equal to returns true if the left-hand side is not equal to the right-hand side.
 <, less than: returns true if the left-hand side is less than the right-hand side.
 <=, less than or equal to returns true if the left-hand side is less than or equal to the
right-hand side.
 >, Greater than: returns true if the left-hand side is greater than the right-hand side.
 >=, Greater than or equal to returns true if the left-hand side is greater than or equal to
the right-hand side.
Example:
// Java Program to implement
// Relational Operators
import java.io.*;
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Comparison operators
int a = 10;
int b = 3;
int c = 5;

System.out.println("a > b: " + (a > b));


System.out.println("a < b: " + (a < b));
System.out.println("a >= b: " + (a >= b));
System.out.println("a <= b: " + (a <= b));
System.out.println("a == c: " + (a == c));
System.out.println("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” operations, i.e., a function
similar to AND gate and OR gate in digital electronics. One thing to keep in mind is the second
condition is not evaluated if the first one is false, i.e., it has a short-circuiting effect. Used
extensively to test for several conditions for making a decision. Java also has “Logical NOT”,
which returns true when the condition is false and vice-versa
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
Example:
// Java Program to implemenet
// Logical operators
import java.io.*;

// Driver Class
class GFG {
// Main Function
public static void main (String[] args) {
// Logical operators
boolean x = true;
boolean y = false;

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


System.out.println("x || y: " + (x || y));
System.out.println("!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 ‘:’.
Example:
// Java program to illustrate
// max of three numbers using
// ternary operator.
public class operators {
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) ? a : c : (b > c) ? b : c);
System.out.println("Max of three numbers = "
+ result);
}
}
Output
Max of three numbers = 30
7. Bitwise Operators
These operators are used to perform the manipulation of individual bits of a number. They can be
used with any of the integer types. They are used when performing update and query operations of
the Binary indexed trees.
 &, Bitwise AND operator: returns bit by bit AND of input values.
 |, Bitwise OR operator: returns bit by bit OR of input values.
 ^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
 ~, Bitwise Complement Operator: This is a unary operator which returns the one’s
complement representation of the input value, i.e., with all bits inverted.
Java

// Java Program to implement


// bitwise operators
import java.io.*;

// Driver class
class GFG {
// main function
public static void main(String[] args)
{
// Bitwise operators
int d = 0b1010;
int e = 0b1100;
System.out.println("d & e: " + (d & e));
System.out.println("d | e: " + (d | e));
System.out.println("d ^ e: " + (d ^ e));
System.out.println("~d: " + (~d));
System.out.println("d << 2: " + (d << 2));
System.out.println("e >> 1: " + (e >> 1));
System.out.println("e >>> 1: " + (e >>> 1));
}
}
Output
d & e: 8
d | e: 14
d ^ e: 6
~d: -11
d << 2: 40
e >> 1: 6
e >>> 1: 6
8. Shift Operators
These 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. General format-
number shift_op number_of_places_to_shift;
 <<, Left shift operator: shifts the bits of the number to the left and fills 0 on voids left
as a result. Similar effect as multiplying the number with some power of two.
 >>, Signed Right shift operator: shifts the bits of the number to the right and fills 0 on
voids left as a result. The leftmost bit depends on the sign of the initial number. Similar
effect to dividing the number with some power of two.
 >>>, Unsigned Right shift operator: shifts the bits of the number to the right and fills 0
on voids left as a result. The leftmost bit is set to 0.
// Java Program to implement
// shift operators
import java.io.*;

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

// using left shift


System.out.println("a<<1 : " + (a << 1));

// using right shift


System.out.println("a>>1 : " + (a >> 1));
}
}
Output
a<<1 : 20
a>>1 : 5
9. instanceof operator
The instance of the 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. General format-
object instance of class/subclass/interface
// Java program to illustrate
// instance of operator

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

Person obj1 = new Person();


Person obj2 = new Boy();

// As obj is of type person, it is not an


// instance of Boy or interface
System.out.println("obj1 instanceof Person: "
+ (obj1 instanceof Person));
System.out.println("obj1 instanceof Boy: "
+ (obj1 instanceof Boy));
System.out.println("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
System.out.println("obj2 instanceof Person: "
+ (obj2 instanceof Person));
System.out.println("obj2 instanceof Boy: "
+ (obj2 instanceof Boy));
System.out.println("obj2 instanceof MyInterface: "
+ (obj2 instanceof MyInterface));
}
}

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
Precedence and Associativity of Java Operators
Precedence and associative rules are used when dealing with hybrid equations involving more
than one type of operator. In such cases, these rules determine which part of the equation to
consider first, as there can be many different valuations for the same equation. The below table
depicts the precedence of operators in decreasing order as magnitude, with the top representing
the highest precedence and the bottom showing the lowest precedence.
Interesting Questions about Java Operators
1. Precedence and Associativity:
There is often confusion when it comes to hybrid equations which are equations having multiple
operators. The problem is which part to solve first. There is a golden rule to follow in these
situations. If the operators have different precedence, solve the higher precedence first. If they
have the same precedence, solve according to associativity, that is, either from right to left or from
left to right. The explanation of the below program is well written in comments within the
program itself.
public class operators {
public static void main(String[] args)
{
int a = 20, b = 10, c = 0, d = 20, e = 40, f = 30;

// precedence rules for arithmetic operators.


// (* = / = %) > (+ = -)
// prints a+(b/d)
System.out.println("a+b/d = " + (a + b / d));

// if same precedence then associative


// rules are followed.
// e/f -> b*d -> a+(b*d) -> a+(b*d)-(e/f)
System.out.println("a+b*d-e/f = "
+ (a + b * d - e / f));
}
}
Output
a+b/d = 20
a+b*d-e/f = 219

2. Be a Compiler:
The compiler in our systems uses a lex tool to match the greatest match when generating tokens.
This creates a bit of a problem if overlooked. For example, consider the statement a=b+++c; too
many of the readers might seem to create a compiler error. But this statement is absolutely
correct as the token created by lex is a, =, b, ++, +, c. Therefore, this statement has a similar
effect of first assigning b+c to a and then incrementing b. Similarly, a=b+++++c; would
generate an error as the tokens generated are a, =, b, ++, ++, +, c. which is actually an error as
there is no operand after the second unary operand.
public class operators {
public static void main(String[] args)
{
int a = 20, b = 10, c = 0;

// a=b+++c is compiled as
// b++ +c
// a=b+c then b=b+1
a = b++ + c;
System.out.println("Value of a(b+c), "
+ " b(b+1), c = " + a + ", " + b
+ ", " + c);

// a=b+++++c is compiled as
// b++ ++ +c
// which gives error.
// a=b+++++c;
// System.out.println(b+++++c);
}
}
Output
Value of a(b+c), b(b+1), c = 10, 11, 0

3. Using + over ():


When using the + operator inside system.out.println() make sure to do addition using
parenthesis. If we write something before doing addition, then string addition takes place, that is,
associativity of addition is left to right, and hence integers are added to a string first producing a
string, and string objects concatenate when using +. Therefore it can create unwanted results.
public class operators {
public static void main(String[] args)
{
int x = 5, y = 8;

// concatenates x and y as
// first x is added to "concatenation (x+y) = "
// producing "concatenation (x+y) = 5"
// and then 8 is further concatenated.
System.out.println("Concatenation (x+y)= " + x + y);

// addition of x and y
System.out.println("Addition (x+y) = " + (x + y));
}
}
Output
Concatenation (x+y)= 58
Addition (x+y) = 13

Advantages of Operators in Java


The advantages of using operators in Java are mentioned below:
1. Expressiveness: Operators in Java provide a concise and readable way to perform
complex calculations and logical operations.
2. Time-Saving: Operators in Java save time by reducing the amount of code required to
perform certain tasks.
3. Improved Performance: Using operators can improve performance because they are
often implemented at the hardware level, making them faster than equivalent Java code.
Disadvantages of Operators in Java
The disadvantages of Operators in Java are mentioned below:
1. Operator Precedence: Operators in Java have a defined precedence, which can lead to
unexpected results if not used properly.
2. Type Coercion: Java performs implicit type conversions when using operators, which
can lead to unexpected results or errors if not used properly.

Java Control Statements | Control Flow in Java


Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. However, Java provides statements that can be used
to control the flow of Java code. Such statements are called control flow statements. It is one of
the fundamental features of Java, which provides a smooth flow of program.
Java provides three types of control flow statements.
1. Decision Making statements
1. if statements
2. switch statement
2. Loop statements
1. do while loop
2. while loop
3. for loop
4. for-each loop
3. Jump statements
1. break statement
2. continue statement
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and when.
Decision-making statements evaluate the Boolean expression and control the program flow
depending upon the result of the condition provided. There are two types of decision-making
statements in Java, i.e., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted
depending upon the specific condition. The condition of the If statement gives a Boolean value,
either true or false. In Java, there are four types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
Let's understand the if-statements one by one.
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean
expression and enables the program to enter a block of code if the expression evaluates to true.
Syntax of if statement is given below.

. if(condition) {
. statement 1; //executes when condition is true
. }
Consider the following example in which we have used the if statement in the java code.
Student.java
Student.java

. public class Student {


. public static void main(String[] args) {
. int x = 10;
. int y = 12;
. if(x+y > 20) {
. System.out.println("x + y is greater than 20");
. }
. }
. }
Output:
x+y is greater than 20

2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code, i.e.,
else block. The else block is executed if the condition of the if-block is evaluated as false.
Syntax:

. if(condition) {
. statement 1; //executes when condition is true
. }
. else{
. statement 2; //executes when condition is false
. }
Consider the following example.
Student.java

. public class Student {


. public static void main(String[] args) {
. int x = 10;
. int y = 12;
. if(x+y < 10) {
. System.out.println("x + y is less than 10");
. } else {
. System.out.println("x + y is greater than 20");
. }
. }
. }
Output:
x+y is greater than 20

3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other
words, we can say that it is the chain of if-else statements that create a decision tree where the
program may enter in the block of code where the condition is true. We can also define an else
statement at the end of the chain.
Syntax of if-else-if statement is given below.

. if(condition 1) {
. statement 1; //executes when condition 1 is true
. }
. else if(condition 2) {
. statement 2; //executes when condition 2 is true
. }
. else {
. statement 2; //executes when all the conditions are false
. }
Consider the following example.
Student.java
. public class Student {
. public static void main(String[] args) {
. String city = "Delhi";
. if(city == "Meerut") {
. System.out.println("city is meerut");
. }else if (city == "Noida") {
. System.out.println("city is noida");
. }else if(city == "Agra") {
. System.out.println("city is agra");
. }else {
. System.out.println(city);
. }
. }
. }
Output:
Delhi

4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or
else-if statement.
Syntax of Nested if-statement is given below.

. if(condition 1) {
. statement 1; //executes when condition 1 is true
. if(condition 2) {
. statement 2; //executes when condition 2 is true
. }
. else{
. statement 2; //executes when condition 2 is false
. }
. }
Consider the following example.
Student.java

. public class Student {


. public static void main(String[] args) {
. String address = "Delhi, India";
.
. if(address.endsWith("India")) {
. if(address.contains("Meerut")) {
. System.out.println("Your city is Meerut");
. }else if(address.contains("Noida")) {
. System.out.println("Your city is Noida");
. }else {
. System.out.println(address.split(",")[0]);
. }
. }else {
. System.out.println("You are not living in India");
. }
. }
. }
Output:
Delhi

Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which is
being switched. The switch statement is easier to use instead of if-else-if statements. It also
enhances the readability of the program.
Points to be noted about switch statement:
o The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of expression.
It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the same
type as the variable. However, it will also be a constant value.
The syntax to use the switch statement is given below.

. switch (expression){
. case value1:
. statement1;
. break;
. .
. .
. .
. case valueN:
. statementN;
. break;
. default:
. default statement;
. }
Consider the following example to understand the flow of the switch statement.
Student.java

. public class Student implements Cloneable {


. public static void main(String[] args) {
. int num = 2;
. switch (num){
. case 0:
. System.out.println("number is 0");
. break;
. case 1:
. System.out.println("number is 1");
. break;
. default:
. System.out.println(num);
. }
. }
. }
Output:
2

While using switch statements, we must notice that the case expression will be of the same type as
the variable. However, it will also be a constant value. The switch permits only int, string, and
Enum type variables to be used.
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of instructions in
a repeated order. The execution of the set of instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in
their syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
Let's understand the loop statements one by one.
Java for loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the
condition, and increment/decrement in a single line of code. We use the for loop only when we
exactly know the number of times, we want to execute the block of code.

. for(initialization, condition, increment/decrement) {


. //block of statements
. }
The flow chart for the for-loop is given below.

Consider the following example to understand the proper functioning of the for loop in java.
Calculation.java

. public class Calculattion {


. public static void main(String[] args) {
. // TODO Auto-generated method stub
. int sum = 0;
. for(int j = 1; j<=10; j++) {
. sum = sum + j;
. }
. System.out.println("The sum of first 10 natural numbers is " + sum);
. }
. }
Output:

The sum of first 10 natural numbers is 55

Java for-each loop


Java provides an enhanced for loop to traverse the data structures like array or collection. In the
for-each loop, we don't need to update the loop variable. The syntax to use the for-each loop in
java is given below.

. for(data_type var : array_name/collection_name){


. //statements
. }
Consider the following example to understand the functioning of the for-each loop in Java.
Calculation.java
. public class Calculation {
. public static void main(String[] args) {
. // TODO Auto-generated method stub
. String[] names = {"Java","C","C++","Python","JavaScript"};
. System.out.println("Printing the content of the array names:\n");
. for(String name:names) {
. System.out.println(name);
. }
. }
. }
Output:

Printing the content of the array names:

Java
C
C++
Python
JavaScript

Java while loop


The while loop is also used to iterate over the number of statements multiple times. However, if
we don't know the number of iterations in advance, it is recommended to use a while loop. Unlike
for loop, the initialization and increment/decrement doesn't take place inside the loop statement in
while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the loop.
If the condition is true, then the loop body will be executed; otherwise, the statements after the
loop will be executed.
The syntax of the while loop is given below.

. while(condition){
. //looping statements
. }
The flow chart for the while loop is given in the following image.

Consider the following example.


Calculation .java

. public class Calculation {


. public static void main(String[] args) {
. // TODO Auto-generated method stub
. int i = 0;
. System.out.println("Printing the list of first 10 even numbers \n");
. while(i<=10) {
. System.out.println(i);
. i = i + 2;
. }
. }
. }
Output:

Printing the list of first 10 even numbers

0
2
4
6
8
10

Java do-while loop


The do-while loop checks the condition at the end of the loop after executing the loop statements.
When the number of iteration is not known and we have to execute the loop at least once, we can
use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The
syntax of the do-while loop is given below.

. do
. {
. //statements
. } while (condition);
The flow chart of the do-while loop is given in the following image.

Consider the following example to understand the functioning of the do-while loop in Java.
Calculation.java
. public class Calculation {
. public static void main(String[] args) {
. // TODO Auto-generated method stub
. int i = 0;
. System.out.println("Printing the list of first 10 even numbers \n");
. do {
. System.out.println(i);
. i = i + 2;
. }while(i<=10);
. }
. }
Output:

Printing the list of first 10 even numbers


0
2
4
6
8
10

Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In other
words, jump statements transfer the execution control to the other part of the program. There are
two types of jump statements in Java, i.e., break and continue.
Java break statement
As the name suggests, the break statement is used to break the current flow of the program and
transfer the control to the next statement outside a loop or switch statement. However, it breaks
only the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be written
inside the loop or switch statement.
The break statement example with for loop
Consider the following example in which we have used the break statement with the for loop.
BreakExample.java

. public class BreakExample {


.
. public static void main(String[] args) {
. // TODO Auto-generated method stub
. for(int i = 0; i<= 10; i++) {
. System.out.println(i);
. if(i==6) {
. break;
. }
. }
. }
. }
Output:

0
1
2
3
4
5
6

break statement example with labeled for loop


Calculation.java

. public class Calculation {


.
. public static void main(String[] args) {
. // TODO Auto-generated method stub
. a:
. for(int i = 0; i<= 10; i++) {
. b:
. for(int j = 0; j<=15;j++) {
. c:
. for (int k = 0; k<=20; k++) {
. System.out.println(k);
. if(k==5) {
. break a;
. }
. }
. }
.
. }
. }
.
.
. }
Output:
0
1
2
3
4
5
Java continue statement
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the
specific part of the loop and jumps to the next iteration of the loop immediately.
Consider the following example to understand the functioning of the continue statement in Java.

. public class ContinueExample {


.
. public static void main(String[] args) {
. // TODO Auto-generated method stub
.
. for(int i = 0; i<= 2; i++) {
.
. for (int j = i; j<=5; j++) {
.
. if(j == 4) {
. continue;
. }
. System.out.println(j);
. }
. }
. }
.
. }
Output:
0
1
2
3
5
1
2
3
5
2
3
5

Type Casting in Java


Type casting in Java is a fundamental concept that allows developers to convert data from one
data type to another. It is essential for handling data in various situations, especially when dealing
with different types of variables, expressions, and methods. In Java, type casting is a method or
process that converts a data type into another data type in both ways manually and automatically.
The automatic conversion is done by the compiler and manual conversion performed by the
programmer. In this section, we will discuss type casting and its types with proper examples.

Type Casting
Convert a value from one data type to another data type is known as type casting.
Rules of Typecasting
Widening Conversion (Implicit)
o No explicit notation is required.
o Conversion from a smaller data type to a larger data type is allowed.
o No risk of data loss.
Narrowing Conversion (Explicit)
o Requires explicit notation using parentheses and casting.
o Conversion from a larger data type to a smaller data type is allowed.
o Risk of data loss due to truncation.
Use Cases
Typecasting is commonly used in various scenarios, such as:
o Converting between primitive data types.
o Handling data in expressions and calculations.
o Interacting with different methods and APIs that expect specific data types.
Types of Type Casting
There are two types of type casting:
o Widening Type Casting
o Narrowing Type Casting
Widening Type Casting
Converting a lower data type into a higher one is called widening type casting. It is also known
as implicit conversion or casting down. It is done automatically. It is safe because there is no
chance to lose data. It takes place when:
o Both data types must be compatible with each other.
o The target type must be larger than the source type.

. byte -> short -> char -> int -> long -> float -> double
Why Widening Type Casting?
Widening conversion needs to be implemented in order to enable Java to work smoothly with
different data types. It creates unbroken workflows when an element of a smaller type is used in a
context that needs a larger type. The reason for generalizing the narrower type is in order not to
lose any data by converting the smaller type to the larger one, and preserving the whole
information.
Types of Widening Type Casting
The common procedure of the Widening type casting is about conversion from primitive to
primitive data types in Java.
o From byte to short, int, long, float, or double.
o From data to type int, long, float, or double.
o Char to int, long, float, or double can be converted.
o Various other types like int, long, float, or double can also be used.
Key Points to Note
o Widening typecasting is performed automatically by the Java compiler when converting
from a smaller data type to a larger data type.
o No explicit notation, such as casting, is required for widening typecasting.
o Widening conversions are always safe and do not result in any loss of data.
o Widening typecasting is commonly used in assignments, expressions, and method
invocations where data of different types interact.
For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other. Let's see
an example.
WideningTypeCastingExample.java

. public class WideningTypeCastingExample


. {
. public static void main(String[] args)
. {
. int x = 7;
. //automatically converts the integer type into long type
. long y = x;
. //automatically converts the long type into float type
. float z = y;
. System.out.println("Before conversion, int value "+x);
. System.out.println("After conversion, long value "+y);
. System.out.println("After conversion, float value "+z);
. }
. }
Output

Before conversion, the value is: 7


After conversion, the long value is: 7
After conversion, the float value is: 7.0

In the above example, we have taken a variable x and converted it into a long type. After that, the
long type is converted into the float type.
Narrowing Type Casting
Converting a higher data type into a lower one is called narrowing type casting. It is also known
as explicit conversion or casting up. It is done manually by the programmer. If we do not
perform casting, then the compiler reports a compile-time error.

. double -> float -> long -> int -> char -> short -> byte
Why Narrowing Type casting?
Narrowing typecasting becomes necessary when we need to convert data from a larger data type
to a smaller one. It often occurs when we are working with data of different sizes and need to fit
larger values into smaller containers.
Let's see an example of narrowing type casting.
In the following example, we have performed the narrowing type casting two times. First, we
have converted the double type into long data type after that long data type is converted into int
type.
NarrowingTypeCastingExample.java

. public class NarrowingTypeCastingExample


. {
. public static void main(String args[])
. {
. double d = 166.66;
. //converting double data type into long data type
. long l = (long)d;
. //converting long data type into int data type
. int i = (int)l;
. System.out.println("Before conversion: "+d);
. //fractional part lost
. System.out.println("After conversion into long type: "+l);
. //fractional part lost
. System.out.println("After conversion into int type: "+i);
. }
. }
Output

Before conversion: 166.66


After conversion into long type: 166
After conversion into int type: 166

Potential Data Loss


One of the risky things incurred with narrowing type casting is data loss. When going from a
larger data type to a smaller one, we may lose accuracy or range. For example, if the value of the
target data type is larger than the range represented by the larger data type.
Handling Potential Data Loss
o The data stability depends on your caution when type casting.
o Make certain that the value that is being converted falls within the range of the data target
type.
o Remember about the potential miscalculation, especially when converting floating-point
numbers to integers.
o Employ rounding or other techniques to ensure data integrity given the demands of your
application.
Avoiding Runtime Errors
Narrowing type casting or any other improper usage of it can lead to runtime errors consisting of
data truncation or unexpected behaviors.
o Data loss might happen, and cope with it appropriately.
o Check your code throughly, especially when is involved converting between different data
types.
o Looking at different methods, for example, widening type casting or the use of data
structures that can handle larger values without precision loss, is an alternative way of
doing it.
Type Casting Pitfalls
While type casting is a powerful feature, it comes with certain pitfalls:
o Data loss in narrowing conversions.
o Potential runtime errors if type casting is not handled properly.
o Reduced code readability if type casting is overused.
Avoiding Pitfalls
o Use implicit type casting where possible to ensure data integrity.
o Employ explicit type casting only when necessary, and handle potential data loss carefully.
o Thoroughly test code involving type casting to identify and address any runtime issues.
First Java Program | Hello World Example
In this section, we will learn how to write the simple program of Java. We can write a
simple hello world Java program easily after installing the JDK.
In Java, for creating a program it is necessary to create a class that contains the main() method
(entry point of the program). Before moving forward in this section, let's understand the
requirement first.
Basic Requirement for Java Hello World Example
For executing any Java program, the following software or application must be properly installed.
o Install the JDK if we do not have installed it, download the JDK and install it.
o Set path of the jdk/bin directory, go through the link http://www.javatpoint.com/how-to-
set-path-in-java
o Create the Java program.
o Compile and run the Java program.
Creating Hello World Example
Let's create the hello world Java program:

. class Simple{
. public static void main(String args[]){
. System.out.println("Hello Java");
. }
. }
Save the above file as Simple.java.
To compile: javac Simple.java
To execute: java Simple
Output:
Hello Java

Compilation Flow:
When we compile Java program using javac tool, the Java compiler converts the source code into
byte code.
Parameters used in First Java Program
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
o class keyword is used to declare a class in Java.
o public keyword is an access modifier that represents visibility. It means it is visible to all.
o 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 does not
require creating an object to invoke the main() method. So, it saves memory.
o void is the return type of the method. It means it does not return any value.
o The main() method represents the starting point of the program.
o String[] args or String args[] is used for command line argument. We will discuss it in
coming section.
o System.out.println() is used to print statement on the console. Here, System is a class, out
is an object of the PrintStream class, println() is a method of the PrintStream class. We
will discuss the internal working of System.out.println() statement in the coming section.
To write the simple program, we need to open notepad by Start Menu -> All Programs ->
Accessories -> Notepad and write a simple program as we have shownbelow:

As we can see in the above notepad window, we have written a simple Java program and saved it
as Simple.java.
In order to compile and run the above program, open the Command Prompt window by using the
following steps:
Click on start menu -> All Programs -> Accessories -> command prompt. When we have
done with all the steps properly, following window appears on the screen:
To compile and run the above program, go to your current directory first; my current directory
is c:\new. Write the following commands:
To compile: javac Simple.java
To execute: java Simple

In how many ways we can write a Java program?


There are many ways to write a Java program. The modifications that can be done in a Java
program are given below:
1) By changing the sequence of the modifiers, method prototype is not changed in Java.
Let's see the simple code of the main() method.

. static public void main(String args[])


2) The subscript notation in the Java array can be used after type, before the variable or
after the variable.
Let's see the different codes to write the main method.

. public static void main(String[] args)


. public static void main(String []args)
. public static void main(String args[])
3) You can provide var-args support to the main() method by passing 3 ellipses (dots)
Let's see the simple code of using var-args in the main() method. We will learn about var-args
later in the Java New Features chapter.

. public static void main(String... args)


4) Having a semicolon at the end of class is optional in Java.
Let's see the simple code.

. class A{
. static public void main(String... args){
. System.out.println("hello java4");
. }
. }; //optional
Valid Java main() method signature

. public static void main(String[] args)


. 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)
. final strictfp 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)
. abstract public static void main(String[] args)
Resolving an error "javac is not recognized as an internal or external command"?
If there occurs a problem like displayed in the below figure, we need to set a path. Since DOS
does not recognize javac and java as internal or external command. To overcome this problem, we
need to set Java path.
The path is not required in a case where we save your program inside the JDK/bin directory.
However, it is an excellent approach to set the path. Click here for How to set path in java.

Java Constructors
Java constructors or constructors in Java is a terminology used to construct something in our
programs. A constructor in Java is a special method that is used to initialize objects. The
constructor is called when an object of a class is created. It can be used to set initial values for
object attributes.

What are Constructors in Java?


In Java, a Constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling the constructor, memory for the object is allocated in
the memory. It is a special type of method that is used to initialize the object. Every time an
object is created using the new() keyword, at least one constructor is called.
Understanding how to effectively use constructors can significantly improve your Java
programming skills, especially when you’re dealing with complex applications. It’s crucial to
grasp the nuances of constructors to build scalable and maintainable software. This knowledge
forms a foundation for more advanced concepts and practices in Java development, which can
be further explored through our dedicated Java Course .

Example of Java Constructor


Below is the implementation of Java Constructors:
// Java Program to demonstrate
// Constructor
import java.io.*;

// Driver Class
class Geeks {

// Constructor
Geeks()
{
super();
System.out.println("Constructor Called");
}

// main function
public static void main(String[] args)
{
Geeks geek = new Geeks();
}
}
Output
Constructor Called
Note: It is not necessary to write a constructor for a class. It is because the java
compiler creates a default constructor (constructor with no arguments) if your
class doesn’t have any.

How Java Constructors are Different From Java Methods?


 Constructors must have the same name as the class within which it is defined it is not
necessary for the method in Java.
 Constructors do not return any type while method(s) have the return type or void if does
not return any value.
 Constructors are called only once at the time of Object creation while method(s) can be
called any number of times.
Now let us come up with the syntax for the constructor being invoked at the time of object or
instance creation.
class Geek
{
.......
// A Constructor
Geek() {
}
.......
}
// We can create an object of the above class
// using the below statement. This statement
// calls above constructor.
Geek obj = new Geek();
The first line of a constructor is a call to super() or this(), (a call to a constructor of a super-class
or an overloaded constructor), if you don’t type in the call to super in your constructor the
compiler will provide you with a non-argument call to super at the first line of your code, the
super constructor must be called to create an object:
If you think your class is not a subclass it actually is, every class in Java is the subclass of a
class object even if you don’t say extends object in your class definition.
Need of Constructors in Java
Think of a Box. If we talk about a box class then it will have some class variables (say length,
breadth, and height). But when it comes to creating its object(i.e Box will now exist in the
computer’s memory), then can a box be there with no value defined for its dimensions? The
answer is N o .
So constructors are used to assign values to the class variables at the time of object creation,
either explicitly done by the programmer or by Java itself (default constructor).

When Java Constructor is called?


Each time an object is created using a new() keyword, at least one constructor (it could be the
default constructor) is invoked to assign initial values to the data members of the same class.
Rules for writing constructors are as follows:
 The constructor(s) of a class must have the same name as the class name in which it
resides.
 A constructor in Java can not be abstract, final, static, or Synchronized.
 Access modifiers can be used in constructor declaration to control its access i.e which
other class can call the constructor.
So by far, we have learned constructors are used to initialize the object’s state. Like methods , a
constructor also contains a collection of statements(i.e. instructions) that are executed at the
time of Object creation.

Types of Constructors in Java


Now is the correct time to discuss the types of the constructor, so primarily there are three types
of constructors in Java are mentioned below:
 Default Constructor
 Parameterized Constructor
 Copy Constructor

1. Default Constructor in Java


A constructor that has no parameters is known as default the constructor. A default constructor
is invisible. And if we write a constructor with no arguments, the compiler does not create a
default constructor. It is taken out. It is being overloaded and called a parameterized constructor.
The default constructor changed into the parameterized constructor. But Parameterized
constructor can’t change the default constructor. The default constructor can be implicit or
explicit. If we don’t define explicitly, we get an implicit default constructor. If we manually
write a constructor, the implicit one is overridded.
Example:
// Java Program to demonstrate
// Default Constructor
import java.io.*;

// Driver class
class GFG {

// Default Constructor
GFG() { System.out.println("Default constructor"); }

// Driver function
public static void main(String[] args)
{
GFG hello = new GFG();
}
}
Output
Default constructor
Note: Default constructor provides the default values to the object like 0, null,
etc. depending on the type.
2. Parameterized Constructor in Java
A constructor that has parameters is known as parameterized constructor. If we want to
initialize fields of the class with our own values, then use a parameterized constructor.
Example:
// Java Program for Parameterized Constructor
import java.io.*;
class Geek {
// data members of the class.
String name;
int id;
Geek(String name, int id)
{
this.name = name;
this.id = id;
}
}
class GFG {
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
Geek geek1 = new Geek("Avinash", 68);
System.out.println("GeekName :" + geek1.name
+ " and GeekId :" + geek1.id);
}
}
Output
GeekName :Avinash and GeekId :68
Remember: Does constructor return any value?
There are no “return value” statements in the constructor, but the constructor
returns the current class instance. We can write ‘return’ inside a constructor.
Now the most important topic that comes into play is the strong incorporation of OOPS with
constructors known as constructor overloading. Just like methods, we can overload constructors
for creating objects in different ways. The compiler differentiates constructors on the basis of
the number of parameters, types of parameters, and order of the parameters.
Example:
// Java Program to illustrate constructor overloading
// using same task (addition operation ) for different
// types of arguments.

import java.io.*;

class Geek {
// constructor with one argument
Geek(String name)
{
System.out.println("Constructor with one "
+ "argument - String : " + name);
}

// constructor with two arguments


Geek(String name, int age)
{

System.out.println(
"Constructor with two arguments : "
+ " String and Integer : " + name + " " + age);
}

// Constructor with one argument but with different


// type than previous..
Geek(long id)
{
System.out.println(
"Constructor with one argument : "
+ "Long : " + id);
}
}

class GFG {
public static void main(String[] args)
{
// Creating the objects of the class named 'Geek'
// by passing different arguments

// Invoke the constructor with one argument of


// type 'String'.
Geek geek2 = new Geek("Shikhar");

// Invoke the constructor with two arguments


Geek geek3 = new Geek("Dharmesh", 26);

// Invoke the constructor with one argument of


// type 'Long'.
Geek geek4 = new Geek(325614567);
}
}
Output
Constructor with one argument - String : Shikhar
Constructor with two arguments : String and Integer : Dharmesh 26
Constructor with one argument : Long : 325614567
3. Copy Constructor in Java
Unlike other constructors copy constructor is passed with another object which copies the data
available from the passed object to the newly created object.
Note: In Java,there is no such inbuilt copy constructor available like in other
programming languages such as C++, instead we can create our own copy
constructor by passing the object of the same class to the other instance(object)
of the class.
Example:
// Java Program for Copy Constructor
import java.io.*;

class Geek {
// data members of the class.
String name;
int id;

// Parameterized Constructor
Geek(String name, int id)
{
this.name = name;
this.id = id;
}

// Copy Constructor
Geek(Geek obj2)
{
this.name = obj2.name;
this.id = obj2.id;
}
}
class GFG {
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
System.out.println("First Object");
Geek geek1 = new Geek("Avinash", 68);
System.out.println("GeekName :" + geek1.name
+ " and GeekId :" + geek1.id);

System.out.println();

// This would invoke the copy constructor.


Geek geek2 = new Geek(geek1);
System.out.println(
"Copy Constructor used Second Object");
System.out.println("GeekName :" + geek2.name
+ " and GeekId :" + geek2.id);
}
}
Output
First Object
GeekName :Avinash and GeekId :68

Copy Constructor used Second Object


GeekName :Avinash and GeekId :68

Java Methods
The method in Java or Methods of Java is a collection of statements that perform some specific
tasks and return the result to the caller. A Java method can perform some specific tasks without
returning anything. Java Methods allows us to reuse the code without retyping the code. In Java,
every method must be part of some class that is different from languages like C, C++, and Python.
 A method is like a function i.e. used to expose the behavior of an object.
 It is a set of codes that perform a particular task.
Syntax of Method:
<access_modifier> <return_type> <method_name>( list_of_parameters)
{
//body
}
Advantage of Method:
 Code Reusability
 Code Optimization
Note: Methods are time savers and help us to reuse the code without retyping the
code.
To deepen your understanding of Java methods and learn how to effectively implement them in
your programs, you might consider exploring structured learning resources or comprehensive
Java Programming Online courses designed to enhance your coding skills and knowledge.

Method Declaration
In general, method declarations have 6 components:
1. Modifier: It defines the access type of the method i.e. from where it can be accessed in your
application. In Java, there 4 types of access specifiers.
 public: It is accessible in all classes in your application.
 protected: It is accessible within the class in which it is defined and in its subclasses.
 private: It is accessible only within the class in which it is defined.
 default: It is declared/defined without using any modifier. It is accessible within the same
class and package within which its class is defined.
Note: It is Optional in syntax.
2. The return type: The data type of the value returned by the method or void if does not return a
value. It is Mandatory in syntax.
3. Method Name: the rules for field names apply to method names as well, but the convention is
a little different. It is Mandatory in syntax.
4. Parameter list: Comma-separated list of the input parameters is defined, preceded by their
data type, within the enclosed parenthesis. If there are no parameters, you must use empty
parentheses (). It is Optional in syntax.
5. Exception list: The exceptions you expect by the method can throw; you can specify these
exception(s). It is Optional in syntax.
6. Method body: it is enclosed between braces. The code you need to be executed to perform
your intended operations. It is Optional in syntax.

Types of Methods in Java


There are two types of methods in Java:
1. Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built-in method.
We can directly use these methods just by calling them in the program at any point.
2. User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
Ways to Create Method in Java
There are two ways to create a method in Java:
1. Instance Method: Access the instance data using the object name. Declared inside a class.
Syntax:
// Instance Method
void method_name(){
body // instance area
}

2. Static Method: Access the static data using class name. Declared inside class
with static keyword.
Syntax:
//Static Method
static void method_name(){
body // static area
}

Method Signature:
It consists of the method name and a parameter list (number of parameters, type of the parameters,
and order of the parameters). The return type and exceptions are not considered as part of it.
Method Signature of the above function:
max(int x, int y) Number of parameters is 2, Type of parameter is int.

Naming a Method
In Java language method name is typically a single word that should be a verb in lowercase or a
multi-word, that begins with a verb in lowercase followed by an adjective, noun. After the first
word, the first letter of each word should be capitalized.

Rules to Name a Method:


 While defining a method, remember that the method name must be a verb and start with
a lowercase letter.
 If the method name has more than two words, the first name must be a verb followed by
an adjective or noun.
 In the multi-word method name, the first letter of each word must be in uppercase except
the first word. For example, findSum, computeMax, setX, and getX.
Generally, a method has a unique name within the class in which it is defined but sometimes a
method might have the same name as other method names within the same class as method
overloading is allowed in Java .

Method Calling
The method needs to be called for use its functionality. There can be three situations when a
method is called:
A method returns to the code that invoked it when:
 It completes all the statements in the method.
 It reaches a return statement.
 Throws an exception.
Example:
// Java Program to Illustrate Methods

// Importing required classes


import java.io.*;

// Class 1
// Helper class
class Addition {

// Initially taking sum as 0


// as we have not started computation
int sum = 0;

// Method
// To add two numbers
public int addTwoInt(int a, int b)
{

// Adding two integer value


sum = a + b;

// Returning summation of two values


return sum;
}
}
// Class 2
// Helper class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating object of class 1 inside main() method


Addition add = new Addition();

// Calling method of above class


// to add two integer
// using instance created
int s = add.addTwoInt(1, 2);

// Printing the sum of two numbers


System.out.println("Sum of two integer values :"
+ s);
}
}
Output
Sum of two integer values :3

Passing Parameters to a method


There are some cases when we don’t know the number of parameters to be passed or an
unexpected case to use more parameters than declared number of parameters. In such cases we
can use
 Passing Array as an Argument
 Passing Variable-arguments as an Argument
 Method Overloading.

Memory Allocation for Methods Calls


Methods calls are implemented through a stack. Whenever a method is called a stack frame is
created within the stack area and after that, the arguments passed to and the local variables and
value to be returned by this called method are stored in this stack frame and when execution of
the called method is finished, the allocated stack frame would be deleted. There is a stack
pointer register that tracks the top of the stack which is adjusted accordingly.
Example: pseudo-code for implementing methods
// Define a class
public class Example {

// Define instance variables


private int number;
private String name;

// Define accessor (getter) methods


public int getNumber() {
return number;
}

public String getName() {


return name;
}
// Define mutator (setter) methods
public void setNumber(int number)
{
this.number = number;
}

public void setName(String name) { this.name = name; }

// Define other methods


public void printDetails()
{
System.out.println("Number: " + number);
System.out.println("Name: " + name);
}
}

There are several advantages to using methods in Java, including:


 Reusability : Methods allow you to write code once and use it many times, making your
code more modular and easier to maintain.
 Abstraction : Methods allow you to abstract away complex logic and provide a simple
interface for others to use. This makes your code more readable and easier to understand.
 Improved readability : By breaking up your code into smaller, well-named methods,
you can make your code more readable and easier to understand.
 Encapsulation : Methods allow you to encapsulate complex logic and data, making it
easier to manage and maintain.
 Separation of concern s: By using methods, you can separate different parts of your
code and assign different responsibilities to different methods, improving the structure and
organization of your code.
 Improved modularity : Methods allow you to break up your code into smaller, more
manageable units, improving the modularity of your code.
 Improved testability : By breaking up your code into smaller, more manageable units,
you can make it easier to test and debug your code.
 Improved performance: By organizing your code into well-structured methods, you
can improve performance by reducing the amount of code that needs to be executed and by
making it easier to cache and optimize your code.
1. Static Block
 A static block is a block of code inside a class that is executed once when the class is
loaded into memory by the Java Virtual Machine (JVM).
 It is used for static initialization of variables or for executing code that should run before
the creation of any objects or invocation of static methods.
class StaticBlockExample {
static int num;

// Static block
static {
num = 10;
System.out.println("Static block executed. num = " + num);
}

public static void main(String[] args) {


System.out.println("Main method executed.");
System.out.println("Value of num: " + num);
}
}
Output:
Static block executed. num = 10
Main method executed.
Value of num: 10

Static Data
 Static data (or static variables) are variables declared with the static keyword.
 They belong to the class rather than any specific instance.
 All objects of the class share the same copy of the static variable.
class StaticDataExample {
static int counter = 0;

StaticDataExample() {
counter++;
}

public static void displayCounter() {


System.out.println("Counter: " + counter);
}

public static void main(String[] args) {


StaticDataExample obj1 = new StaticDataExample();
StaticDataExample obj2 = new StaticDataExample();
StaticDataExample obj3 = new StaticDataExample();

StaticDataExample.displayCounter(); // Access static variable


}
}
Output:
Counter: 3

Static Method
 A static method is a method that is associated with the class rather than any object of the
class.
 It can be called without creating an object of the class.
 Static methods can only access other static members (variables or methods).
Example:
class StaticMethodExample {
static int add(int a, int b) {
return a + b;
}

public static void main(String[] args) {


int result = StaticMethodExample.add(10, 20);
System.out.println("Sum: " + result);
}
}
Output:
Sum: 30

String Class
 The String class is used to create and manipulate immutable strings in Java.
 Strings created using the String class cannot be modified (immutable).
class StringExample {
public static void main(String[] args) {
String str = "Hello, Java!";
System.out.println("String length: " + str.length());
System.out.println("Character at index 4: " + str.charAt(4));
System.out.println("Substring: " + str.substring(7));
System.out.println("Uppercase: " + str.toUpperCase());
}
}
Output:
String length: 12
Character at index 4: o
Substring: Java!
Uppercase: HELLO, JAVA!

StringBuffer Class
 The StringBuffer class is used to create and manipulate mutable strings.
 It is thread-safe because its methods are synchronized.
class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
sb.append(", Java!"); // Append to the string
System.out.println("After append: " + sb);

sb.insert(5, " World"); // Insert into the string


System.out.println("After insert: " + sb);

sb.replace(0, 5, "Hi"); // Replace a portion of the string


System.out.println("After replace: " + sb);

sb.delete(3, 8); // Delete a portion of the string


System.out.println("After delete: " + sb);
}
}
Output:
After append: Hello, Java!
After insert: Hello World, Java!
After replace: Hi World, Java!
After delete: HiJava!
Comparison Between String and StringBuffer:
Feature String StringBuffer
Mutability Immutable Mutable
Thread Safety Not thread-safe Thread-safe
Performance Faster for small data Slower due to synchronization
Use Cases Fixed content Dynamic content manipulatio

You might also like