0% found this document useful (0 votes)
21 views57 pages

Introduction to Java Programming Basics

Java is a high-level, object-oriented programming language created in 1995, known for its platform independence and widespread use across various applications. It features a variety of data types, including primitive and non-primitive types, and supports different variable types such as local, instance, and static variables. The document also covers Java operators, including arithmetic, unary, and assignment operators, essential for performing operations in Java programs.

Uploaded by

manojkumar
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)
21 views57 pages

Introduction to Java Programming Basics

Java is a high-level, object-oriented programming language created in 1995, known for its platform independence and widespread use across various applications. It features a variety of data types, including primitive and non-primitive types, and supports different variable types such as local, instance, and static variables. The document also covers Java operators, including arithmetic, unary, and assignment operators, essential for performing operations in Java programs.

Uploaded by

manojkumar
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

Introduction to JAVA

What is Java?
Java is a popular programming language, created in 1995.
 Java is a high-level, object-oriented programming language developed by Sun
Microsystems (now owned by Oracle).
 It is platform-independent (Write Once, Run Anywhere - WORA) thanks to the
Java Virtual Machine (JVM).
It is owned by Oracle, and more than 3 billion devices run Java.
It is used for:
 Mobile applications (specially Android apps)
 Desktop applications
 Web applications
 Web servers and application servers
 Games
 Database connection

 Key Features of Java:


Feature Description
Simple Easy to learn and use.
Object-Oriented Everything is an object.
Platform Independent Java bytecode runs on any OS.
Secure Provides runtime security checks.
Robust Strong memory management.
Multithreaded Supports concurrent execution.

Structure of a Basic Java Program


java
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}

Explanation:

 public class HelloWorld: Defines a class.


 public static void main(String[] args): Entry point of any Java program.
 [Link](): Prints output to the console.

DATA TYPES
Java data types define the type and value range of the data for the different types of variables,
constants, method parameters, return types, etc. The data type tells the compiler about the type of data
to be stored and the required memory. To store and manipulate different types of data, all variables
must have specified data types.
Based on the data type of a variable, the operating system allocates memory and decides what can be
stored in the reserved memory. Therefore, by assigning different data types to variables, you can store
integers, decimals, or characters in these variables.

The Java data types are categorized into two main categories
 Primitive Data Types
 Reference/Object Data Types

Java Primitive Data Types


Primitive data types are predefined by the language and named by a keyword. There are eight
primitive data types supported by Java. Below is the list of the primitive data types:

 byte
 short
 int
 long
 float
 double
 boolean

byte Data Type


The byte data type is an 8-bit signed two's complement integer with a minimum value of -128 (-27)
and a maximum value of 127 (inclusive) (27 -1).

The default value of a byte variable is 0, which is used to save space in large arrays, which is mainly
beneficial in integers since a byte is four times smaller than an integer.

Example
byte a = 100;
byte b = -50;

short Data Type


The short data type is a 16-bit signed two's complement integer, which provides a range of values
from -32,768 (-215) to 32,767 (inclusive) (215 -1). Like the byte data type, the short data type is also
beneficial for saving memory, as it occupies less space compared to an integer, being only half the
size.

The default value for a short variable is 0.

Example
short s = 10000;
short r = -20000;
int Data Type
The int data type is a 32-bit signed two's complement integer, allowing for a wide range of values
from -2,147,483,648 (-231) to 2,147,483,647 (inclusive) (231 -1). Here the integer is generally used
as the default data type for integral values unless there is a concern about memory.

The default value for an int variable is 0.

Example
int a = 100000;
int b = -200000;

long Data Type


The long data type is a 64-bit signed two's complement integer, capable of representing a vast range
of values from -9,223,372,036,854,775,808 (-263) to 9,223,372,036,854,775,807 (inclusive) (263 -1).
This data type is used when a wider range than int is needed, where its default value is 0L.

Example
long a = 100000L;
long b = -200000L;

float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating-point representation. It is
particularly useful for saving memory in large arrays of floating-point numbers. Its default value is
0.0f. However, it's important to note that the float data type is not suitable for precise values, such as
currency, due to potential rounding errors in floating-point arithmetic.

Example
float f1 = 234.5f;

double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating-point representation, which is
generally used as the default data type for decimal values, generally the default choice. Double data
type should never be used for precise values such as currency, where its default value is 0.0d.

Example
double d1 = 123.4;

boolean Data Type


The boolean data type represents a single bit of information and can hold one of two possible values:
true or false. This data type is used for simple flags that track true/false conditions where its default
value is false.

Example
boolean one = true;

char Data Type


The char data type is a single 16-bit Unicode character, which represents a wide range of characters
from different languages and symbols. With a range '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).
This data type is primarily used to store individual characters.

Example
char letterA = 'A'

Java Non-Primitive (Reference/Object) Data Types


The non-primitive data types are not predefined. The reference data types are created using defined
constructors of the classes. They are used to access objects. These variables are declared to be of a
specific type that cannot be changed. For example, Employee, Puppy, etc.

The following are the non-primitive (reference/object) data types −

 String: The string is a class in Java, and it represents the sequences of characters.
 Arrays: Arrays are created with the help of primitive data types and store multiple values of
the same type.
 Classes: The classes are the user-defined data types and consist of variables and methods.
 Interfaces: The interfaces are abstract types that are used to specify a set of methods.

Java Variables
What is a Java Variable?

A variable provides us with named storage that our programs can manipulate. Each variable
in Java has a specific type, which determines the size and layout of the variable's memory;
the range of values that can be stored within that memory; and the set of operations that can
be applied to the variable.

Variable Declaration and Initialization


You must declare all variables before they can be used. Java variables are declared by specifying the
data type followed by the variable name. To assign a value, use the assignment (=) operator followed
by the value. Each declaration or initialization statement must end with a semicolon (;).

Syntax
Following is the basic form of a variable declaration −

data type variable [ = value][, variable [ = value] ...] ;


Here data type is one of Java's data types and variable is the name of the variable. To declare more
than one variable of the specified type, you can use a comma-separated list.
Example of Valid Variables Declarations and Initializations
Following are valid examples of variable declaration and initialization in Java −

int a, b, c; // Declares three ints, a, b, and c.


int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a iis initialized with value 'a'

Java Variables Types


The following are the three types of Java variables:

 Local variables
 Instance variables
 Class/Static variables
1. Java Local Variables
Local variables are declared in methods, constructors, or blocks.

Local variables are created when the method, constructor or block is entered and the variable will be
destroyed once it exits the method, constructor, or block.

Access modifiers cannot be used for local variables.

Local variables are visible only within the declared method, constructor, or block.

Local variables are implemented at stack level internally.

There is no default value for local variables, so local variables should be declared and an initial value
should be assigned before the first use.

Example 1: Variable's local scope with initialization


Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to only
this method.

Open Compiler
public class Test {
public void pupAge() {
int age = 0;
age = age + 7;
[Link]("Puppy age is : " + age);
}

public static void main(String args[]) {


Test test = new Test();
[Link]();
}
}
Output

