0% found this document useful (0 votes)
15 views32 pages

Chap 1 Introduction To Java

Chapter 1 introduces Java as a popular, high-level, object-oriented programming language known for its slogan 'Write once, run anywhere', allowing applications to run on various platforms. It covers Java's key features, including its object-oriented nature, platform independence, ease of learning, security, and support for multithreading, as well as the basics of data types, variables, and operators. The chapter also explains primitive and non-primitive data types, variable types, expressions, and various operators used in Java programming.

Uploaded by

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

Chap 1 Introduction To Java

Chapter 1 introduces Java as a popular, high-level, object-oriented programming language known for its slogan 'Write once, run anywhere', allowing applications to run on various platforms. It covers Java's key features, including its object-oriented nature, platform independence, ease of learning, security, and support for multithreading, as well as the basics of data types, variables, and operators. The chapter also explains primitive and non-primitive data types, variable types, expressions, and various operators used in Java programming.

Uploaded by

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

Chap.

1 : Java Fundamentals

Introduction to Java:
• Java is one of the most popular programming languages.
• Java's slogan is "Write once, run anywhere". Java programs can run on different platforms,
including mobile, desktop, and other portable systems. You can use Java to build apps,
games, banking applications, web apps, and much more!
• Java is a popular high-level, object-oriented programming language that was originally
developed by Sun Microsystems and released in 1995. Currently, Java is owned by Oracle,
and more than 3 billion devices run Java.
• The first example in Java is to print "Hello, World!" on the screen.

public class MyFirstJavaProgram {

/* This is my first java program.


* This will print 'Hello, World!' as the output
*/

public static void main(String []args) {


System.out.println("Hello, World!"); // prints Hello, World!
}
}

Java Features:
Java is a feature-rich language. Java is evolving continuously with every update, and updates are
coming every six months. Following are some of the main features of the Java language:

• Object Oriented: Java is a pure object-oriented language, and everything in Java is an


object. Java supports OOPS principles like Inheritance, Encapsulation, Polymorphism,
Classes , and so on. Java itself can be extended as well, being based on an object model.
• Platform Independent: Java code is platform independent. A Java code is not compiled
into machine-specific code; it is compiled into a platform-neutral byte code. This byte code
is executed by JVM which runs the code on the underlying platform. This capability makes
Java a Write Once Run Anywhere language.
• Easy To Learn: Java inherits features from C and C++, and developers can easily learn
Java if they know any of the C or C++ languages. Even for someone new to computer
languages, Java is very easy to learn from scratch.
• Secure: Java is secure by architecture. A developer is not required to directly interact with
the underlying memory or operating system. Java provides automatic garbage collection,
so developers are not required to worry about memory leaks, management, etc.
• Architectural-Neutral: Java byte code can be executed on any kind of processor. JRE
automatically handles the code execution on different types of processors.
• Portable: A Java code written on a Windows machine can be executed without any code
change on MacOS and vice versa. There is no need to make any operating system-specific
code changes.
• Robust: Java is a very robust language with very strong compile-time error checks, strict
type checking, and runtime exception handling.
• Multithreading: Java provides inbuilt support for multiprocessing and multithreading.
Java provides thread handling, monitors, deadlock handling, racing conditions, etc.
• High Performance: Java, although being interpreted, is still very performant. The JIT(Just
In Time) compiler helps in improving performance.
• Distributed: Java is designed for distributed systems and is the most popular language for
developing internet-based applications as the internet is a distributed environment.

Basics of Java:
❖ 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 −
1. Primitive Data Types
2. Reference/Object Data Types
1. 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

Example:-
public class JavaTester {
public static void main(String args[]) {
byte byteValue1 = 2;
byte byteValue2 = 4;
byte byteResult = (byte)(byteValue1 + byteValue2);
System.out.println("Byte: " + byteResult);

short shortValue1 = 2;
short shortValue2 = 4;
short shortResult = (short)(shortValue1 + shortValue2);
System.out.println("Short: " + shortResult);

int intValue1 = 2;
int intValue2 = 4;
int intResult = intValue1 + intValue2;
System.out.println("Int: " + intResult);

long longValue1 = 2L;


long longValue2 = 4L;
long longResult = longValue1 + longValue2;
System.out.println("Long: " + longResult);

float floatValue1 = 2.0f;


float floatValue2 = 4.0f;
float floatResult = floatValue1 + floatValue2;
System.out.println("Float: " + floatResult);

double doubleValue1 = 2.0;


double doubleValue2 = 4.0;
double doubleResult = doubleValue1 + doubleValue2;
System.out.println("Double: " + doubleResult);

boolean booleanValue = true;


System.out.println("Boolean: " + booleanValue);

char charValue = 'A';


System.out.println("Char: " + charValue);
}
}
OUTPUT:-
Byte: 6
Short: 6
Int: 6
Long: 6
Float: 6.0
Double: 6.0
Boolean: true
Char: A

