0% found this document useful (0 votes)
34 views45 pages

Java Virtual Machine and Data Types Guide

The document provides an overview of the Java Virtual Machine (JVM) and Java data types, including primitive and non-primitive types, along with examples of each. It also covers variables, keywords, and various operators such as arithmetic, unary, assignment, relational, logical, and ternary operators in Java. The document includes code examples to illustrate the usage of these concepts.

Uploaded by

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

Java Virtual Machine and Data Types Guide

The document provides an overview of the Java Virtual Machine (JVM) and Java data types, including primitive and non-primitive types, along with examples of each. It also covers variables, keywords, and various operators such as arithmetic, unary, assignment, relational, logical, and ternary operators in Java. The document includes code examples to illustrate the usage of these concepts.

Uploaded by

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

UNIT-I

Java Virtual Machine


The Java Virtual Machine (JVM) is a core
component of the Java Runtime Environment (JRE) that
allows Java programs to run on any platform without
modification. JVM, or Java Virtual Machine, is a virtual
machine that allows a computer to run Java programs by
interpreting and executing Java bytecode

 Part of both JDK and JRE.


 Performs memory management and garbage collection.
 Provides portability by executing the same bytecode on
different platforms.

Data types
Data types in Java are of different sizes and values that
can be stored in a variable that is made as per convenience
and circumstances to handle different scenarios or data
requirements.

Java Data Type Categories


1. Primitive Data Type: These are the basic building blocks
that store simple values directly in memory. Examples of
primitive data types are boolean, char, byte, short, int, long,
float and double.
2. Non-Primitive Data Types (Object Types): These are
reference types that store memory addresses of objects.
Examples of Non-primitive data types are String, Array,
Class, Interface and Object
Exampl
Descripti Defau e
Type on lt Size Literals Range of values

JVM-
depende
true,
true or false false nt true, false
boolea (typically
false
n 1 byte)

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

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

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

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

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

32-bit IEEE
3.14f, - ~6-7 significant
754 floating- 0.0f 4 bytes
1.23e-10f decimal digits
float point
Exampl
Descripti Defau e
Type on lt Size Literals Range of values

64-bit IEEE 3.1415d,


~15-16 significant
754 floating- 0.0d 8 bytes 1.23e100
decimal digits
double point d

1. Boolean Data Type