Puppy age is: 7


Example 2: Variable's local scope without initialization
Following example uses age without initializing it, so it would give an error at the time of
compilation.

Open Compiler
public class Test {
public void pupAge() {
int age;
age = age + 7;
[Link]("Puppy age is : " + age);
}

public static void main(String args[]) {


Test test = new Test();
[Link]();
}
}
Output

[Link][Link]variable number might not have been initialized


age = age + 7;
^
1 error
2. Java Instance Variables
Instance variables are declared in a class, but outside a method, constructor or any block.

When a space is allocated for an object in the heap, a slot for each instance variable value is created.

Instance variables are created when an object is created with the use of the keyword 'new' and
destroyed when the object is destroyed.

Instance variables hold values that must be referenced by more than one method, constructor or block,
or essential parts of an object's state that must be present throughout the class.

Instance variables can be declared in class level before or after use.

Access modifiers can be given for instance variables.

The instance variables are visible for all methods, constructors and block in the class. Normally, it is
recommended to make these variables private (access level). However, visibility for subclasses can be
given for these variables with the use of access modifiers.

Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and
for object references it is null. Values can be assigned during the declaration or within the constructor.

Instance variables can be accessed directly by calling the variable name inside the class. However,
within static methods (when instance variables are given accessibility), they should be called using the
fully qualified name. [Link].
Example of Java Instance Variables
Open Compiler
import [Link].*;

public class Employee {

// this instance variable is visible for any child class.


public String name;

// salary variable is visible in Employee class only.


private double salary;

// The name variable is assigned in the constructor.


public Employee (String empName) {
name = empName;
}

// The salary variable is assigned a value.


public void setSalary(double empSal) {
salary = empSal;
}

// This method prints the employee details.


public void printEmp() {
[Link]("name : " + name );
[Link]("salary :" + salary);
}

public static void main(String args[]) {


Employee empOne = new Employee("Ransika");
[Link](1000);
[Link]();
}
}
Output

name : Ransika
salary :1000.0
3. Java Class/Static Variables
Class variables also known as static variables are declared with the static keyword in a class, but
outside a method, constructor or a block.

There would only be one copy of each class variable per class, regardless of how many objects are
created from it.

Static variables are rarely used other than being declared as constants. Constants are variables that are
declared as public/private, final, and static. Constant variables never change from their initial value.

Static variables are stored in the static memory. It is rare to use static variables other than declared
final and used as either public or private constants.

Static variables are created when the program starts and destroyed when the program stops.

Visibility is similar to instance variables. However, most static variables are declared public since
they must be available for users of the class.

Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is
false; and for object references, it is null. Values can be assigned during the declaration or within the
constructor. Additionally, values can be assigned in special static initializer blocks.

Static variables can be accessed by calling with the class name [Link].

When declaring class variables as public static final, then variable names (constants) are all in upper
case. If the static variables are not public and final, the naming syntax is the same as instance and
local variables.
Example of Java Class/Static Variables
Open Compiler
import [Link].*;

public class Employee {

// salary variable is a private static variable


private static double salary;

// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";

public static void main(String args[]) {


salary = 1000;
[Link](DEPARTMENT + "average salary:" + salary);
}
}
Output

Development average salary: 1000


Operators in Java
Java Operators are of prime importance in Java. Without operators we wouldn’t be able to perform
logical , arithmetic calculations in our programs. Thus having operators is an integral part of a
programming language.

Operator in Java are the symbols used for performing specific operations in Java.

Types of Operators in Java


 Arithmetic Operators
 Unary Operators
 Assignment Operator
 Relational Operators
 Logical Operators
 Ternary Operator
 Bitwise Operators
 Shift Operators
 instance of operator

1. Arithmetic Operators
Arithmetic operators are used to perform basic mathematical calculations. Java supports addition (+),
subtraction (-), multiplication (*), division (/), and modulus (%).

 Addition (+)
 Subtraction (-)
 Multiplication (*)
 Division (/)
 Modulus (%): Returns the remainder of a division operation

 Addition (+)
public class ArithmeticOperators {
public static void main(String[] args) {
int a = 10;
int b = 5;

// Addition
int sum = a + b;
[Link]("Sum: " + sum);

// Subtraction
int difference = a - b;
[Link]("Difference: " + difference);

// Multiplication
int product = a * b;
[Link]("Product: " + product);

// Division
int quotient = a / b;
[Link]("Quotient: " + quotient);

// Modulus (Remainder)
int remainder = a % b;
[Link]("Remainder: " + remainder);
}
}
OUTPUT
Sum: 15
Difference: 5
Product: 50
Quotient: 2
Remainder: 0

2. Unary Operators
Unary Plus(+): Represents the identity of the operand.

Unary Minus(-) :Negates the value of the operand.

Unary plus (+)


Unary minus (-)
Increment (++)
Decrement (–)
public class UnaryOperators {
public static void main(String[] args) {
int a = 10;
int b = -5;

// Unary plus operator (+)


int result1 = +a;
[Link]("Unary plus operator (+a): " + result1);

// Unary minus operator (-)


int result2 = -a;
[Link]("Unary minus operator (-a): " + result2);

// Increment operator (++)


a++;
[Link]("After incrementing a: " + a);

// Decrement operator (--)


b--;
[Link]("After decrementing b: " + b);

// Logical complement operator (!)


boolean bool = true;
boolean result3 = !bool;
[Link]("Logical complement operator (!bool): " + result3);
}
}
Java OUTPUT
Unary plus operator (+a): 10
Unary minus operator (-a): -10
After incrementing a: 11
After decrementing b: -6
Logical complement operator (!bool): false

[Link] Operator
Assignment operators are used to assign values to variables. The most common assignment operator
is the equal sign (=).

Simple Assignment (=)


Compound Assignment (e.g., +=, -=, *=, /=, %=): Performs the operation and assigns the result to the
variable.

public class AssignmentOperators {


public static void main(String[] args) {
// Assignment operator (=)
int a = 10;
[Link]("a = " + a);
// Addition assignment operator (+=)
a += 5; // Equivalent to: a = a + 5;
[Link]("After a += 5, a = " + a);

// Subtraction assignment operator (-=)


a -= 3; // Equivalent to: a = a - 3;
[Link]("After a -= 3, a = " + a);

// Multiplication assignment operator (*=)


a *= 2; // Equivalent to: a = a * 2;
[Link]("After a *= 2, a = " + a);

// Division assignment operator (/=)


a /= 4; // Equivalent to: a = a / 4;
[Link]("After a /= 4, a = " + a);

// Modulus assignment operator (%=)


a %= 3; // Equivalent to: a = a % 3;
[Link]("After a %= 3, a = " + a);

// Bitwise AND assignment operator (&=)


int b = 7;
b &= 3; // Equivalent to: b = b & 3;
[Link]("After b &= 3, b = " + b);

// Bitwise OR assignment operator (|=)


b |= 9; // Equivalent to: b = b | 9;
[Link]("After b |= 9, b = " + b);

// Bitwise XOR assignment operator (^=)


b ^= 5; // Equivalent to: b = b ^ 5;
[Link]("After b ^= 5, b = " + b);

// Left shift assignment operator (<<=)


b <<= 2; // Equivalent to: b = b << 2;
[Link]("After b <<= 2, b = " + b);

// Right shift assignment operator (>>=)


b >>= 1; // Equivalent to: b = b >> 1;
[Link]("After b >>= 1, b = " + b);

// Unsigned right shift assignment operator (>>>=)


b >>>= 1; // Equivalent to: b = b >>> 1;
[Link]("After b >>>= 1, b = " + b);
}
}
Java OUTPUT
a = 10
After a += 5, a = 15
After a -= 3, a = 12
After a *= 2, a = 24
After a /= 4, a = 6
After a %= 3, a = 0
After b &= 3, b = 3
After b |= 9, b = 11
After b ^= 5, b = 14
After b <<= 2, b = 56
After b >>= 1, b = 28
After b >>>= 1, b = 14