2. Java Non-Primitive (Reference/Object)

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.

The default value of any reference variable is null. A reference variable can be used to refer to any
object of the declared type or any compatible type.

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

Variables Types
• Local variables
• Instance variables
• Class/Static variables

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

public class Test {


public void pupAge() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}

public static void main(String args[]) {


Test test = new Test();
test.pupAge();
}
}
OUTPUT:-
Puppy age is: 7

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

import java.io.*;
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() {
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}

public static void main(String args[]) {


Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}

Output:-
name : Ransika
salary :1000.0

3. 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.
• Static variables can be accessed by calling with the class name ClassName.VariableName.

import java.io.*;
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;
System.out.println(DEPARTMENT + "average salary:" + salary);
}
}

output:-
Development average salary:1000

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.

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

operators
Java operators are the symbols that are used to perform various operations on variables and values.
By using these operators, we can perform operations like addition, subtraction, checking less than
or greater than, etc.

There are different types of operators in Java, we have listed them below −

• Arithmetic Operators
• Assignment Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Misc Operators

Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators −

Assume integer variable A holds 10 and variable B holds 20, then –

Operator Description
+ (Addition) Adds values on either side of the operator.

- (Subtraction) Subtracts right-hand operand from left-hand operand.


* (Multiplication) Multiplies values on either side of the operator.

/ (Division) Divides left-hand operand by right-hand operand.

% (Modulus) Divides left-hand operand by right-hand operand and returns remainder.

++ (Increment) Increases the value of operand by 1.

-- (Decrement) Decreases the value of operand by 1.

Example
public class ArithmeticExample {
public static void main(String[] args) {
int a = 10, b = 5;
// Addition
System.out.println("a + b = " + (a + b)); // 15

// Subtraction
System.out.println("a - b = " + (a - b)); // 5

// Multiplication
System.out.println("a * b = " + (a * b)); // 50

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

// Modulus
System.out.println("a % b = " + (a % b)); // 0
}
}
OUTPUT:-
a + b = 15
a-b=5
a * b = 50
a/b=2
a%b=0
Assignment Operators:
Assignment Operators are used to assign values to variables. These operators modify the value of
a variable based on the operation performed. The most commonly used assignment operator is =,
but Java provides multiple compound assignment operators for shorthand operations.

Following are the assignment operators supported by Java language –


Operator Description
= Simple assignment operator. Assigns values from right side operands to
left side operand.

+= Add AND assignment operator. It adds right operand to the left operand
and assign the result to left operand.

-= Subtract AND assignment operator. It subtracts right operand from the


left operand and assign the result to left operand.

*= Multiply AND assignment operator. It multiplies right operand with the


left operand and assign the result to left operand.

/= Divide AND assignment operator. It divides left operand with the right
operand and assign the result to left operand.

%= Modulus AND assignment operator. It takes modulus using two


operands and assign the result to left operand.

<<= Left shift AND assignment operator.


>>= Right shift AND assignment operator.

&= Bitwise AND assignment operator.

^= bitwise exclusive OR and assignment operator.

|= bitwise inclusive OR and assignment operator.

Example:-
public class AssignmentExample {
public static void main(String[] args) {
int a = 10;

// Assign and add


a += 5;
System.out.println("a += 5: " + a); // 15
// Assign and subtract
a -= 3;
System.out.println("a -= 3: " + a); // 12

// Assign and multiply


a *= 2;
System.out.println("a *= 2: " + a); // 24

// Assign and divide


a /= 4;
System.out.println("a /= 4: " + a); // 6

// Assign and modulus


a %= 5;
System.out.println("a %= 5: " + a); // 1
}
}
OUTPUT:-
a += 5: 15
a -= 3: 12
a *= 2: 24
a /= 4: 6
a %= 5: 1