The boolean data type represents a logical value that can be
either true or false. Conceptually, it represents a single bit of
information, but the actual size used by the virtual machine is
implementation-dependent and typically at least one byte
(eight bits) in practice. Values of the boolean type are not
implicitly or explicitly converted to any other type using casts.
However, programmers can write conversion code if needed.
Syntax:
boolean booleanVar;
Size : Virtual machine dependent (typically 1 byte, 8 bits)
Example: This example, demonstrating how to use boolean
data type to display true/false values.
// Demonstrating boolean data type
public class Geeks {
public static void main(String[] args) {
boolean b1 = true;
boolean b2 = false;

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


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

Output
Is Java fun? true
Is fish tasty? false

2. Byte Data Type


The byte data type is an 8-bit signed two's complement
integer. The byte data type is useful for saving memory in
large arrays.
Syntax:
byte byteVar;
Size : 1 byte (8 bits)
Example: This example, demonstrating how to use byte data
type to display small integer values.
// Demonstrating byte data type
public class Geeks {
public static void main(String[] args) {
byte a = 25;
byte t = -10;

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


[Link]("Temperature: " + t);
}
}

Output
Age: 25
Temperature: -10

3. Short Data Type


The short data type is a 16-bit signed two's complement
integer. Similar to byte, a short is used when memory savings
matter, especially in large arrays where space is constrained.
Syntax:
short shortVar;
Size : 2 bytes (16 bits)
Example: This example, demonstrates how to use short data
type to store moderately small integer value.
//Demonstrating short data types
public class Geeks {
public static void main(String[] args) {
short num = 1000;
short t = -200;

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


[Link]("Temperature: " + t);
}
}

Output
Number of Students: 1000
Temperature: -200

4. Int Data Type


It is a 32-bit signed two's complement integer.
Syntax:
int intVar;
Size : 4 bytes ( 32 bits )
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.
Example: This example demonstrates how to use int data
type to display larger integer values.
// Demonstrating int data types
public class Geeks {
public static void main(String[] args) {
int p = 2000000;
int d = 150000000;

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


[Link]("Distance: " + d);
}
}

5. Long Data Type


The long data type is a 64-bit signed two's complement
integer. It is used when an int is not large enough to hold a
value, offering a much broader range.
Syntax:
long longVar;
Size : 8 bytes (64 bits)
Remember: In Java SE 8 and later, you can use the long data
type to represent an unsigned 64-bit long, which has a
minimum value of 0 and a maximum value of 2 64 -1. The Long
class also contains methods like comparing Unsigned, divide
Unsigned, etc to support arithmetic operations for unsigned
long.
Example: This example demonstrates how to use long data
type to store large integer value.
// Demonstrating long data type
public class Geeks {
public static void main(String[] args) {
long w = 7800000000L;
long l = 9460730472580800L;

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


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

6. Float Data Type


The float data type is a single-precision 32-bit IEEE 754
floating-point. Use a float (instead of double) if you need to
save memory in large arrays of floating-point numbers. The
size of the float data type is 4 bytes (32 bits).
Syntax:
float floatVar;
Size : 4 bytes (32 bits)
Example: This example demonstrates how to use float data
type to store decimal value.
// Demonstrating float data type
public class Geeks {
public static void main(String[] args) {
float pi = 3.14f;
float gravity = 9.81f;

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


[Link]("Gravity: " + gravity);
}
}

Output
Value of Pi: 3.14
Gravity: 9.81
7. Double Data Type
The double data type is a double-precision 64-bit IEEE 754
floating-point. For decimal values, this data type is generally
the default choice. The size of the double data type is 8 bytes
or 64 bits.
Syntax:
double doubleVar;
Size : 8 bytes (64 bits)
Note: Both float and double data types were designed
especially for scientific calculations, where approximation
errors are acceptable. If accuracy is the most prior concern
then, it is recommended not to use these data types and use
BigDecimal class instead.
It is recommended to go through rounding off errors in java.
Example: This example demonstrates how to use double data
type to store precise decimal value.
// Demonstrating double data type
public class Geeks {
public static void main(String[] args) {
double pi = 3.141592653589793;
double an = 6.02214076e23;

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


[Link]("Avogadro's Number: " + an);
}
}

Output
Value of Pi: 3.141592653589793
Avogadro's Number: 6.02214076E23
8. Char Data Type
The char data type is a single 16-bit Unicode character with
the size of 2 bytes (16 bits).
Syntax:
char charVar;
Size : 2 bytes (16 bits)
Example: This example, demonstrates how to use char data
type to store individual characters.
// Demonstrating char data type
public class Geeks{
public static void main(String[] args) {
char g = 'A';
char s = '$';

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


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

Output
Grade: A
Symbol: $

Variables
A variables are containers used to store data in memory.
Variables define how data is stored, accessed, and
manipulated.
A variable in Java has three components,
 Data Type: Defines the kind of data stored (e.g., int, String,
float).
 Variable Name: A unique identifier following Java naming
rules.
 Value: The actual data assigned to the variable.

Syntax
type variableName = value;

eg:
public class Main {
public static void main(String[] args) {
String name = "John";
[Link](name);
}
}
Output:
John

Rules to Name Java Variables


 Start with a Letter, $, or _ – Variable names must begin
with a letter (a–z, A–Z), dollar sign $, or underscore _.
 No Keywords: Reserved Java keywords (e.g., int, class, if)
cannot be used as variable names.
 Case Sensitive: age and Age are treated as different
variables.
 Use Letters, Digits, $, or _ : After the first character, you
can use letters, digits (0–9), $, or _.
 Meaningful Names: Choose descriptive names that reflect
the purpose of the variable (e.g., studentName instead of
s).
 No Spaces: Variable names cannot contain spaces.
 Follow Naming Conventions: Typically, use camelCase
for variable names in Java (e.g., totalMarks).
Keywords
The keywords are the reserved words that have some
predefined meanings and are used by the Java compiler for
some internal process or represent some predefined actions.
These words cannot be used as identifiers such
as variable names, method names, class names, or object
names.

// Java Program to demonstrate Keywords

class Geeks {

public static void main(String[] args)

// Using final and int keyword

final int x = 10;

// Using if and else keywords


if(x > 10){

[Link]("Failed");

else {

[Link]("Successful demonstration"

+" of keywords.");
}
}
Output
Successful demonstration of keywords.

Operators
1. Arithmetic Operators
Arithmetic Operators are used to perform simple arithmetic
operations on primitive and non-primitive data types.
public class GFG{
public static void main(String[] args) {
int a = 10, b = 3;
// Addition
int sum = a + b;
// Subtraction
int diff = a - b;
// Multiplication
int mul = a * b;
// Division
int div = a / b;
// Modulus
int mod = a % b; // Modulus

[Link]("Sum: " + sum);


[Link]("Difference: " + diff);
[Link]("Multiplication: " + mul);
[Link]("Division: " + div);
[Link]("Modulus: " + mod);
}
}
Output
Sum: 13
Difference: 7
Multiplication: 30
Division: 3
Modulus: 1

2. Unary Operators
Unary Operators need only one operand. They are used to
increment, decrement, or negate a value.
import [Link].*;

// Driver Class
class Geeks{

public static void main(String[] args){


// Interger declared
int a = 10;
int b = 10;

// Using unary operators


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

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


[Link]("Predecrement : " + (--b));
}
}

Output
Postincrement : 10
Preincrement : 12
Postdecrement : 10
Predecrement : 8

3. Assignment Operator
The assignment operator assigns a value from the right-hand
side to a variable on the left. Since it has right-to-left
associativity, the right-hand value must be declared or
constant.
public class GFG{
public static void main(String[] args){
int n = 10;
// n = n + 5
n += 5;
[Link]("After += : " + n);
// n = n * 2
n *= 2;
[Link]("After *= : " + n);
// n = n - 5
n -= 5;
[Link]("After -= : " + n);
// n = n / 2
n /= 2;
[Link]("After /= : " + n);
// n = n % 3
n %= 3;
[Link]("After %= : " + n);
}
}

Output
After += : 15
After *= : 30
After -= : 25
After /= : 12
After %= : 0

Note: Use compound assignments (+=, -=) for cleaner code.


4. Relational Operators
Relational 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.
import [Link].*;

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

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


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

Output
a > b: true
a < b: false
a >= b: true
a <= b: false
a == c: false
a != c: true

5. Logical Operators
Logical Operators are used to perform "logical AND" and
"logical OR" operations, similar to AND gate and OR gate in
digital electronics. They have a short-circuiting effect, meaning
the second condition is not evaluated if the first is false.
import [Link].*;

class Geeks {
// Main Function
public static void main (String[] args) {
// Logical operators
boolean x = true;
boolean y = false;
[Link]("x && y: " + (x && y));
[Link]("x || y: " + (x || y));
[Link]("!x: " + (!x));
}
}

Output
x && y: false
x || y: true
!x: false

6. Ternary operator
The Ternary Operator is a shorthand version of the if-else
statement. It has three operands and hence the name Ternary.
The general format is,
public class Geeks{
public static void main(String[] args){
int a = 20, b = 10, c = 30, result;

// result holds max of three


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

Output
Max of three numbers = 30

7. Bitwise Operators
These operators perform operations at the bit level.
 Bitwise Operators manipulate individual bits using AND,
OR, XOR, and NOT.
 Shift Operators move bits to the left or right, effectively
multiplying or dividing by powers of two.

import [Link].*;

class Geeks
{
public static void main(String[] args)
{
// Bitwise operators
int d = 0b1010;
int e = 0b1100;
[Link]("d & e : " + (d & e));
[Link]("d | e : " + (d | e));
[Link]("d ^ e : " + (d ^ e));
[Link]("~d : " + (~d));
[Link]("d << 2 : " + (d << 2));
[Link]("e >> 1 : " + (e >> 1));
[Link]("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. instanceof Operator
The instanceof operator is used for type checking. It can be
used to test if an object is an instance of a class, a subclass,
or an interface. The general format,
public class GFG{
public static void main(String[] args){
String str = "Hello";
[Link](str instanceof String);

Object obj = new Integer(10);


[Link](obj instanceof Integer);
[Link](obj instanceof String);
}
}
Output
true
true
false
Expression
An expression is a combination of operators, constants
and variables. An expression may consist of one or more
operands, and zero or more operators to produce a value.

Types of Expressions: Expressions may be of the following


types:

Constant expressions: Constant Expressions consists of
only constant values. A constant value is one that doesn't
change. Examples:
5, 10 + 5 / 6.0, 'x’

 Integral expressions: Integral Expressions are those


which produce integer results after implementing all the
automatic and explicit type conversions. Examples:
x, x * y, x + int( 5.0)

where x and y are integer variables.


 Floating expressions: Float Expressions are which
produce floating point results after implementing all the
automatic and explicit type conversions. Examples:
x + y, 10.75

where x and y are floating point variables.


 Relational expressions: Relational Expressions yield
results of type bool which takes a value true or false. When
arithmetic expressions are used on either side of a
relational operator, they will be evaluated first and then the
results compared. Relational expressions are also known
as Boolean expressions. Examples:
x <= y, x + y > 2

 Logical expressions: Logical Expressions combine two or


more relational expressions and produces bool type
results. Examples:
x > y && x == 10, x == 10 || y == 5

 Pointer expressions: Pointer Expressions produce


address values. Examples:
&x, ptr, ptr++

where x is a variable and ptr is a pointer.


 Bitwise expressions: Bitwise Expressions are used to
manipulate data at bit level. They are basically used for
testing or shifting bits. Examples:
x << 3

shifts three bit position to left


y >> 1

shifts one bit position to right. Shift operators are often used
for multiplication and division by powers of two.

control statements
Conditions and if statements let you control the flow of your
program - deciding which code runs, and which code is skipped.

Java has the following conditional statements:

 Use if to specify a block of code to be executed, if a


specified condition is true
 Use else to specify a block of code to be executed, if the
same condition is false
 Use else if to specify a new condition to test, if the first
condition is false
 Use switch to specify many alternative blocks of code to
be executed

if Statement
The if statement is the simplest decision-making statement. It
executes a block of code only if a given condition is true.

Syntax
if (condition) {
// block of code to be executed if the condition is
true
}

PROGRAM
public class Main {
public static void main(String[] args) {
boolean isRaining = true;

if (isRaining) {
[Link]("Bring an umbrella!");
}
}
}
OUTPUT
Bring an umbrella!
else Statement
The else statement lets you run a block
of code when the condition in
the if statement is false.
Syntax
if (condition) {
} else {
}
program
public class Main {

public static void main(String[] args) {

boolean isRaining = false;

if (isRaining) {

[Link]("Bring an umbrella!");

} else {

[Link]("No rain today, no need for an


umbrella!");

}
}
Output
No rain today, no need for an umbrella!
If ... Else
The if-else statement in Java is a fundamental control flow
structure used to execute different blocks of code based on whether a
specified condition evaluates to true or false
SYNTAX

if (condition) {

} else {

}
PROGRAM

public class IfElseExample {

public static void main(String[] args) {

int age = 20;

if (age >= 18) {

[Link]("You are an adult.");

} else {

[Link]("You are a minor.");

}
}
OUTPUT
You are an adult.

The else if Statement


The if-else statement will perform some action for a
specific condition. If the condition meets then a particular code
of action will be executed otherwise it will execute another
code of action that satisfies that particular condition.

Syntax
if (condition1) {

} else if (condition2) {

} else if (condition3) {

} else {

}
program

public class Main {

public static void main(String[] args) {

int weather = 2; // 1 = raining, 2 = sunny, 3 = cloudy

if (weather == 1) {

[Link]("Bring an umbrella.");

} else if (weather == 2) {
[Link]("Wear sunglasses.");

} else {

[Link]("Just go outside normally.");

}
}
Output
Wear sunglasses.

Switch Statements
The switch statement in Java is a multi-way
branch statement. In simple words, the Java switch
statement executes one statement from multiple
conditions.
SYNTAX
switch (expression) {

case value1:

break;

case value2:

break

default:

program
public class Main {

public static void main(String[] args) {

int day = 4;

switch (day) {

case 1:

[Link]("Monday");

break;

case 2:

[Link]("Tuesday");

break;

case 3:

[Link]("Wednesday");

break;

case 4:

[Link]("Thursday");

break;

case 5:

[Link]("Friday");

break;

case 6:
[Link]("Saturday");

break;

case 7:

[Link]("Sunday");

break;

Output

Thursday

CLASS
 A class is a template to create objects having
similar properties and behavior, or in other words,
we can say that a class is a blueprint for objects.

 A class in Java is a template with the help of which


we create real-world entities known as objects that
share common characteristics and properties.
PROGRAM

class Student {

int id;

String n;

// Added constructor to initialize both fields

public Student(int id, String n) {

[Link] = id;

this.n = n;

}
public class Main {

public static void main(String[] args) {

// Creating Student object using the new constructor

Student s1 = new Student(10, "Alice");

[Link]([Link]);

[Link](s1.n);

OUTPUT

10

Alice

OBJECT
Objects are the instances of a class that are created to
use the attributes and methods of a class. A typical
Java program creates many objects, which as you
know, interact by invoking methods. An object consists
of:
 State: It is represented by attributes of an object.
It also reflects the properties of an object.
 Behavior: It is represented by the methods of an
object. It also reflects the response of an object
with other objects.
 Identity: It gives a unique name to an object and
enables one object to interact with other objects.

Constructors
A constructor is a special method that initializes an
object and is automatically called when a class
instance is created using new. It is used to set default
or user-defined values for the object's attributes
 A constructor has the same name as the class.

 It does not have a return type, not even void.

 It can accept parameters to initialize object

properties.
Types of Constructors in Java
There are Four types of constructors in Java
1. Default Constructor
A default constructor has no parameters. It’s used to
assign default values to an object. If no constructor is
explicitly defined, Java provides a default constructor.
import [Link].*;

class Geeks{

// Default Constructor
Geeks(){
[Link]("Default constructor");
}
public static void main(String[] args){
Geeks hello = new Geeks();
}
}
Output
Default constructor

Note: It is not necessary to write a constructor for a


class because the Java compiler automatically creates
a default constructor (a constructor with no
arguments) if your class doesn’t have any.
2. Parameterized Constructor
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.
import [Link].*;

class Geeks{
// data members of the class
String name;
int id;
Geeks(String name, int id){
[Link] = name;
[Link] = id;
}
}

class GFG{
public static void main(String[] args){
// This would invoke the parameterized constructor
Geeks geek1 = new Geeks("Sweta", 68);
[Link]("GeekName: " + [Link]
+ " and GeekId: " + [Link]);
}
}

Output
GeekName: Sweta and GeekId: 68

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.
import [Link].*;

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

// Parameterized Constructor
Geeks(String name, int id)
{
[Link] = name;
[Link] = id;
}

// Copy Constructor
Geeks(Geeks obj2)
{
[Link] = [Link];
[Link] = [Link];
}
}

class GFG {
public static void main(String[] args)
{
// This would invoke the parameterized constructor
[Link]("First Object");
Geeks geek1 = new Geeks("Sweta", 68);
[Link]("GeekName: " + [Link]
+ " and GeekId: " + [Link]);

[Link]();

// This would invoke the copy constructor


Geeks geek2 = new Geeks(geek1);
[Link](
"Copy Constructor used Second Object");
[Link]("GeekName: " + [Link]
+ " and GeekId: " + [Link]);
}
}

Output
First Object

GeekName: Sweta and GeekId: 68

Copy Constructor used Second Object

GeekName: Sweta and GeekId: 68


Note: Java does not provide a built-in copy
constructor like C++. We can create our own by
writing a constructor that takes an object of the same
class as a parameter and copies its fields.
4. Private Constructor
A private constructor cannot be accessed from outside
the class. It is commonly used in:
 Singleton Pattern : To ensure only one instance of

a class is created.
 Utility/Helper Classes: To prevent instantiation of

a class containing only static methods.


class GFG {

// Private constructor
private GFG(){
[Link]("Private constructor called");
}

// Static method
public static void displayMessage(){
[Link]("Hello from GFG class!");
}
}

class Main{
public static void main(String[] args){
// GFG u = new GFG(); // Error: constructor is
// private
[Link]();
}
}

Output
Hello from GFG class!

Access control
Access control in Java is managed through access modifiers,
which define the visibility and accessibility of classes, fields,
methods, and constructors. There are four main access
modifiers:
 private :
 Scope: Accessible only within the declaring class.
 Purpose: Primarily used for encapsulation, ensuring internal
state is protected and only modified through designated
methods.
default (package-private):

 Scope: Accessible only within the same package.


 Purpose: Useful for grouping related classes that need to
interact but should not be exposed globally. This is the default if
no access modifier is specified.
protected:

 Scope: Accessible within the same package and by subclasses


(even if in different packages).
 Purpose: Designed for inheritance, allowing subclasses to
access and potentially modify inherited members while
maintaining some level of restriction for unrelated classes.
public:
 Scope: Accessible from anywhere (any class in any package).
 Purpose: Used for components that need to be universally
accessible, such as APIs or utility classes.
Example Program:
Program
package [Link].package1;

public class ParentClass {


private String privateData = "Private to
ParentClass";
String defaultData = "Default (package-
private) to package1";
protected String protectedData = "Protected
to package1 and subclasses";
public String publicData = "Public to
everyone";

private void privateMethod() {


[Link](privateData);
}

void defaultMethod() {
[Link](defaultData);
}

protected void protectedMethod() {


[Link](protectedData);
}

public void publicMethod() {


[Link](publicData);
privateMethod();
}
}

Method Overloading
In Java, Method Overloading allows a class to have
multiple methods with the same name but different
parameters, enabling compile-time (static)
polymorphism.
 Methods can share the same name if their

parameter lists differ.


 Cannot overload by return type alone; parameters

must differ.
 The compiler chooses the most specific match

when multiple methods could apply.


The different ways of method overloading in Java are
mentioned below:
1. Changing the Number of Parameters
Method overloading can be achieved by changing the
number of parameters while passing to different
methods.
import [Link].*;

class Product{
// Multiplying two integer values
public int multiply(int a, int b){
int prod = a * b;
return prod;
}
// Multiplying three integer values
public int multiply(int a, int b, int c){
int prod = a * b * c;
return prod;
}
}

class Geeks{
public static void main(String[] args)
{
Product ob = new Product();

// Calling method to Multiply 2 numbers


int prod1 = [Link](1, 2);

// Printing Product of 2 numbers


[Link](
"Product of the two integer value: " + prod1);

// Calling method to multiply 3 numbers


int prod2 = [Link](1, 2, 3);

// Printing product of 3 numbers


[Link](
"Product of the three integer value: " + prod2);
}
}

Output
Product of the two integer value: 2
Product of the three integer value: 6

Explanation:
 Two methods have the same name but different

number of parameters.
 Compiler selects the correct method based on how

many arguments are passed.


2. Changing Data Types of Parameters
In many cases, methods can be considered
overloaded if they have the same name but have
different parameter types, methods are considered to
be overloaded.
class Product{
public int prod(int a, int b, int c){
return a * b * c;
}
public double prod(double a, double b, double c){
return a * b * c;
}
}

public class Geeks {


public static void main(String[] args){
Product p = new Product();
[Link]([Link](1, 2, 3));
[Link]([Link](1.0, 2.0, 3.0));
}
}

Output
6

6.0

Explanation:
 Methods differ in parameter types (int vs double).

 Compiler matches the method based on the exact

data type of arguments.


3. Changing the Order of Parameters
Method overloading can also be implemented by
rearranging the parameters of two or more overloaded
methods.
class Student {

public void studentId(String name, int rollNo){

[Link]("Name: " + name


+ ", Roll-No: " + rollNo);
}
public void studentId(int rollNo, String name){
[Link]("Roll-No: " + rollNo
+ ", Name: " + name);
}
}

public class Geeks{


public static void main(String[] args){
Student s = new Student();
[Link]("Sweta", 1);
[Link](2, "Gudly");
}
}
Output
Name: Sweta, Roll-No: 1

Roll-No: 2, Name: Gudly

Arrays,
 Arrays in Java are objects, like all other objects in
Java, arrays implicitly inherit from the
[Link] class. This allows you to invoke
methods defined in Object (such as toString(),
equals() and hashCode()).
 Arrays have a built-in length property, which
provides the number of elements in the array
public class Geeks {
public static void main(String[] args)
{

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

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

// traversing array
for (int i = 0; i < n; i++)
[Link](arr[i] + " ");
}
}
Output
40 55 63 17 22

Key features of Arrays


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

You might also like