[Link] Operators
Relational operators are used to compare values and determine their relationship. They include
equality (==), inequality (!=), greater than (>), less than (<), greater than or equal to (>=), and less
than or equal to (<=)

Equal to (==)
Not equal to (!=)
Greater than (>)
Less than (<)
Greater than or equal to (>=)
Less than or equal to (<=)
public class RelationalOperators {
public static void main(String[] args) {
int a = 5;
int b = 10;

// Equal to (==)
[Link]("Is a equal to b? " + (a == b));

// Not equal to (!=)


[Link]("Is a not equal to b? " + (a != b));

// Greater than (>)


[Link]("Is a greater than b? " + (a > b));

// Less than (<)


[Link]("Is a less than b? " + (a < b));

// Greater than or equal to (>=)


[Link]("Is a greater than or equal to b? " + (a >= b));

// Less than or equal to (<=)


[Link]("Is a less than or equal to b? " + (a <= b));
}
}
Java OUPUT
Is a equal to b? false
Is a not equal to b? true
Is a greater than b? false
Is a less than b? true
Is a greater than or equal to b? false
Is a less than or equal to b? true

[Link] Operators
Logical operators are used to perform logical operations on boolean values. They include logical
AND (&&), logical OR (||), and logical NOT (!).

AND (&&)
OR (||)
NOT (!)
public class LogicalOperators {
public static void main(String[] args) {
boolean a = true;
boolean b = false;

// Logical AND (&&)


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

// Logical OR (||)
[Link]("a || b: " + (a || b));

// Logical NOT (!)


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

// Logical XOR (Exclusive OR) - Java doesn't have a built-in XOR operator, but it can be
simulated using AND, OR, and NOT
boolean xorResult = (a || b) && !(a && b);
[Link]("a XOR b: " + xorResult);

// Short-circuit AND (&)


// Both operands are always evaluated, even if the first operand evaluates to false.
[Link]("a & b: " + (a & b));

// Short-circuit OR (|)
// Both operands are always evaluated, even if the first operand evaluates to true.
[Link]("a | b: " + (a | b));
}
}
Java OUTPUT
a && b: false
a || b: true
!a: false
a XOR b: true
a & b: false
a | b: true

6. Ternary operator
The ternary operator (?:) is a concise way of expressing if-else statements. It evaluates a condition and
returns one of two expressions based on the result.

(condition) ? expression1 : expression2

public class TernaryOperatorExample {


public static void main(String[] args) {
int number = 10;

// Check if number is even or odd using ternary operator


String result = (number % 2 == 0) ? "Even" : "Odd";
[Link]("Number " + number + " is " + result);

// Another example: Check if a person is eligible to vote


int age = 20;
String eligibility = (age >= 18) ? "Eligible to vote" : "Not eligible to vote";
[Link]("Age " + age + ": " + eligibility);

// Ternary operator can also be used to assign values


int x = 5;
int y = (x > 0) ? 10 : 20;
[Link]("Value of y: " + y); // Since x is greater than 0, y will be assigned 10

// Ternary operator can be nested


int z = (x > 0) ? ((x < 10) ? 1 : 2) : 3;
[Link]("Value of z: " + z); // If x is greater than 0 and less than 10, z will be 1;
otherwise, it will be 3
}
}
Java OUTPUT
Number 10 is Even
Age 20: Eligible to vote
Value of y: 10
Value of z: 1

[Link] Operators

Bitwise operators perform operations on individual bits of binary numbers. They include bitwise
AND (&), bitwise OR (|), bitwise XOR (^), bitwise complement (~), left shift (<<), and right shift
(>>).

AND (&)
OR (|)
XOR (^)
Complement (~)
Left Shift (<<)
Right Shift (>>)
Unsigned Right Shift (>>>)
public class BitwiseOperators {
public static void main(String[] args) {
int a = 5; // Binary: 101
int b = 3; // Binary: 011

// Bitwise AND (&)


int resultAnd = a & b; // Result: 1 (Binary: 001)
[Link]("a & b = " + resultAnd);

// Bitwise OR (|)
int resultOr = a | b; // Result: 7 (Binary: 111)
[Link]("a | b = " + resultOr);

// Bitwise XOR (^)


int resultXor = a ^ b; // Result: 6 (Binary: 110)
[Link]("a ^ b = " + resultXor);

// Bitwise NOT (~) - Unary Operator


int resultNotA = ~a; // Result: -6 (Binary: 11111111111111111111111111111010)
[Link]("~a = " + resultNotA);

// Left Shift (<<)


int leftShiftResult = a << 1; // Result: 10 (Binary: 1010)
[Link]("a << 1 = " + leftShiftResult);

// Right Shift (>>)


int rightShiftResult = a >> 1; // Result: 2 (Binary: 10)
[Link]("a >> 1 = " + rightShiftResult);

// Unsigned Right Shift (>>>)


int unsignedRightShiftResult = a >>> 1; // Result: 2 (Binary: 10)
[Link]("a >>> 1 = " + unsignedRightShiftResult);
}
}

[Link] Operators
Shift operator in Java, namely left shift (<<) and right shift (>>), allow for bit-level manipulation by
shifting the bits of a binary number.

Left Shift: <<


Signed Right Shift: >>
Unsigned Right Shift: >>>
public class ShiftOperatorsExample {
public static void main(String[] args) {
int number = 10; // Binary: 1010

// Left Shift (<<) - Shifts the bits of the number to the left by specified number of positions
int leftShiftResult = number << 2; // Shifting 'number' 2 positions to the left
[Link]("Left Shift Result: " + leftShiftResult); // Expected: 40 (Binary: 101000)

// Right Shift (>>) - Shifts the bits of the number to the right by specified number of positions
int rightShiftResult = number >> 1; // Shifting 'number' 1 position to the right
[Link]("Right Shift Result: " + rightShiftResult); // Expected: 5 (Binary: 101)

// Unsigned Right Shift (>>>) - Shifts the bits of the number to the right by specified number of
positions, filling the leftmost bits with zeros
int unsignedRightShiftResult = number >>> 1; // Shifting 'number' 1 position to the right
[Link]("Unsigned Right Shift Result: " + unsignedRightShiftResult); // Expected: 5
(Binary: 101)
}
}