Relational Operators:
Relational operators are used to compare two values. These operators return a boolean result: true
if the condition is met and false otherwise. Relational operators are commonly used in decision-
making statements like if conditions and loops.
There are following relational operators supported by Java language.
Assume variable A holds 10 and variable B holds 20, then –
Operator Description
== (equal to) Checks if the values of two operands are equal or not, if yes then condition
becomes true.
!= (not equal to) Checks if the values of two operands are equal or not, if values are not equal
then condition becomes true.
> (greater than) Checks if the value of left operand is greater than the value of right operand, if
yes then condition becomes true.

< (less than) Checks if the value of left operand is less than the value of right operand, if
yes then condition becomes true.

>= (greater than or Checks if the value of left operand is greater than or equal to the value of right
equal to) operand, if yes then condition becomes true.
<= (less than or Checks if the value of left operand is less than or equal to the value of right
equal to) operand, if yes then condition becomes true.

Example:-
public class RelationalExample {
public static void main(String[] args) {
int A = 10, B = 5;

System.out.println("A == B: " + (A == B)); // false


System.out.println("A != B: " + (A != B)); // true
System.out.println("A > B: " + (A > B)); // true
System.out.println("A < B: " + (A < B)); // false
System.out.println("A >= B: " + (A >= B)); // true
System.out.println("A <= B: " + (A <= B)); // false
}
}
OUTPUT:-
A == B: false
A != B: true
A > B: true
A < B: false
A >= B: true
A <= B: false

Logical Operators
Logical operators are used to perform logical operations on boolean values. These operators are
commonly used in decision-making statements such as if conditions and loops to control program
flow.
The following table lists the logical operators −
Assume Boolean variables A holds true and variable B holds false, then −

Operator Description Example


&& (logical and) Called Logical AND operator. If both the operands (A && B) is false
are non-zero, then the condition becomes true.

|| (logical or) Called Logical OR Operator. If any of the two (A || B) is true


operands are non-zero, then the condition becomes
true.
! (logical not) Called Logical NOT Operator. Use to reverses the !(A && B) is true
logical state of its operand. If a condition is true
then Logical NOT operator will make false.

Example:-
public class LogicalExample {
public static void main(String[] args) {
boolean A = true, B = false;

System.out.println("A && B: " + (A && B)); // false


System.out.println("A || B: " + (A || B)); // true
System.out.println("!A: " + (!A)); // false
System.out.println("!B: " + (!B)); // true
}
}
OUTPUT:-
A && B: false
A || B: true
!A: false
!B: true

Bitwise Operators:
Bitwise operators are used to perform operations at the binary (bit) level. These operators work on
individual bits of numbers. They are commonly used in low-level programming, encryption, and
performance optimization.
Java defines several bitwise operators, which can be applied to the integer types, long, int, short,
char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13;
now in binary format they will be as follows −

a = 0011 1100
b = 0000 1101
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

The following table lists the bitwise operators −


Assume integer variable A holds 60 and variable B holds 13 then −
Operator Description Example
& (bitwise and) Binary AND Operator copies a bit to the result if it (A & B) will give 12 which is
exists in both operands. 0000 1100
| (bitwise or) Binary OR Operator copies a bit if it exists in (A | B) will give 61 which is
either operand. 0011 1101
^ (bitwise Binary XOR Operator copies the bit if it is set in (A ^ B) will give 49 which is
XOR) one operand but not both. 0011 0001
⁓ (bitwise Binary Ones Complement Operator is unary and (⁓A ) will give -61 which is
compliment) has the effect of 'flipping' bits. 1100 0011 in 2's complement
form due to a signed binary
number.

<< (left shift) Binary Left Shift Operator. The left operands A << 2 will give 240 which is
value is moved left by the number of bits specified 1111 0000
by the right operand.

>> (right shift) Binary Right Shift Operator. The left operands A >> 2 will give 15 which is
value is moved right by the number of bits 1111
specified by the right operand.

>>> (zero fill Shift right zero fill operator. The left operands A >>>2 will give 15 which is
right shift) value is moved right by the number of bits 0000 1111
specified by the right operand and shifted values
are filled up with zeros.

Example
public class BitwiseExample {
public static void main(String[] args) {
int A = 60; // 0011 1100
int B = 13; // 0000 1101

System.out.println("A & B: " + (A & B)); // 12 (0000 1100)


System.out.println("A | B: " + (A | B)); // 61 (0011 1101)
System.out.println("A ^ B: " + (A ^ B)); // 49 (0011 0001)
System.out.println("~A: " + (~A)); // -61 (1100 0011 in 2's complement)
System.out.println("A << 2: " + (A << 2)); // 240 (1111 0000)
System.out.println("A >> 2: " + (A >> 2)); // 15 (0000 1111)
System.out.println("A >>> 2: " + (A >>> 2)); // 15 (0000 1111)
}
}
OUTPUT:-
A & B: 12
A | B: 61
A ^ B: 49
~A: -61
A << 2: 240
A >> 2: 15
A >>> 2: 15

Constants in Java
A constant is a variable whose value cannot be changed once it has been initialized. Java doesn't
have built-in support for constants. To define a variable as a constant, we just need to add the
keyword "final" in front of the variable declaration.
It is not mandatory that we assign values to constants during declaration.

Syntax of Java Constant


final float pi = 3.14f;

The above statement declares the float variable "pi" as a constant with a value of 3.14f. We cannot
change the value of "pi" at any point in time in the program. Later, if we try to do that by using a
statement like "pi=5.25f", Java will throw errors at compile time itself.

Structure and execution of java program:-


A typical structure of a Java program contains the following elements:
• Package declaration
• Import statements
• Comments
• Class definition
• Class variables, Local variables
• Methods/Behaviors
• Main Method

Execution: -
• Java is a platform-independent language, meaning the same program can run on different
operating systems like Windows, Linux, or macOS.
• This platform independence is possible because of the Java Virtual Machine (JVM), which
can run Java bytecode on any system that has a compatible JVM installed.
• We write code in Java using .java files, which are human-readable source code.
• This Java code is compiled by the Java Compiler (javac) into bytecode, which is stored in
.class files.
• Bytecode is a platform-independent, intermediate code that JVM understands, not human-
readable, and not tied to any specific operating system.
• The JVM reads the bytecode and converts it into machine-specific instructions, producing
the final program output.
• We cannot write bytecode directly; we always write Java source code and compile it to
generate bytecode.
• To run a Java program, we must indicate which class contains the main() method, because
it's the starting point of execution for the JVM.

Implementation:
Consider simple printing program is written somewhere on the local directory in a machine.

// Java Program to Illustrate Compilation and Execution


// Stages

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Print command
System.out.print("Welcome to Java");
}
}

Output:-
Welcome to Java
Let us understand the real compilation and execution process.
Step 1: Let us create a file writing simple printing code in a text file and saving it with ".java"
extension.
Step 2: Open the terminal(here we are using macOS)and go to the Desktop directory using the
command below as follows.
cd /Users/mayanksolanki/GFG.java
Step 3: Let us try to compile our program with the below command
javac GFG.java
Step 4: Lastly, run it with the below command as follows:
java GFG

Command Line Arguments in Java:


Java command-line argument is an argument, i.e., passed at the time of running the Java program.
In Java, command-line arguments passed from the console can be received by the Java program
and used as input. The users can pass the arguments during the execution, bypassing the command-
line arguments inside the main() method.

Why Use Command Line Arguments?


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

Working of Command-Line Arguments:


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

Example:
/*Slip 11A – Write a menu driven java program using command line arguments for the following:
1. Addition
2. Subtraction
3. Multiplication
4. Division*/

package com.slipsprogram;

public class Slip11A {


public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Please provide 2 numbers and an operation (add/sub/mul/div)");
return;
}
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
String op = args[2];

switch (op.toLowerCase()) {
case "add":
System.out.println("Addition: " + (a + b));
break;
case "sub":
System.out.println("Subtraction: " + (a - b));
break;
case "mul":
System.out.println("Multiplication: " + (a * b));
break;
case "div":
if (b != 0)
System.out.println("Division: " + ((float) a / b));
else
System.out.println("Cannot divide by zero");
break;
default:
System.out.println("Invalid operation");
}
}
}
Steps to Run the programs:-
1. Right click on program
2.
3. Select your project and main class and Click on Apply
4. Go to Arguments Tab give the arguments in program arguments click on apply and click
on run

Arrays in Java :
In Java, an array is an important linear data structure that allows us to store multiple values of the
same type.