[Link] operator
The instance of operator in Java is used to check if an object belongs to a specific class or its
subclasses. It returns true if the object is an instance of the specified class or a subclass, and false
otherwise.

class Animal {}
class Dog extends Animal {}

public class InstanceOfExample {


public static void main(String[] args) {
Animal animal = new Animal();
Dog dog = new Dog();

// Using instanceof to check if an object is an instance of a class


[Link]("Is 'animal' an instance of Animal? " + (animal instanceof Animal)); // true
[Link]("Is 'animal' an instance of Dog? " + (animal instanceof Dog)); // false

[Link]("Is 'dog' an instance of Animal? " + (dog instanceof Animal)); // true


[Link]("Is 'dog' an instance of Dog? " + (dog instanceof Dog)); // true

// Using instanceof to check if an object is an instance of a superclass


[Link]("Is 'dog' an instance of Object? " + (dog instanceof Object)); // true

// Using instanceof to check if an object is an instance of an interface


[Link]("Is 'dog' an instance of Animal interface? " + (dog instanceof Animal)); // true
}
}
Control structures in Java
A program is a list of instructions or blocks of instructions. Java provides Control structures
that can change the path of execution and control the execution of instructions. In this post, we will
discuss the Control structures in programming language.

Here is the table content of the article.


Three kinds of control structures in Java?
1. Control statements/Conditional/selection statements
 if statement in java
 nested if statement in java
 if-else statement in java
 if-else if statement/ ladder if statements in java
 switch statement in java

2. Loops in Java?
 For
 While
 Do-while
3. Branching Statements in Java?

Three kinds of control structures in Java


1. Control statements in java / Conditional Branches in java
Java control statements use to choose the path for execution. There are some types of control
statements:

if statement
It is a simple decision-making statement. It uses to decide whether the statement or block of
statements should be executed or not. A Block of statements executes only if the given condition
returns true otherwise the block of the statement skips. The if statement always accepts the boolean
value and performs the action accordingly. Here we will see the simplest example of an if statement.
We will discuss it in detail in a separate post.

public class IfStatementExample


{
public static void main(String arg[]) {
int a = 5;
int b = 4;
// Evaluating the expression that will return true or false
if (a > b) {
[Link]("a is greater than b");
}
}
}
Output: a is greater than b
OR
public class IfStatementExample
{
public static void main(String arg[]) {
int a = 5;
int b = 4;
// Evaluating the expression that will return true or false
if (a > b)
[Link]("a is greater than b");

}
}
Output: a is greater than b

Example 2:
import [Link].*;
public class IfStatementExample
{
public static void main(String arg[]) {
int a = 2;
int b = 4;
// Evaluating the expression that will return true or false
if (a > b)
[Link]("a is greater than b");
else
[Link]("b is greater than a");

}
}
Ouput:
b is greater than a

nested if statement
The nested if statements mean an if statement inside another if statement. The inner block of the if
statement executes only if the outer block condition is true. This statement is useful when you want to
test a dependent condition. Here we will see the example of nested if with a common example and see
how it works. Visit here for more details.

public class NestedIfStatementExample


{
public static void main(String[] args)
{
int age = 20;
boolean hasVoterCard = true;
// Evaluating the expression that will return true or false
if (age > 18)
{
// If outer condition is true then this condition will be check
if (hasVoterCard)
{
[Link]("You are Eligible");
}
}
}
}
Output: You are Eligible

if-else statement
In the if statement, the block of statements executes when the given condition returns true otherwise
block of the statement skips. Suppose when we want to execute the same block of code if the
condition is false. Here we come on the if-else statement. In an if-else statement, there are two blocks
one is an if block and another is an else block. If a certain condition is true, then if block executes
otherwise else block executes. Let’s see the example and understand it. Visit here for more details.

public class IfElseStatementExample


{
public static void main(String arg[]) {
int a = 10;
int b = 50;
// Evaluating the expression that will return true or false
if (a > b)
{
[Link]("a is greater than b");
}
else
{
[Link]("b is greater than a");
}
}
}
Output: b is greater than a

if-else if statement/ ladder if statements


If we want to execute the different codes based on different conditions then we can use if-else-if. It is
known as if-else if ladder. This statement executes from the top down. During the execution of
conditions if any condition is found true, then the statement associated with that if statement is
executed, and the rest of the code will be skipped. If none of the conditions returns true, then the final
else statement executes. Let’s see the example of the ladder if and you can visit here for more details.

public class IfElseIfStatementExample


{
public static void main(String arg[]) {
int a = 10;
// Evaluating the expression that will return true or false
if (a == 1)
{
[Link]("Value of a: "+a);
}
// Evaluating the expression that will return true or false
else if(a == 5)
{
[Link]("Value of a: "+a);
}
// Evaluating the expression that will return true or false
else if(a == 10)
{
[Link]("Value of a: "+a);
}
else
{
[Link]("else block");
}
}
}
Output: Value of a: 10

Switch statement
The switch statement in java is like the if-else-if ladder statement. To reduce the code complexity of
the if-else-if ladder switch statement comes.
In a switch, the statement executes one from multiple statements based on condition. In the switch
statements, we have a number of choices and we can perform a different task for each choice. You
can read it in detail, for more details.

public class SwitchStatementExample


{
public static void main(String arg[]) {
int a = 10;
// Evaluating the expression that will return true or false
switch(a)
{
case 1:
[Link]("Value of a: 1");
break;
case 5:
[Link]("Value of a: 5");
break;
case 10:
[Link]("Value of a: 10");
break;
default:
[Link]("else block");
break;
}
}
}
Output: Value of a: 10

Loops in Java / Looping statements in java


The loop in java uses to iterate the instruction multiple times. When we want to execute the statement
a number of times then we use loops in java.

for loop
A for loop executes the block of code several times. It means the number of iterations is fixed. JAVA
provides a concise way of writing the loop structure. When we want to execute the block of code
serval times, let’s see the example and visit here for more details.
When you know exactly how many times you want to loop through a block of code, use
the for loop.

Syntax
for (expression 1; expression 2; expression 3)

{
// code block to be executed
}

Expression 1 is executed (one time) before the execution of the code block. (Initialization).
Expression 2 defines the condition for executing the code block.(test condition).
Expression 3 is executed (every time) after the code block has been executed.(update).

public class ForLoopExample


{
public static void main(String[] args)
{
// Creating a for loop
for(int i = 1; i <= 3; i++)
{
[Link]("Iteration number: "+i);
}
}
}
Output: Iteration number: 1
Iteration number: 2
Iteration number: 3

while loop
A while loop allows code to execute repeatedly until the given condition returns true. If the number of
iterations doesn’t fix, it recommends using a while loop. It is also known as an entry control loop. For
more details.