• Arrays in Java are objects, like all other objects in Java, arrays implicitly inherit from the
java.lang.Object 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
• The index of an array starts from 0.
public class Hello {
public static void main(String[] args) {

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

// traversing array
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
}

Output:
40 55 63 17 22 68 89 97 89

One-Dimensional Array
• One of the most commonly used types of arrays is the one-dimensional array. It represents
a simple list of elements where each item can be accessed using a single index.
• Basic operations on a one-dimensional array is include the accessing elements, inserting
elements, deleting elements, searching for elements and sorting elements.
• This Java program demonstrates the implementation of the one-dimensional array and it
performs the basic operations like initialization, accessing elements, inserting elements,
deleting elements, searching for elements and sorting elements:

import java.util.Arrays;
// Driver Class
public class Hello {

// Main Function
public static void main(String[] args)
{
// Initializing an array
int[] numbers = new int[5];

// Inserting elements into the array


numbers[0] = 10;
numbers[1] = 30;
numbers[2] = 20;
numbers[3] = 50;
numbers[4] = 40;

// Accessing elements in the array


System.out.println("Element at index 0: " + numbers[0]);

System.out.println("Element at index 3: " + numbers[3]);

// Deleting an element from the array


deleteElement(numbers,2);
// Delete element at index 2

System.out.println(
"Array after deleting element at index 2: "
+ Arrays.toString(numbers));

// Searching for an element in the array


int searchElement = 30;
int index = searchElement(numbers, searchElement);
if (index != -1) {
System.out.println("Element " + searchElement
+ " found at index "
+ index);
}
else {
System.out.println("Element " + searchElement
+ " not found in the array");
}

// Sorting the array


Arrays.sort(numbers);
System.out.println("Sorted array: "
+ Arrays.toString(numbers));
}

// Function to delete an element from the array


public static void deleteElement(int[] arr, int index)
{
if (index < 0 || index >= arr.length) {
System.out.println(
"Invalid index. Element cannot be deleted.");
}
else {
for (int i = index; i < arr.length - 1; i++) {
arr[i] = arr[i + 1];
}

arr[arr.length - 1] = 0;
// Set the last element to 0 or default
// value
}
}

// Function to search for an element in the array


public static int searchElement(int[] arr, int element)
{
for (int i = 0; i < arr.length; i++) {
if (arr[i] == element) {
// Element found, return its index
return i;
}
}

// Element not found


return -1;
}
}

Output:-
Element at index 0: 10
Element at index 3: 50
Array after deleting element at index 2: [10, 30, 50, 40, 0]
Element 30 found at index 1
Sorted array: [0, 10, 30, 40, 50]

Multidimensional Arrays In Java


Multidimensional arrays are used to store the data in rows and columns, where each row can
represent another individual array are multidimensional array.

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

Parameters:
data_type: Type of data to be stored in the array. For example: int, char, etc.
dimension: The dimension of the array created. For example: 1D, 2D, etc.
array_name: Name of the array
size1, size2, ..., sizeN: Sizes of the dimensions respectively.

Examples:

// Two dimensional array:


int[][] arr2d = new int[3][5];

// Three dimensional array:


int[][][] arr3d = new int[3][5][7];

Program:-
import java.io.*;

public class Geeks


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

// Multidimensional array declaration


int[][] arr;

// Initializing the size of row and column respectively


arr = new int[1][3];

// Initializing the values


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

// Display the values using index


System.out.println("arr[0][0] = " + arr[0][0]);
System.out.println("arr[0][1] = " + arr[0][1]);
System.out.println("arr[0][2] = " + arr[0][2]);
}
}
output:-
arr[0][0] = 3
arr[0][1] = 5
arr[0][2] = 7

String, String Buffer :

String represents sequence of characters enclosed within the double quotes. “abc”, “JAVA”,
“123”, “A” are some examples of strings. In many languages, strings are treated as character
arrays. But In java, strings are treated as objects. To create and manipulate the strings, Java
provides three classes.

1) java.lang.String (From JDK 1.0)

2) java.lang.StringBuffer (From JDK 1.5)

3) java.lang.StringBuilder (From JDK 1.5)

Let’s discuss some introductory points about these three classes.

• All these three classes are members of java.lang package and they are final classes. That
means you can’t create subclasses to these three classes.
• All three classes implement Serializable and CharSequence interface.
• java.lang.String objects are immutable in java. That is, once you create String objects, you
can’t modify them. Whenever you try to modify the existing String object, a new String
object is created with modifications. Existing object is not at all altered. Where as
java.lang.StringBuffer and java.lang.StringBuilder objects are mutable. That means, you
can perform modifications to existing objects.
• Only String and StringBuffer objects are thread safe. StringBuilder objects are not thread
safe. So whenever you want immutable and thread safe string objects, use java.lang.String
class and whenever you want mutable as well as thread safe string objects then use
java.lang.StringBuffer class.
• In all three classes, toString() method is overrided. So. whenever you use reference
variables of these three types, they will return contents of the objects not physical address
of the objects.
• hashCode() and equals() methods are overrided only in java.lang.String class but not in
java.lang.StringBuffer and java.lang.StringBuilder classes.
• There is no reverse() and delete() methods in String class. But, StringBuffer and
StringBuilder have reverse() and delete() methods.
• In case of String class, you can create the objects without new operator. But in case of
StringBuffer and StringBuilder class, you have to use new operator to create the objects.

Built In Packages and Classes :

In Java, Packages are used to avoid naming conflicts and to control the access of classes, interfaces,
sub-classes, etc. A package can be defined as a group of similar types of classes, sub-classes,
interfaces, or enumerations, etc. Using packages makes it easier to locate or find the related classes
and packages provide a good structure or outline of the project with a huge amount of classes and
files.
Types of Packages in Java
Packages are divided into two parts, which are listed below:

• Built-in packages: These are the predefined packages provided by the JDK (Java
Development Kit). They are present in the .jar files and include packages such as java.lang,
java.util, and java.io
• User-defined packages: These packages are created by us to organize our own classes and
interfaces in a meaningful way.

Hierarchical Structure of Java Packages


The image below demonstrates the hierarchical structure of Java packages and their related class
files.

Examples of Built-in Packages


java.sql: Provides the classes for accessing and processing data stored in a database. Classes like
Connection, DriverManager, PreparedStatement, ResultSet, Statement, etc. are part of this
package.
java.lang: Contains classes and interfaces that are fundamental to the design of the Java
programming language. Classes like String, StringBuffer, System, Math, Integer, etc. are part of
this package.
java.util: Contains the collections framework, some internationalization support classes,
properties, random number generation classes. Classes like ArrayList, LinkedList, HashMap,
Calendar, Date, Time Zone, etc. are part of this package.
java.net: Provides classes for implementing networking applications. Classes like Authenticator,
HTTP Cookie, Socket, URL, URLConnection, URLEncoder, URLDecoder, etc. are part of this
package.
java.io: Provides classes for system input/output operations. Classes like BufferedReader,
BufferedWriter, File, InputStream, OutputStream, PrintStream, Serializable, etc. are part of this
package.
java.awt: Contains classes for creating user interfaces and for painting graphics and images.
Classes like Button, Color, Event, Font, Graphics, Image, etc. are part of this package.
java.util:
The java.util package is a standard package of Java SDK. It contains the collections framework,
legacy collection classes, event model, date and time facilities, internationalization, and
miscellaneous utility classes. This package is very useful as it provides commonly used Collections
like ArrayList, HashMap, Set etc. Java.util provides StrinTokenizer classes for String operations
and similarly other utility classes for event model handlings, date and time operations and lot more.
This reference will take you through simple and practical methods available in java.util package.

Importing java.util Package


• Being an inbuilt package of Java, we're not required to download any external library
for java.util package and its all classes can be imported using following syntax:
import java.util.*;
• Here we've used * operator to import all classes from java.util package and now any class can
be used in the program. In case of specific class, for example ArrayList, we can import a class
using following syntax:
import java.util.ArrayList;

Why java.util Package is used in Java Programs


Java.util package classes contains utility classes like collections frameworks, String operations
utilities, Date and Time operations utilities. Following list shows some of the categories of classes
of java.util package.
• Collections − ArrayList, HashMap, Dictionary are few of the classes of large set of
Collection classes availble in java.util package. These classes provides commonly used
operations on large data sets.
• Date Time Operations − GregorianCalendar, Timezone are some of the classes of utility
classes availble in java.util package. These classes provides commonly used operations on
date and time.
• String Manipulations − StringTokenizer is an important utility class availble in java.util
package. This class provides a lot of operations to manipulate strings.
• Enumerations − Enumeration class of java.util package provides operations on set of
values like iterations, comparison etc.
• Exceptions − java.util package contains various commonly occuring exceptions like
ConcurrentModificationException, InputMismatchException etc.

Important classes in java.util Package