The while loop loops through a block of code as long as a specified condition is true:
Syntax
while (condition) {
// code block to be executed
}

java program
import [Link].*;
public class WhileLoopExample
{
public static void main(String arg[])
{
// Creating a while loop
int i = 1;
while(i <= 3)
{
[Link]("Iteration number: "+i);
i++;
}
}
}
Output: Iteration number: 1
Iteration number: 2
Iteration number: 3

do-while loop
It is like a while loop with the only difference being that it checks for the condition after the execution
of the body of the loop. It is also known as Exit Control Loop. For more details.

public class DoWhileLoopExample


{
public static void main(String arg[])
{
// Creating a while loop
int i = 1;
do
{
[Link]("Iteration number: "+i);
i++;
}
while(i <= 3);
}
}
Output: Iteration number: 1
Iteration number: 2
Iteration number: 3

Jump Statements in Java


These use to alter the flow of control in loops.

break

If a break statement encounters inside a loop, the loop immediately terminates, and the control of the
program goes to the next statement following the loop. It is used along with the if statement in loops.
If the condition is true, then the break statement terminates the loop immediately.

public class BreakStatementExample


{
public static void main(String arg[])
{
for(int i = 0; i <=3; i++)
{
[Link]("Iteration number:" + i);
if(i == 2)
break;
}
}
}
Output: Iteration number:0
Iteration number:1
Iteration number:2

continue
The continue statement uses in a loop control structure. If you want to skip some code and need to
jump to the next iteration of the loop immediately. Then you can use a continue statement. It can be
used in for loop or a while loop. Read it in detail

public class ContinueStatementExample


{
public static void main(String arg[])
{
for(int i = 0; i <=3; i++)
{
if(i == 1)
continue;
[Link]("Iteration number:" + i);
}
}
}
Output: Iteration number:0
Iteration number:2
Iteration number:3

 return: Exits the current method and returns control to the calling method, optionally
returning a value.

Java Loops
Loops in programming allow a set of instructions to run multiple times based on a condition. In Java,
there are three types of loops, each with its own syntax and method of checking the condition, but
fundamentally, they all serve the same purpose.

Loops in Java
In Java, there are three types of Loops, which are listed below:

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

Syntax:

for (initialization; condition; increment/decrement) {

// code to be executed

The image below demonstrates the flow chart of a for loop:


Forloop
Flowchart of for -loop
Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An
already declared variable can be used or a variable can be declared, local to loop only.
Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It
is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.
Statement execution: Once the condition is evaluated to true, the statements in the loop body are
executed.
Increment/ Decrement: It is used for updating the variable for next iteration.
Loop termination:When the condition becomes false, the loop terminates marking the end of its life
cycle.
Example: The below Java program demonstrates a for loop that prints numbers from 0 to 10 in a
single line.

// Java program to demonstrates the working of for loop


import [Link].*;

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

Output
0 1 2 3 4 5 6 7 8 9 10
Note: There is another form of the for loop known as Enhanced for loop or (for each loop).

Enhanced for loop (for each)


This loop is used to iterate over arrays or collections.

Syntax:

for (dataType variable : arrayOrCollection) {

// code to be executed

Example: The below Java program demonstrates an Enhanced for loop (for each loop) to iterate
through an array and print names.

// Java program to demonstrate


// the working of for each loop
import [Link].*;

class Geeks {
public static void main(String[] args)
{
String[] names = { "Sweta", "Gudly", "Amiya" };

for (String name : names) {


[Link]("Name: " + name);
}
}
}

Output
Name: Sweta
Name: Gudly
Name: Amiya

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

while (condition) {

// code to be executed

The below image demonstrates the flow chart of a while loop:

While-loop
Flowchart of while-loop
While loop starts with the checking of Boolean condition. If it evaluated to true, then the loop body
statements are executed otherwise first statement following the loop is executed. For this reason it is
also called Entry control loop
Once the condition is evaluated to true, the statements in the loop body are executed. Normally the
statements contain an update value for the variable being processed for the next iteration.
When the condition becomes false, the loop terminates which marks the end of its life cycle.
Example: The below Java program demonstrates a while loop that prints numbers from 0 to 10 in a
single line.

// Java program to demonstrates


// the working of while loop
import [Link].*;

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

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

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

Syntax:

do {

// code to be executed

} while (condition);

The below image demonstrates the flow chart of a do-while loop:

Do-while-loop
Flowchart of do-while loop
do while loop starts with the execution of the statement. There is no checking of any condition for the
first time.
After the execution of the statements, and update of the variable value, the condition is checked for
true or false value. If it is evaluated to true, next iteration of loop starts.
When the condition becomes false, the loop terminates which marks the end of its life cycle.
It is important to note that the do-while loop will execute its statements a tleast once before any
condition is checked, and therefore is an example of exit control loop.
Example: The below Java program demonstrates a do-while loop that prints numbers from 0 to 10 in a
single line.

// Java program to demonstrates


// the working of do-while loop
import [Link].*;

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

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

Java Methods
A Java method is a collection of statements that are grouped together to perform an operation. When
you call the [Link]() method, for example, the system actually executes several statements
in order to display a message on the console.

Creating a Java Method


To create a Java method, there should be an access modifier followed by the return type, method's
name, and parameters list.

Syntax to Create a Java Method


Considering the following example to explain the syntax of a method −

modifier returnType nameOfMethod (Parameter List) {


// method body
}
The syntax shown above includes −

 modifier − It defines the access type of the method and it is optional to use.

 returnType − Method may return a value.

 nameOfMethod − This is the method name. The method signature consists of the method
name and the parameter list.

 Parameter List − The list of parameters, it is the type, order, and number of parameters of a
method. These are optional, method may contain zero parameters.

 method body − The method body defines what the method does with the statements.

Example to Create a Java Method


Here is the source code of the above defined method called minFunction(). This method takes two
parameters n1 and n2 and returns the minimum between the two −

/** the snippet returns the minimum between two numbers */

public static int minFunction(int n1, int n2) {


int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}
Calling a Java Method
For using a method, it should be called. There are two ways in which a method is called i.e., method
returns a value or returning nothing (no return value).

The process of method calling is simple. When a program invokes a method, the program control gets
transferred to the called method. This called method then returns control to the caller in two
conditions, when −the return statement is executed.
it reaches the method ending closing brace.
The methods returning void is considered as call to a statement. Lets consider an example −

[Link]("This is [Link]!");
The method returning value can be understood by the following example −

int result = sum(6, 9);


Example: Defining and Calling a Java Method
Following is the example to demonstrate how to define a method and how to call it −

public class ExampleMinNumber {


public static void main(String[] args) {
int a = 11;
int b = 6;
int c = minFunction(a, b);
[Link]("Minimum Value = " + c);
}

/** returns the minimum of two numbers */


public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}
}
Output
Minimum value = 6

Passing Parameters by Value in Java Methods


While working under calling process, arguments is to be passed. These should be in the same order as
their respective parameters in the method specification. Parameters can be passed by value or by
reference.

Passing Parameters by Value means calling a method with a parameter. Through this, the argument
value is passed to the parameter.

Example: Passing Parameters by Value


The following program shows an example of passing parameter by value. The values of the arguments
remains the same even after the method invocation.

public class swappingExample {

public static void main(String[] args) {


int a = 30;
int b = 45;
[Link]("Before swapping, a = " + a + " and b = " + b);

// Invoke the swap method


swapFunction(a, b);
[Link]("\n**Now, Before and After swapping values will be same here**:");
[Link]("After swapping, a = " + a + " and b is " + b);
}
public static void swapFunction(int a, int b) {
[Link]("Before swapping(Inside), a = " + a + " b = " + b);

// Swap n1 with n2
int c = a;
a = b;
b = c;
[Link]("After swapping(Inside), a = " + a + " b = " + b);
}
}
Output
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30

**Now, Before and After swapping values will be same here**:


After swapping, a = 30 and b is 45
Java Methods Overloading
When a class has two or more methods by the same name but different parameters, it is known as
method overloading. It is different from overriding. In overriding, a method has the same method
name, type, number of parameters, etc.

Let's consider the example discussed earlier for finding minimum numbers of integer type. If, let's say
we want to find the minimum number of double type. Then the concept of overloading will be
introduced to create two or more methods with the same name but different parameters.

The following example explains the same −

Example: Methods Overloading in Java


Open Compiler
public class ExampleOverloading {

public static void main(String[] args) {


int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;
int result1 = minFunction(a, b);

// same function name with different parameters


double result2 = minFunction(c, d);
[Link]("Minimum Value = " + result1);
[Link]("Minimum Value = " + result2);
}

// for integer
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}

// for double
public static double minFunction(double n1, double n2) {
double min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}
}
Output
Minimum Value = 6
Minimum Value = 7.3
Overloading methods makes program readable. Here, two methods are given by the same name but
with different parameters. The minimum number from integer and double types is the result.

Using Command-Line Arguments


Sometimes you will want to pass some information into a program when you run it. This is
accomplished by passing command-line arguments to main( ).

A command-line argument is the information that directly follows the program's name on the
command line when it is executed. To access the command-line arguments inside a Java program is
quite easy. They are stored as strings in the String array passed to main( ).

Example
The following program displays all of the command-line arguments that it is called with −

public class CommandLine {

public static void main(String args[]) {


for(int i = 0; i<[Link]; i++) {
[Link]("args[" + i + "]: " + args[i]);
}
}
}
Try executing this program as shown here −
$java CommandLine this is a command line 200 -100
Output
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100

The this Keyword inside Java Methods


this is a keyword in Java which is used as a reference to the object of the current class, with in an
instance method or a constructor. Using this you can refer the members of a class such as
constructors, variables and methods.

Note − The keyword this is used only within instance methods or constructors

This
In general, the keyword this is used to −

Differentiate the instance variables from local variables if they have same names, within a constructor
or a method.

class Student {
int age;
Student(int age) {
[Link] = age;
}
}
Call one type of constructor (parametrized constructor or default) from other in a class. It is known as
explicit constructor invocation.

class Student {
int age
Student() {
this(20);
}

Student(int age) {
[Link] = age;
}
}
Example: Use of this keyword in Java Methods
Here is an example that uses this keyword to access the members of a class. Copy and paste the
following program in a file with the name, This_Example.java.
Open Compiler
public class This_Example {
// Instance variable num
int num = 10;

This_Example() {
[Link]("This is an example program on keyword this");
}

This_Example(int num) {
// Invoking the default constructor
this();

// Assigning the local variable <i>num</i> to the instance variable <i>num</i>


[Link] = num;
}

public void greet() {


[Link]("Hi Welcome to Tutorialspoint");
}

public void print() {


// Local variable num
int num = 20;

// Printing the local variable


[Link]("value of local variable num is : "+num);

// Printing the instance variable


[Link]("value of instance variable num is : "+[Link]);

// Invoking the greet method of a class


[Link]();
}

public static void main(String[] args) {


// Instantiating the class
This_Example obj1 = new This_Example();

// Invoking the print method


[Link]();

// Passing a new value to the num variable through parametrized constructor


This_Example obj2 = new This_Example(30);

// Invoking the print method again


[Link]();
}
}
Output
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 10
Hi Welcome to Tutorialspoint
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 30
Hi Welcome to Tutorialspoint

What is Method Overloading in Java?


Java allows the creation of multiple methods in a class, which can have the same names. But all the
methods will be assigned with different parameters. This feature is known as Java Method
Overloading. The primary significance of this feature is that it increases the readability of programs.
Method Overloading is often known as Compile-time polymorphism.

Let’s delve into the Method Overloading feature with an example. In this case, we define two
methods with the same name – add – but with different parameters. Utilizing the same name within
the same class, including the StringBuilder Class in Java, enhances the program's readability. The
Java code used in this example would be as follows:

public class Example


{
public static void main(String[] args)
{
Example obj = new Example();
[Link]([Link](10, 20));
[Link]([Link](10, 20, 30));
}
public int add(int a, int b)
{
return a + b;
}
public int add(int a, int b, int c)
{
return a + b + c;
}
}

The first method, ' add(int a, int b),' takes two integer-based parameters and returns their sum, while
the second method, 'add(int a, int b, int c),' takes three integer parameters and returns their sum.
Output:

30

60

Method overloading: Benefits


The definition of Method Overloading is highly similar to that of Constructor Overloading in Java,
but they're not the same. The former is a fairly popular feature in Java, with multiple advantages. The
following are some benefits of using Method Overloading:

a) Method overloading significantly improves the readability of programs.

b) The feature allows programmers to operate on tasks efficiently.

c) Using Method Overloading results in codes that look neat and compact.

d) Complex programs can be simplified using Method Overloading.

e) Codes can be reused using this feature, which helps save memory as well.

f) Since binding is accomplished in the compilation time, the execution period shortens.

g) Method Overloading can also be used on constructors, which offers you opportunities to initialise
objects of a class in different ways.

h) Using Method Overloading, you can access the methods that perform related functions that use the
same name, with a minor difference in the argument number or type.

Keen on getting a clear understanding between method and function, refer to our blog on difference
between method and function

How do you initiate method overloading in Java?


Method overloading can be used by changing the number of parameters or the data type. The best way
to understand concepts in Java is via examples. Here is a detailed look into the different ways to
initiate Method Overloading in Java with examples:

Change in the number of parameters


One of the ways to accomplish Method Overloading is by changing the number of parameters. This is
done while passing to different methods. Here is an example of changing the number of parameters
while using Method Overloading in Java:

public class Calculator


{
// Method to add two integers
public int add(int a, int b)
{
return a + b;
}
// Overloaded method to add three integers
public int add(int a, int b, int c)
{
return a + b + c; }
// Overloaded method to add two doubles
public double add(double a, double b)
{
return a + b;
}
// Overloaded method to add three doubles
public double add(double a, double b, double c)
{
return a + b + c;
}
}