Following is the list of important classes in java.util.package:
• ArrayDeque − This class provides resizable-array and implements the Deque interface. This
class and its iterator implement all of the optional methods of the Collection and Iterator
interfaces.
• ArrayList − This class provides resizable-array and implements the List interface. The
ArrayList class extends AbstractList and implements the List interface. ArrayList supports
dynamic arrays that can grow as needed.
• Arrays − This class contains a static factory that allows arrays to be viewed as lists. The
ArrayList class contains various methods for manipulating arrays (such as sorting and
searching).
• BitSet − This class creates a special type of array that holds bit values. The BitSet array can
increase in size as needed. This makes it similar to a vector of bits. This is a legacy class but it
has been completely re-engineered in Java 2, version 1.4. The Java BitSet class implements a
vector of bits that grows as needed.
• Calendar − This class is an abstract class that provides methods for converting between a
specific instant in time and a set of calendar fields such as YEAR, MONTH,
DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as
getting the date of the next week.
• Collections − This class consists exclusively of static methods that operate on or return
collections.
• Currency − This class represents a currency. The Currency class is designed so that there's
never more than one Currency instance for any given currency, this is the reason behind no
public constructor.
• Date − This class represents a specific instant in time, with millisecond precision.
• Dictionary − This class is the abstract parent of any class, such as Hashtable, which maps keys
to values.
• EnumMap − This class is a specialized Map implementation for use with enum keys. All of
the keys in an enum map must come from a single enum type that is specified, explicitly or
implicitly, when the map is created.
• EnumSet − This class is a specialized Set implementation for use with enum keys. All of the
keys in an enum set must come from a single enum type that is specified, explicitly or
implicitly, when the set is created.
• Formatter − This class provides support for layout justification and alignment, common
formats for numeric, string, and date/time data, and locale-specific output.
• GregorianCalendar − This class is a concrete subclass of Calendar and provides the standard
calendar system used by most of the world. It is a hybrid calendar that supports both the Julian
and Gregorian calendar systems with the support of a single discontinuity, which corresponds
by default to the Gregorian date when the Gregorian calendar was instituted.
• HashMap − This class is the Hash table based implementation of the Map interface.
• HashSet − This class implements the Set interface, backed by a hash table.
• HashTable − This class implements a hashtable, which maps keys to values.
• IdentityHashMap − This class implements the Map interface with a hash table, using
reference-equality in place of object-equality when comparing keys (and values).
• LinkedHashMap − This class is Hash table and Linked list implementation of the Map
interface, with predictable iteration order.
• LinkedHashSet − This class is Hash table and Linked list implementation of the Set interface,
with predictable iteration order.
• LinkedList − This class operations perform we can expect for a doubly-linked list. Operations
that index into the list will traverse the list from the beginning or the end, whichever is closer
to the specified index.
• ListResourceBundle − This class is an abstract subclass of ResourceBundle that manages
resources for a locale in a convenient and easy to use list.
• Locale − This class object represents a specific geographical, political, or cultural region.
• Observable − This class represents an observable object, or "data" in the model-view
paradigm. The class can be subclassed to represent an object that the application wants to have
observed.
• PriorityQueue − This class is an unbounded priority queue based on a priority heap. The
elements of the priority queue are ordered according to their natural ordering, or by a
Comparator provided at queue construction time, depending on which constructor is used.
• Properties − This class is a class which represents a persistent set of properties. The Properties
can be saved to a stream or loaded from a stream.
• PropertyPermission − This class is a class for property permissions.
• PropertyResourceBundle − This class is a concrete subclass of ResourceBundle that
manages resources for a locale using a set of static strings from a property file.
• Random − This class instance is used to generate a stream of pseudorandom numbers. The
class uses a 48-bit seed, which is modified using a linear congruential formula.
• ResourceBundle − This class contain locale-specific objects. The class allows you to write
programs that can be easily localized, or translated, into different languages.
• ResourceBundle.Control − This class collaborates with the factory methods for loading
resource bundles.
• Scanner − This class is a simple text scanner which can parse primitive types and strings using
regular expressions.
• ServiceLoader − This class is a simple service-provider loading facility. Service loaders
always execute in the security context of the caller.Trusted system code should typically
invoke the methods in this class, and the methods of the iterators which they return, from within
a privileged security context.
• SimpleTimeZone − This class is a concrete subclass of TimeZone that represents a time zone
for use with a Gregorian calendar.
• Stack − Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack
only defines the default constructor, which creates an empty stack. Stack includes all the
methods defined by Vector, and adds several of its own.
• StringTokenizer − This class allows an application to break a string into tokens. This class is
a legacy class that is retained for compatibility reasons although its use is discouraged in new
code.
• Timer − This class provides facility for threads to schedule tasks for future execution in a
background thread.
• TimerTask − This class represents a task that can be scheduled for one-time or repeated
execution by a Timer.
• TimeZone − This class represents a time zone offset, and also figures out daylight savings.
• TreeMap − This class is the Red-Black tree based implementation of the Map interface. The
TreeMap class guarantees that the Map will be in ascending key order.
• TreeSet − This class implements the Set interface. The TreeSet class guarantees that the Set
will be in ascending key order and backed by a TreeSet.
• UUID − This class class represents an immutable universally unique identifier (UUID). There
are four different basic types of UUIDs: time-based, DCE security, name-based, and randomly
generated UUIDs.
• Vector − Vector implements a dynamic array. The Vector class implements a growable array
of objects. Similar to an Array, it contains components that can be accessed using an integer
index.

Java.lang package in Java

Provides classes that are fundamental to the design of the Java programming language. The most
important classes are Object, which is the root of the class hierarchy, and Class, instances of which
represent classes at run time.
Following are the Important Classes in Java.lang package :
• Boolean: The Boolean class wraps a value of the primitive type boolean in an object.
• Byte: The Byte class wraps a value of primitive type byte in an object.
• Character – Set 1, Set 2: The Character class wraps a value of the primitive type char in an
object.
• Character.Subset: Instances of this class represent particular subsets of the Unicode character
set.
• Character.UnicodeBlock: A family of character subsets representing the character blocks in
the Unicode specification.
• Class – Set 1, Set 2 : Instances of the class Class represent classes and interfaces in a running
Java application.
• ClassLoader: A class loader is an object that is responsible for loading classes.
• ClassValue: Lazily associate a computed value with (potentially) every type.
• Compiler: The Compiler class is provided to support Java-to-native-code compilers and
related services.
• Double: The Double class wraps a value of the primitive type double in an object.
• Enum: This is the common base class of all Java language enumeration types.
• Float: The Float class wraps a value of primitive type float in an object.
• InheritableThreadLocal: This class extends ThreadLocal to provide inheritance of values
from parent thread to child thread: when a child thread is created, the child receives initial
values for all inheritable thread-local variables for which the parent has values.
• Integer :The Integer class wraps a value of the primitive type int in an object.
• Long: The Long class wraps a value of the primitive type long in an object.
• Math – Set 1, Set 2: The class Math contains methods for performing basic numeric operations
such as the elementary exponential, logarithm, square root, and trigonometric functions.
• Number: The abstract class Number is the superclass of classes BigDecimal, BigInteger, Byte,
Double, Float, Integer, Long, and Short.
• Object: Class Object is the root of the class hierarchy.
• Package: Package objects contain version information about the implementation and
specification of a Java package.
• Process: The ProcessBuilder.start() and Runtime.exec methods create a native process and
return an instance of a subclass of Process that can be used to control the process and obtain
information about it.
• ProcessBuilder: This class is used to create operating system processes.
• ProcessBuilder.Redirect: Represents a source of subprocess input or a destination of
subprocess output.
• Runtime: Every Java application has a single instance of class Runtime that allows the
application to interface with the environment in which the application is running.
• RuntimePermission: This class is for runtime permissions.
• SecurityManager: The security manager is a class that allows applications to implement a
security policy.
• Short: The Short class wraps a value of primitive type short in an object.
• StackTraceElement: An element in a stack trace, as returned by Throwable.getStackTrace().
• StrictMath- Set1, Set2: The class StrictMath contains methods for performing basic numeric
operations such as the elementary exponential, logarithm, square root, and trigonometric
functions.
• String- Set1, Set2: The String class represents character strings.
• StringBuffer: A thread-safe, mutable sequence of characters.
• StringBuilder: A mutable sequence of characters.
• System: The System class contains several useful class fields and methods.
• Thread: A thread is a thread of execution in a program.
• ThreadGroup: A thread group represents a set of threads.
• ThreadLocal: This class provides thread-local variables.
• Throwable: The Throwable class is the superclass of all errors and exceptions in the Java
language.
• Void: The Void class is an uninstantiable placeholder class to hold a reference to the Class
object representing the Java keyword void.

You might also like