Here, a 'Calculator' class with four methods named 'add' is taken. The first method takes two 'int'
parameters and returns their sum as an 'int'. The second method is an overloaded version of the first
but takes three 'int' parameters instead of two.

The third method takes two 'double' parameters and returns their sum as a 'double'. The fourth method
is an overloaded version of the third but takes three 'double' parameters instead of two. You can use
the 'add' method to add two integers, three integers, two doubles, or three doubles, depending on the
arguments we pass to the method. This concept is similar to Constructor Overloading in Java, where
multiple constructors can exist within a class, each with different parameter types or counts, allowing
flexible object creation.

public static void main(String[] args)


{
Calculator calculator = new Calculator();
// Adding two integers
int sum1 = [Link](5, 10);
[Link](sum1); // Output: 15
// Adding three integers
int sum2 = [Link](5, 10, 15);
[Link](sum2); // Output: 30
// Adding two doubles
double sum3 = [Link](5.5, 10.5);
[Link](sum3); // Output: 16.0
// Adding three doubles
double sum4 = [Link](5.5, 10.5, 15.5);
[Link](sum4); // Output: 31.5
}
Output:
15
30
16.0
31.5

Expand your skillset by learning to enhance web pages with dynamic effects in JavaScript. Sign up
for our JavaScript & jQuery course now!

Change in the data types of arguments


Method Overloading can also be accomplished by having different parameter types with the same
name. Here is an example of method overloading in Java where multiple methods differ in data type:

public class Example


{
public int sum(int a, int b)
{
return a + b;
} public double sum(double a, double b)
{
return a + b;
} public String sum(String a, String b)
{
return a + b;
} public static void main(String[] args)
{
Example ex = new Example();
int result1 = [Link](2, 3);
double result2 = [Link](2.5, 3.5);
String result3 = [Link]("Hello ", "World");
[Link]("Result1: " + result1);
[Link]("Result2: " + result2);
[Link]("Result3: " + result3);
}
}

In this example, three methods are mentioned with the same name, "sum", but with different data
types and output types. The first method takes two integers as input and returns an integer.

The second method takes two doubles as input and returns a double, and the third method uses two
strings as input and returns a string. Then an object of the Example class is created in the main
method.

The sum method with different arguments is called, and the variables with varying types of data are
assigned with the results. Finally, the results are printed using '[Link]. println' statements.
Output:

Result1: 5

Result2: 6.0

Result3: Hello World

From the output we understand the following:

a) The first call to the sum method with 2 and 3 as arguments return 5

b) The second call to the sum method with 2.5 and 3.5 as arguments return 6.0

c) The third call to the sum method with "Hello " and "World" as arguments concatenates the two
strings and returns "Hello World"

d) The [Link] statements then print out the values of the result1, result2, and result3
variables, respectively.

Stand out among your peers by learning to test your JavaScript applications the right way. Enroll for
our JavaScript Unit Testing Training with Jasmine course now!

MATH CLASS IN JAVA


The Math class in Java is a utility class that is part of the [Link] package. It provides a collection of
static methods for performing common mathematical operations and calculations.
Key characteristics and uses of the Math class:
Static Methods:
All methods within the Math class are static, meaning you can call them directly on the class name
without needing to create an instance of Math. For example, to find the square root of a number, you
would use [Link](number).
The Math class cannot be instantiated, as it is declared as final and its constructor is private.
Mathematical Operations:
It offers a wide range of functions for various mathematical computations, including:
Trigonometric functions: sin(), cos(), tan(), asin(), acos(), atan(), toRadians(), toDegrees().
Exponential and Logarithmic functions: exp(), log(), log10(), pow(), sqrt(), cbrt().
Rounding and Absolute Value: abs(), ceil(), floor(), round().
Min/Max values: min(), max().
Random number generation: random().
Exact arithmetic operations: addExact(), subtractExact(), multiplyExact(), incrementExact(),
decrementExact(), negateExact(), toIntExact(). These methods throw an ArithmeticException if an
overflow occurs.
Constants:
It also defines two commonly used mathematical constants:
[Link]: Represents the value of pi.
Math.E: Represents the base of the natural logarithm (Euler's number).
Example Usage:
public class MathExample {
public static void main(String[] args) {
double number = 16.0;
double squareRoot = [Link](number); // Calculates square root
[Link]("Square root of " + number + ": " + squareRoot);

int a = 10, b = 20;


int max = [Link](a, b); // Finds the maximum value
[Link]("Maximum of " + a + " and " + b + ": " + max);

double angleDegrees = 45.0;


double angleRadians = [Link](angleDegrees); // Converts degrees to radians
double sineValue = [Link](angleRadians); // Calculates sine
[Link]("Sine of " + angleDegrees + " degrees: " + sineValue);

double randomNumber = [Link](); // Generates a random number between 0.0 and 1.0
[Link]("Random number: " + randomNumber);
}
}

What are Arrays in Java?


Java provides a data structure called the array, which stores a fixed-size sequential collection of
elements of the same data type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare
one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables.

This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed
variables.

Declaring Array Variables


To use an array in a program, you must declare a variable to reference the array, and you must specify
the type of array the variable can reference. Here is the syntax for declaring an array variable −

Syntax
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
Example
The following code snippets are examples of this syntax −

double[] myList; // preferred way.


or
double myList[]; // works but not preferred way.

Creating Arrays
You can create an array by using the new operator with the following syntax −

Syntax
arrayRefVar = new dataType[arraySize];
The above statement does two things −

It creates an array using new dataType[arraySize].

It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the variable
can be combined in one statement, as shown below −

dataType[] arrayRefVar = new dataType[arraySize];


Alternatively you can create arrays as follows −

dataType[] arrayRefVar = {value0, value1, ..., valuek};


The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0
to [Link]-1.

double[] myList = new double[10];


Following picture represents array myList. Here, myList holds ten double values and the indices are
from 0 to 9.

Processing Arrays
When processing array elements, we often use either for loop or foreach loop because all of the
elements in an array are of the same type and the size of the array is known.

Example: Creating, Iterating and Performing Other Operations on Arrays


public class TestArray {

public static void main(String[] args) {


double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (int i = 0; i < [Link]; i++) {
[Link](myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < [Link]; i++) {
total += myList[i];
}
[Link]("Total is " + total);

// Finding the largest element


double max = myList[0];
for (int i = 1; i < [Link]; i++) {
if (myList[i] > max) max = myList[i];
}
[Link]("Max is " + max);
}
}

This will produce the following result −

Output
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

UNIT – 5
In Java, Text and Binary I/O (Input and Output) refers to how data is read from or written to
files or streams. There are two primary modes:

1. Text I/O (Character Streams)**

* Handles **character data** (letters, numbers, symbols).


* Uses Unicode and is **character-oriented**.
* Suitable for reading and writing **human-readable text files**.

Classes Used:

* `FileReader`, `FileWriter`
* `BufferedReader`, `BufferedWriter`
* `PrintWriter`

Example – Writing and Reading Text:

```java
import [Link].*;

public class TextIOExample {


public static void main(String[] args) throws IOException {
// Writing to a text file
FileWriter writer = new FileWriter("[Link]");
[Link]("Hello, Java Text I/O!");
[Link]();

// Reading from a text file


FileReader reader = new FileReader("[Link]");
int data;
while ((data = [Link]()) != -1) {
[Link]((char) data);
}
[Link]();
}
}
```

---

2. Binary I/O (Byte Streams)**

* Handles **raw binary data** like images, audio, video, or serialized objects.
* Uses **byte-oriented streams**.

Classes Used:

* `FileInputStream`, `FileOutputStream`
* `BufferedInputStream`, `BufferedOutputStream`
* `DataInputStream`, `DataOutputStream`
* `ObjectInputStream`, `ObjectOutputStream` (for objects)
Example – Writing and Reading Binary Data:

```java
import [Link].*;

public class BinaryIOExample {


public static void main(String[] args) throws IOException {
// Writing bytes to a file
FileOutputStream fos = new FileOutputStream("[Link]");
[Link](new byte[] {10, 20, 30, 40});
[Link]();

// Reading bytes from a file


FileInputStream fis = new FileInputStream("[Link]");
int b;
while ((b = [Link]()) != -1) {
[Link](b + " ");
}
[Link]();
}
}

Binary I/O Classes in Java

Binary I/O in Java is used to handle byte-level input and output, making it ideal for working
with non-text data such as images, audio files, video, and serialized objects.

1. InputStream (Abstract Class)

 Superclass of all byte input stream classes.


 Reads byte by byte.

Common Subclasses:
Class Description

FileInputStream Reads bytes from a file.

BufferedInputStream Adds buffering to improve efficiency.

DataInputStream Reads Java primitive data types in binary form.

ObjectInputStream Reads serialized Java objects.

2. OutputStream (Abstract Class)

 Superclass of all byte output stream classes.


 Writes byte by byte.
Common Subclasses:
Class Description

FileOutputStream Writes bytes to a file.

BufferedOutputStream Adds buffering to output stream.

DataOutputStream Writes Java primitive data types in binary form.

ObjectOutputStream Writes serialized Java objects.

3. Description of Key Classes

🔸 FileInputStream / FileOutputStream

 Read/write raw byte data from/to a file.

FileInputStream fis = new FileInputStream("[Link]");


FileOutputStream fos = new FileOutputStream("[Link]");

🔸 BufferedInputStream / BufferedOutputStream

 Wraps around FileInputStream or FileOutputStream for faster I/O.

BufferedInputStream bis = new BufferedInputStream(new FileInputStream("[Link]"));


BufferedOutputStream bos = new BufferedOutputStream(new
FileOutputStream("file_copy.bin"));

DataInputStream / DataOutputStream

 Reads and writes primitive data types like int, float, boolean, double.

DataOutputStream dos = new DataOutputStream(new FileOutputStream("[Link]"));


[Link](123);
[Link](45.6);
[Link]();

DataInputStream dis = new DataInputStream(new FileInputStream("[Link]"));


int num = [Link]();
double val = [Link]();
[Link]();

ObjectInputStream / ObjectOutputStream

 Used for serialization and deserialization of Java objects.


ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("[Link]"));
[Link](new Student("John", 25));
[Link]();

ObjectInputStream ois = new ObjectInputStream(new FileInputStream("[Link]"));


Student s = (Student) [Link]();
[Link]();

Note: The class must implement Serializable.

Object I/O in Java

Object I/O (Object Input/Output) in Java is used to read and write entire objects to and from
files (or other streams). This is achieved using **serialization** and **deserialization**.

---

Key Concepts

1. Serialization

Serialization is the process of converting an object into a byte stream so it can be saved to a
file, sent over a network, etc.

2. Deserialization

Deserialization is the reverse process — converting a byte stream back into an object.

Important Classes (in `[Link]` package)


| Class | Description |

| -------------------- |
------------------------------------------------------------------------------------------- |

| `ObjectOutputStream` | Used to write objects to a stream.


|

| `ObjectInputStream` | Used to read objects from a stream.


|

| `Serializable` | Marker interface that must be implemented by a class to allow its objects
to be serialized. |

Basic Example

Step 1: Create a Serializable Class

import [Link];

class Student implements Serializable {

int id;

String name;

public Student(int id, String name) {

[Link] = id;

[Link] = name;

Step 2: Write Object to File (Serialization)

import [Link];

import [Link];

public class WriteObject {


public static void main(String[] args) {

try {

Student s = new Student(101, "John");

FileOutputStream fileOut = new FileOutputStream("[Link]");

ObjectOutputStream out = new ObjectOutputStream(fileOut);

[Link](s);

[Link]();

[Link]();

[Link]("Object has been serialized");

} catch (Exception e) {

[Link]();

```

Step 3: Read Object from File (Deserialization)

import [Link];

import [Link];

public class ReadObject {

public static void main(String[] args) {

try {

FileInputStream fileIn = new FileInputStream("[Link]");

ObjectInputStream in = new ObjectInputStream(fileIn);

Student s = (Student) [Link]();


[Link]();

[Link]();

[Link]("Object has been deserialized");

[Link]("ID: " + [Link] + ", Name: " + [Link]);

} catch (Exception e) {

[Link]();

Random Access Files in Java

In Java, `RandomAccessFile` is a class that allows **reading from and writing to a file at any
position** (not just sequentially like `FileInputStream` or `FileOutputStream`).

It is useful when:

* You want to update specific parts of a file.

* You need both **read** and **write** access.

* You want to jump (seek) to specific locations in a file.

Class: `RandomAccessFile`**

* Package: `[Link]`

* Constructor:

RandomAccessFile(String fileName, String mode)

* Modes:
* `"r"` – read-only

* `"rw"` – read and write

Basic Methods of `RandomAccessFile`**

| Method | Description |

| ------------------------ | ------------------------------------------------- |

| `read()` / `readFully()` | Read data |

| `write()` | Write data |

| `seek(long pos)` | Move the file pointer to a specific byte position |

| `getFilePointer()` | Returns the current position |

| `length()` | Gets the file length |

| `setLength(long len)` | Sets the file length |

Example: Write and Read Using RandomAccessFile**

import [Link];

public class RandomAccessExample {

public static void main(String[] args) {

try {

// Open file in read-write mode

RandomAccessFile file = new RandomAccessFile("[Link]", "rw");

// Write data

[Link]("Hello Java");

[Link](123);

// Move file pointer to beginning


[Link](0);

// Read data

String text = [Link]();

int number = [Link]();

[Link]("Text: " + text);

[Link]("Number: " + number);

[Link]();

} catch (Exception e) {

[Link]();

Seek Example (Jumping in a File)**

[Link](5); // Move to 5th byte

[Link]('X'); // Overwrite character at that position

You might also like