Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
23 views47 pages

S12BLH31 Unit I Java

The document provides an overview of Java programming, detailing its key features such as simplicity, platform independence, and robust security. It explains the Java Virtual Machine (JVM) and Java bytecode, emphasizing their roles in executing Java programs across different platforms. Additionally, it covers the installation of the Java Development Kit (JDK) on Windows, data types in Java, and the concept of tokens used in Java programming.

Uploaded by

chhandanandi26
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)
23 views47 pages

S12BLH31 Unit I Java

The document provides an overview of Java programming, detailing its key features such as simplicity, platform independence, and robust security. It explains the Java Virtual Machine (JVM) and Java bytecode, emphasizing their roles in executing Java programs across different platforms. Additionally, it covers the installation of the Java Development Kit (JDK) on Windows, data types in Java, and the concept of tokens used in Java programming.

Uploaded by

chhandanandi26
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/ 47

SATHYABMA INSTITUTE OF SCIENCE AND TECHNOLOGY SCHOOL OF COMPUTING

S12BLH31 PROGRAMMING IN JAVA

Unit – I

Features of Java Language

Java is a powerful and versatile programming language known for its platform independence and
wide range of features.

Here are some key features of Java:

 Simple and Easy to Learn: Java was designed to be easy to write, compile, and debug. Its
syntax is similar to C++, making it familiar to many programmers.
 Platform Independence: Java programs can run on any device that has a Java Runtime
Environment (JRE), due to its "write once, run anywhere" (WORA) principle. This is achieved
through the use of the Java Virtual Machine (JVM).
 Object-Oriented: Java is fully object-oriented, which means it supports principles like
inheritance, encapsulation, and polymorphism.
 Robust and Secure: Java puts a lot of emphasis on early checking for possible errors, as well
as runtime checking, which makes Java programs more robust. It also includes security
features to protect against viruses and other malicious attacks.
 Multithreaded: Java supports multithreading, allowing concurrent execution of two or more
parts of a program for maximum utilization of CPU.
 High Performance: Java is known for its performance. The use of Just-In-Time (JIT) compilers
improves performance by compiling bytecode into native machine code at runtime.
 Distributed: Java is designed for distributed computing. RMI (Remote Method Invocation) and
EJB (Enterprise JavaBeans) are used for creating distributed applications.
 Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt
to an evolving environment. Java programs can carry extensive amount of run-time
information that can be used to verify and resolve accesses to objects at run-time.
 Rich Standard Library: Java has a large and comprehensive standard library that provides APIs
for I/O, networking, utilities, and XML parsing, among others.
 Automatic Memory Management: Java manages memory allocation and deallocation
automatically through garbage collection. This helps developers avoid manual memory
management and reduces the likelihood of memory leaks.

These features make Java suitable for a wide variety of applications, from enterprise-level
applications to mobile apps and embedded systems.

JVM (Java Virtual Machine)

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed. JVMs are available for many hardware and
software platforms (i.e. JVM is platform dependent).

What is JVM

It is:

1. A specification where working of Java Virtual Machine is specified. But implementation


provider is independent to choose the algorithm. Its implementation has been provided
by Oracle and other companies.

2. An implementation Its implementation is known as JRE (Java Runtime Environment).

3. Runtime Instance Whenever you write java command on the command prompt to run
the java class, an instance of JVM is created.

What it does

The JVM performs following operation:

o Loads code

o Verifies code

o Executes code

o Provides runtime environment


JVM provides definitions for the:

o Memory area

o Class file format

o Register set

o Garbage-collected heap

o Fatal error reporting etc.

BYTECODE
What is Java Bytecode?

Java bytecode is the instruction set for the Java Virtual Machine. It acts similar to an assembler
which is an alias representation of a C++ code. As soon as a java program is compiled, java
bytecode is generated. In more apt terms, java bytecode is the machine code in the form of a
.class file. With the help of java bytecode we achieve platform independence in java.

How does it works?

When we write a program in Java, firstly, the compiler compiles that program and a bytecode is
generated for that piece of code. When we wish to run this .class file on any other platform, we
can do so. After the first compilation, the bytecode generated is now run by the Java Virtual
Machine and not the processor in consideration. This essentially means that we only need to
have basic java installation on any platforms that we want to run our code on. Resources required
to run the bytecode are made available by theJava Virtual Machine, which calls the processor to
allocate the required resources. JVM's are stack-based so they stack implementation to read the
codes.
Fig: Working Process of JVM

Advantage of Java Bytecode

Platform independence is one of the soul reasons for which James Gosling started the formation
of java and it is this implementation of bytecode which helps us to achieve this. Hence bytecode
is a very important component of any java program.The set of instructions for the JVM may differ
from system to system but all can interpret the bytecode. A point to keep in mind is that
bytecodes are non-runnable codes and rely on the availability of an interpreter to execute and
thus the JVM comes into play.

Bytecode is essentially the machine level language which runs on the Java Virtual Machine.
Whenever a class is loaded, it gets a stream of bytecode per method of the class. Whenever that
method is called during the execution of a program, the bytecode for that method gets
invoked.Javac not only compiles the program but also generates the bytecode for the program.
Thus, we have realized that the bytecode implementation makes Java a platform-
independent language. This helps to add portability to Java which is lacking in languages like C or
C++. Portability ensures that Java can be implemented on a wide array of platforms like desktops,
mobile devices, severs and many more. Supporting this, Sun Microsystems captioned JAVA
as "write once, read anywhere" or "WORA" in resonance to the bytecode interpretation.

How to Install the Java JDK in Windows


Java is one of the most favored programming languages for back-end development (apart from
JavaScript). Java is also a fairly popular choice for mobile and desktop development. the exact
method to install JDK, or the Java Development Environment, a software development
environment necessary for running Java on your PC.

Run a Check for Java JDK on Your PC


Before we move to the installation, though, it’s useful to see if JDK is already present in your
system. To do that, go to the Start menu search bar, type in ‘cmd,’ and select the Best match.
Once you have opened the Command prompt, type the following command and hit Enter:

As soon as you do that the Command prompt will check your PC for JDK. If your Windows 11
doesn’t have the JDK installed, you should see something like this on your cmd screen:
Alternatively, the JDK can also be checked through the Control Panel. Here's how:

1. Head to Start menu search bar, type in 'control panel', and select the best match.
2. Head to Programs and Features menu and see if you can find the JDK there.
To install the JDK, jump to the section below if you cannot find it using either method.

Installing Java JDK in Windows 11

To install the JDK installer, we need to head to Oracle’s website first. Here’s how:

1. Go to the Java Downloads section of the Oracle website, and download the x64
Installer from there.
2. As soon as the download completes, launch the installation file and click on Yes.
3. The JDK installation wizard will be launched. In the dialog box, click on Next.
4. On the next screen, you’ll be asked for the location of your file. Click on Next.
5. Once the JDK installation is complete, click on Close.
By the end of this process the Java development kit will be successfully installed on your PC.

Installing and Running Java in Windows 11

While many programming environments will allow you to compile and run a program within that
environment, you can also compile and run in Command Prompt on Windows or the Terminal on
Mac. The process is nearly the same. To create a simple Java program, you need to create a class
that contains the main method. Let's understand the requirement first.

The requirement for Java Hello World Example

For executing any Java program, the following software or application must be properly installed.

o Install the JDK if you don't have installed it, download the JDK and install it.

o Set path of the jdk/bin directory.

o Create the Java program

o Compile and run the Java program


Creating Hello World Example

o Let's create the hello java program:

class prg{
public static void main(String args[]){
System.out.println("Sathyabama");
System.out.println("CSE ");
}
}

Save the above file as myprg.java.

To compile: javac myprg.java

To execute: java prg

 Open a command prompt window and go to the directory where you saved the java
program (myprg.java). Assume it's C:\.
 Type 'javac myprg.java' and press enter to compile your code. If there are no errors in
your code, the command prompt will take you to the next line (Assumption: The path
variable is set).
 Now, type 'java prg' to run your program.
 You will be able to see the result printed on the window.
The compilation flow of a Java program involves several steps from writing the code to executing
it. Here's a simplified overview of the process:

1. Writing Java Source Code:


o You write your Java program in a text editor or an Integrated Development
Environment (IDE) like IntelliJ IDEA, Eclipse, or Visual Studio Code.
2. Saving the Source Code:
o Save the Java source code with a .java extension. For example, MyProgram.java.
3. Compiling Java Source Code:
o Compilation: The Java source code is compiled using the javac (Java compiler)
command. This step translates the human-readable Java source code into
bytecode.
o javac MyProgram.java
o During compilation, the Java compiler checks syntax errors and type errors in your
code. If there are errors, it will report them, and you'll need to fix them in your
source code and recompile.
4. Generating Bytecode:

 If the compilation is successful, javac generates bytecode in a file named


MyProgram.class. This bytecode is platform-independent and can be executed on any
system that has the Java Virtual Machine (JVM) installed.

5. Executing Java Bytecode:

 Interpretation/Execution: To run your Java program, use the java command


followed by the name of the class that contains the main method (entry point of the
program).
 java MyProgram

The JVM loads the bytecode, verifies it, and then executes it line by line. During
execution, the JVM manages memory, threads, and other resources needed by the Java
program.

6. Output:
o If your program includes output statements (e.g., System.out.println("Hello,
World!");), the results are displayed in the console or other specified output
streams.

Key Points:

 Compilation: Converts .java source code into .class bytecode.


 Bytecode: Platform-independent intermediate code.
 Execution: JVM executes bytecode.
This compilation flow ensures that Java programs are portable and can run on any device with a
JVM, making Java a popular choice for cross-platform development.

Datatypes in Java

In Java, data types specify the type of data that variables can hold. Java supports two categories
of data types: primitive data types and non-primitive data types.

Primitive Data Types:

Primitive data types are the most basic data types in Java. They are predefined by the language
and are directly supported by the Java Virtual Machine (JVM). There are eight primitive data types
in Java:

1. Integral Types:
o byte: 8-bit signed integer. Range: -128 to 127.
o short: 16-bit signed integer. Range: -32,768 to 32,767.
o int: 32-bit signed integer. Range: -2^31 to 2^31 - 1.
o long: 64-bit signed integer. Range: -2^63 to 2^63 - 1.
2. Floating-Point Types:
o float: 32-bit IEEE 754 floating point. Used for decimal numbers with single
precision.
o double: 64-bit IEEE 754 floating point. Used for decimal numbers with double
precision.
3. Other Types:
o boolean: Represents a boolean value, true or false.
o char: Represents a single 16-bit Unicode character. Range: '\u0000' (0) to '\uffff'
(65,535).
Reference/ Non-primitive Data Types:

Non-primitive data types are not directly supported by the JVM but are instead references to
objects. They include:

 Class Types: Such as user-defined classes and built-in classes like String.
 Interface Types: Interfaces implemented by classes.
 Array Types: Arrays of any data type, including arrays of objects.
 Enumeration Types: A special type for defining collections of constants.

Examples: Here are examples of declaring variables using primitive and non-primitive data types
in Java:

// Primitive data types

byte myByte = 10;

short myShort = 100;

int myInt = 1000;

long myLong = 100000L; // L suffix indicates it's a long

float myFloat = 3.14f; // f suffix indicates it's a float

double myDouble = 3.14159;

boolean myBoolean = true;

char myChar = 'A'; //

Reference/Non-primitive data types:

String myString = "Hello, Java!";


Object myObject = new Object(); // Object is a superclass of all classes in Java

int[] myIntArray = {1, 2, 3, 4, 5}; // Array of integers

Key Points:

 Primitive Data Types: Stored directly in memory, and their values are accessed directly.
 Reference Data Types: Stored as references (addresses) to objects stored in memory.
 Default Values: Primitive types have default values (0 for numeric types, false for
boolean, '\u0000' for char), while reference types default to null if not initialized explicitly.
 Type Conversion: Java supports type casting between compatible data types to avoid loss
of data.

Understanding these data types is fundamental for writing efficient and effective Java programs,
as they dictate how data is stored, manipulated, and used throughout your code.

JAVA TOKENS
In Java programming, tokens are the smallest units of a program that are meaningful to the
compiler. These tokens are used to build the syntax and semantics of Java code. Here are the
main types of tokens in Java:

Keywords:

 Keywords are reserved words that have special meanings and cannot be used for other
purposes in the code. Examples include class, public, static, void, if, else, for, while, etc.

Identifiers:

 Identifiers are names given to variables, methods, classes, packages, and interfaces in
Java. They must follow certain rules (e.g., start with a letter, underscore, or dollar sign,
and consist of letters, digits, underscores, and dollar signs).
Literals:

 Literals represent constant values that can be assigned to variables. Java supports various
types of literals:
o Integer literals: e.g., 123, -456
o Floating-point literals: e.g., 3.14, 2.0f
o Boolean literals: true and false
o Character literals: e.g., 'A', '\n'
o String literals: e.g., "Hello, Java!"

Operators:

 Operators perform operations on variables and values. Java supports various types of
operators, including arithmetic (+, -, *, /), assignment (=), comparison (==, !=, <, >), logical
(&&, ||, !), bitwise (&, |, ^, ~, <<, >>, >>>), etc.

Separators:

 Separators are characters used to separate tokens in Java code. Examples include
parentheses (), braces {}, brackets [], commas ,, semicolons ;, periods ., etc.

Comments:

 Comments are not considered tokens by the compiler but are used to add explanations
or notes within the code. Java supports single-line (//) and multi-line (/* */) comments.

Example Java Code with Tokens:

Here's a simple Java program annotated with its tokens:

public class HelloWorld {

public static void main(String[] args) { // Keywords: public, class, static, void, main, String
// Single-line comment

System.out.println("Hello, World!"); // Operators: ., (), String literal: "Hello, World!"

Key Points:

 Tokens in Java are the building blocks of the language's syntax.


 They include keywords, identifiers, literals, operators, separators, and comments.
 Understanding and correctly using tokens is essential for writing valid and readable Java
programs.

Mastering Java tokens enables you to effectively write, understand, and debug Java code by
breaking down its components into manageable units recognized by the Java compiler and
interpreter.

ACCESS MODIFIERS IN JAVA

There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.

3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.

4. Public: The access level of a public modifier is everywhere. It can be accessed from within
the class, outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.

1) Private

The private access modifier is accessible only within the class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data member
and private method. We are accessing these private members from outside the class, so there is
a compile-time error.

class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from
outside the class. For example:

class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}

2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is accessible
only within package. It cannot be accessed from outside the package. It provides more
accessibility than private. But, it is more restrictive than protected, and public.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.

//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}

In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.

3) Protected

The protected access modifier is accessible within package and outside the package but through
inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.

It provides more accessibility than the default modifer.

In this example, we have created the two packages pack and mypack. The A class of pack package
is public, so can be accessed from outside the package. But msg method of this package is
declared as protected, so it can be accessed from outside the class only through inheritance.

//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello

4) Public

The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.

Example of public access modifier

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
} }

Output:Hello

JAVA ACCESS MODIFIERS WITH METHOD OVERRIDING


If you are overriding any method, overridden method (i.e. declared in subclass) must not be more
restrictive.

class A{
protected void msg(){System.out.println("Hello java");}
}
public class Simple extends A{
void msg(){System.out.println("Hello java");}//C.T.Error
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
}
}

The default modifier is more restrictive than protected. That is why, there is a compile-time error.

Key Points:

 Access modifiers in Java are crucial for encapsulation and defining the visibility of classes,
methods, variables, and constructors.
 They ensure proper data hiding and help maintain code integrity and security.
 Choosing the appropriate access modifier depends on the desired level of visibility and
encapsulation for each element within your Java program.

Understanding and correctly applying access modifiers is fundamental to writing maintainable


and secure Java code, ensuring that classes and their members are appropriately accessible
according to design and security requirements.

OPERATORS IN JAVA

In Java, operators are special symbols that perform operations on variables and values. They can
be categorized into several types based on their functionality. Here’s an overview of the main
types of operators in Java:

1. Arithmetic Operators:

Arithmetic operators are used to perform mathematical operations on numeric operands


(variables or values).

 Addition (+): Adds two operands.


 Subtraction (-): Subtracts the second operand from the first.
 Multiplication (*): Multiplies two operands.
 Division (/): Divides the first operand by the second.
 Modulus (%): Returns the remainder when the first operand is divided by the second.

Example:

int a = 10; int b = 3; int sum = a + b; // 13

int difference = a - b; // 7

int product = a * b; // 30
int quotient = a / b; // 3

int remainder = a % b; // 1

2. Relational Operators:

Relational operators are used to establish relationships between operands. They return a
boolean value (true or false).

Equal to (==): Checks if two operands are equal.


Not equal to (!=): Checks if two operands are not equal.
Greater than (>): Checks if the left operand is greater than the right.
Less than (<): Checks if the left operand is less than the right.
Greater than or equal to (>=): Checks if the left operand is greater than or equal to the right.
Less than or equal to (<=): Checks if the left operand is less than or equal to the right.
Example:
int x = 5;
int y = 3;
boolean isEqual = (x == y); // false
boolean isNotEqual = (x != y); // true
boolean isGreater = (x > y); // true
boolean isLess = (x < y); // false

3. Logical Operators:

Logical operators are used to combine conditional statements.

 Logical AND (&&): Returns true if both operands are true.


 Logical OR (||): Returns true if at least one operand is true.
 Logical NOT (!): Reverses the logical state of its operand.

Example:
boolean condition1 = true;
boolean condition2 = false;
boolean result1 = (condition1 && condition2); // false
boolean result2 = (condition1 || condition2); // true
boolean result3 = !condition1; // false

4. Assignment Operators:

Assignment operators are used to assign values to variables.

 Assignment (=): Assigns the value on the right to the variable on the left.
 Addition assignment (+=): Adds the value on the right to the variable on the left and
assigns the result to the variable on the left.
 Subtraction assignment (-=): Subtracts the value on the right from the variable on the left
and assigns the result to the variable on the left.
 Multiplication assignment (*=): Multiplies the variable on the left by the value on the
right and assigns the result to the variable on the left.
 Division assignment (/=): Divides the variable on the left by the value on the right and
assigns the result to the variable on the left.
 Modulus assignment (%=): Computes the modulus of the variable on the left with the
value on the right and assigns the result to the variable on the left.

Example:

int num1 = 10;

int num2 = 5;

num1 += num2;

// num1 is now 15 (equivalent to num1 = num1 + num2)


5. Increment and Decrement Operators:

Increment (++) and decrement (--) operators are used to increase or decrease the value of a
variable by 1, respectively.

Example:

int count = 5;

count++; // count is now 6 (increment)

count--; // count is now 5 again (decrement)

6. Bitwise Operators:

Bitwise operators perform operations on bits of integer operands.

 Bitwise AND (&): Performs a bitwise AND operation.


 Bitwise OR (|): Performs a bitwise OR operation.
 Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation.
 Bitwise complement (~): Flips the bits of the operand.
 Left shift (<<): Shifts bits to the left.
 Right shift (>>): Shifts bits to the right.
 Unsigned right shift (>>>): Shifts bits to the right, filling leftmost bits with zeros.

Example:

int a = 5; // binary: 0101

int b = 3; // binary: 0011

int resultAnd = a & b; // 1 (binary: 0001)

int resultOr = a | b; // 7 (binary: 0111)

int resultXor = a ^ b; // 6 (binary: 0110)


7. Conditional (Ternary) Operator:

The conditional operator (? :) evaluates a boolean expression and returns one of two values
depending on whether the expression is true or false.

Example:

int x = 5; int y = 3;

int max = (x > y) ? x : y; // max is assigned the value of x because x > y is true

Summary:

Understanding and effectively using operators in Java is crucial for performing various tasks such
as arithmetic operations, comparisons, logical evaluations, and bitwise manipulations. Mastery
of these operators is fundamental to writing efficient and concise Java code.

ARRAYS IN JAVA

In Java, an array is a fixed-size, ordered collection of elements of the same type. Arrays allow you
to store multiple values of the same data type under a single variable name, making it easier to
manage and access related data. Here's a comprehensive overview of arrays in Java:

Declaration and Initialization:

1. Declaration:
To declare an array in Java, you specify the data type of the elements followed by square brackets
[] and the array variable name. The size (number of elements) of the array can be specified
explicitly or left empty for later initialization.
// Declaring an array of integers with 5 elements
int[] numbers;
2. Initialization:

After declaring an array, you can initialize it by creating an array object using the new keyword
and specifying the number of elements in the array.
// Initializing the array with 5 elements
numbers = new int[5];

Alternatively, you can combine declaration and initialization in a single statement:

// Declaration and initialization in one line

int[] numbers = new int[5];

Initializing with Initial Values:


You can also initialize the array with initial values using an array initializer list {}:
// Initializing an array with initial values
int[] numbers = {10, 20, 30, 40, 50};

Accessing Elements:
Array elements are accessed using zero-based indexing, where the index starts from 0 for the
first element and goes up to length-1 for the last element.

// Accessing elements of the array

int firstElement = numbers[0]; // Accessing the first element (index 0)

int thirdElement = numbers[2]; // Accessing the third element (index 2)

Array Length:
You can get the length of an array using the length property, which returns the number of
elements in the array.
// Getting the length of the array
int arrayLength = numbers.length; // Returns 5 (length of the 'numbers' array)

Iterating Through an Array:


You can iterate through the elements of an array using loops such as for loop or enhanced for-
each loop.

Using a for loop:


for (int i = 0; i < numbers.length; i++)
{
System.out.println("Element at index " + i + ": " + numbers[i]);
}
Using an enhanced for-each loop:
for (int num : numbers)
{
System.out.println("Element: " + num);
}

In Java, you can create arrays of objects as well. Each element in the array stores a reference
(address) to an object of the specified type.

// Array of Strings

String[] names = {"Alice", "Bob", "Charlie"}; // Accessing elements

String firstPerson = names[0]; // "Alice"


Arrays are Fixed Size:

Arrays in Java are fixed in size once initialized. The size needs to be specified during array creation,
and it cannot be changed later. If dynamic resizing is required, consider using ArrayList from the
java.util package.

Key Points:

 Arrays in Java are used to store multiple values of the same type.
 They are accessed using zero-based indexing.
 Arrays must be initialized with a specific size or with initial values.
 Arrays provide efficient data access but have a fixed size once created.

Understanding arrays is fundamental for handling collections of data in Java effectively, especially
when dealing with structured data that requires ordered storage and retrieval of elements.

MULTIDIMENSIONAL ARRAYS

In Java, multidimensional arrays are arrays of arrays. They allow you to store data in a table-like
structure with rows and columns, or even higher dimensions for more complex data organization.
Here's a detailed explanation of multidimensional arrays in Java:

Declaration and Initialization:


1. Two-Dimensional Array:

A two-dimensional array is the most common form of multidimensional array in


Java. It can be thought of as a matrix with rows and columns.

Declaration:
To declare a two-dimensional array, you specify the data type of the elements followed by two
sets of square brackets [][] and the array variable name.
// Declaration of a 2D array of integers
int[][] matrix;
Initialization:

To initialize a two-dimensional array, you use the new keyword to create an array object and
specify the dimensions (number of rows and columns).
// Initializing a 2D array with 3 rows and 4 columns
matrix = new int[3][4];

Alternatively, you can combine declaration and initialization in one line:

// Declaration and initialization in one line


int[][] matrix = new int[3][4];

Initializing with Initial Values:


You can also initialize a two-dimensional array with initial values using an array initializer list {}.
Each nested array represents a row of the matrix.
// Initializing a 2D array with initial values
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

Accessing Elements:

Elements in a two-dimensional array are accessed using two indices: one for the row and one for
the column.
// Accessing elements of the 2D array
int element = matrix[1][2]; // Accessing element at row 1, column 2 (value: 6)
Array Length:

You can get the length of each dimension of a multidimensional array using the length property.
int rows = matrix.length; // Number of rows (3 in this case)
int columns = matrix[0].length; // Number of columns in the first row (4 in this case)

Iterating Through a 2D Array:

You can iterate through the elements of a two-dimensional array using nested loops, such as a
for loop.
// Iterating through a 2D array
for (int i = 0; i < matrix.length; i++) { // Outer loop for rows
for (int j = 0; j < matrix[i].length; j++) { // Inner loop for columns
System.out.print(matrix[i][j] + " "); // Accessing and printing each element
}
System.out.println(); // Move to the next line after each row
}

Three-Dimensional Array and Higher Dimensions:

Java also supports three-dimensional arrays and arrays of higher dimensions, although they are
less commonly used. The concept is similar to a 2D array but extended into additional
dimensions.

Declaration and Initialization of a 3D Array:


// Declaration and initialization of a 3D array
int[][][] threeDArray = new int[3][4][2]; // 3 matrices, each with 4 rows and 2 columns

Accessing Elements of a 3D Array:


// Accessing elements of a 3D array
int value = threeDArray[1][2][1]; // Accessing element in the second matrix, third row, second
column

Key Points:

 Multidimensional arrays in Java allow you to organize data in multiple dimensions, such
as rows and columns (2D), matrices (3D), etc.
 Initialization: Arrays must be initialized with specific dimensions.
 Accessing Elements: Elements in a multidimensional array are accessed using multiple
indices.
 Iterating: Nested loops are typically used to iterate through multidimensional arrays.
 Fixed Size: Once initialized, the size of multidimensional arrays cannot be changed.

Understanding multidimensional arrays is important for handling complex data structures in Java,
especially when dealing with data that naturally fits into a multi-dimensional grid or matrix
format.

CONTROL STRUCTURES IN JAVA

In Java, control structures are used to control the flow of execution in a program. They enable
you to make decisions, repeat code blocks, and selectively execute code based on conditions.
Java provides several types of control structures:

1. Conditional Statements:

Conditional statements allow you to execute certain code blocks based on the evaluation of a
boolean expression.
a. if Statement:

The if statement executes a block of code if a specified condition is true.

int num = 10;


if (num > 0) {
System.out.println("Number is positive");
}

b. if-else Statement:

The if-else statement executes one block of code if the condition is true and another block if the
condition is false.

int num = -5;


if (num > 0) {
System.out.println("Number is positive");
} else {
System.out.println("Number is non-positive");
}

c. else-if ladder:

The else-if ladder allows you to check multiple conditions sequentially.

int num = 0;
if (num > 0) {
System.out.println("Number is positive");
} else if (num < 0) {
System.out.println("Number is negative");
} else {
System.out.println("Number is zero");
}

2. Looping Statements:

Looping statements allow you to repeat execution of a block of code multiple times based on a
condition.

a. for Loop:

The for loop iterates a block of code a fixed number of times.


for (int i = 1; i <= 5; i++) {
System.out.println("Count is: " + i);
}

b. while Loop:

The while loop repeats a block of code as long as a specified condition is true.

int i = 1;
while (i <= 5) {
System.out.println("Count is: " + i);
i++;
}
c. do-while Loop:

The do-while loop is similar to the while loop, but it guarantees at least one execution of the
block of code.

int i = 1;
do {
System.out.println("Count is: " + i);
i++;
} while (i <= 5);

3. Branching Statements:

Branching statements alter the normal flow of execution by transferring control to another part
of the program.

a. break Statement:

The break statement terminates the loop or switch statement it is in.


for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Terminate loop when i is 5
}
System.out.println("Count is: " + i);
}

b. continue Statement:

The continue statement skips the current iteration of a loop and continues with the next

iteration.

for (int i = 1; i <= 5; i++) {


if (i == 3) {
continue; // Skip iteration when i is 3
}
System.out.println("Count is: " + i);
}
c. return Statement:

The return statement exits from the current method, optionally returning a value.

public int add(int a, int b) {


return a + b; // Return sum of a and b
}

4. Switch Statement:

The switch statement allows a variable to be tested for equality against a list of values. It executes
one block of code based on the value of the variable.

int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
Key Points:

 Control structures in Java provide mechanisms to make decisions, repeat code blocks,
and alter the flow of execution.
 Conditional statements (if, if-else, else-if) allow you to execute code based on conditions.
 Looping statements (for, while, do-while) allow you to repeat execution of code based
on a condition or number of iterations.
 Branching statements (break, continue, return) alter the normal flow of execution within
loops or methods.
 The switch statement provides an alternative to nested if-else statements for multiple
conditional branches based on the value of a variable.

Understanding and effectively using these control structures is essential for writing structured
and efficient Java programs that perform various tasks based on different conditions and
requirements.

STRING CLASS WITH EXAMPLES

The String class in Java is a fundamental class used to handle sequences of characters. Here are
some key features and examples of the String class:

Creating Strings:

 Using string literals


 Using the new keyword

Common Methods:

 length()
 charAt(int index)
 substring(int beginIndex, int endIndex)
 equals(Object anObject)
 compareTo(String anotherString)
 toUpperCase()
 toLowerCase()
 trim()
 replace(char oldChar, char newChar)
 split(String regex)
 Concatenation:
 Using + operator
 Using concat() method
 String Immutability:

Strings are immutable; once created, they cannot be changed.

STRING HANDLING IN JAVA

String handling in Java involves manipulating sequences of characters. In Java, strings are objects
of the String class, which provides a rich set of methods for working with strings. Here are some
key points about string handling in Java:

String Creation: Strings in Java can be created using string literals ("text") or by creating instances
of the String class (new String("text")).

Immutability: Strings in Java are immutable, meaning once a String object is created, it cannot be
changed. Operations on strings (like concatenation) result in new String objects.

String Concatenation: In Java, you can concatenate strings using the + operator or the concat()
method.

Example:

String str1 = "Hello";


String str2 = "World";

String result = str1 + " " + str2; // "Hello World"

String Methods: The String class provides various methods for manipulating strings, such as:

length(): Returns the length of the string.

charAt(int index): Returns the character at the specified index.

substring(int beginIndex), substring(int beginIndex, int endIndex): Returns a substring.

toLowerCase(), toUpperCase(): Converts the string to lowercase or uppercase.

trim(): Removes leading and trailing whitespace.

startsWith(String prefix), endsWith(String suffix): Checks if the string starts or ends with the
specified prefix or suffix.

indexOf(String str), lastIndexOf(String str): Returns the index of the first or last occurrence of the
specified substring.

String Comparison: Use equals() method to compare the content of two strings. Use compareTo()
method for lexicographical comparison.

String Formatting: Java provides several ways to format strings, including String.format() method
and printf() method from PrintStream/PrintWriter.

String Handling Efficiency: When manipulating strings frequently, consider using StringBuilder
(for mutable sequences of characters) or StringBuffer (thread-safe version of StringBuilder) for
better performance compared to repeated string concatenation.

String handling is fundamental in Java programming due to its ubiquitous use in various
operations, from simple text manipulation to more complex data parsing and processing tasks.
STRING HANDLING WITH EXAMPLES:

Sure, let's dive deeper into string handling in Java with some examples to illustrate various
operations:

1. Creating Strings

String str1 = "Hello"; // Using string literal

String str2 = new String("World"); // Creating string object

2. String Concatenation

String message = str1 + " " + str2; // Concatenating strings

System.out.println(message); // Output: Hello World

3. String Length

String str = "Java Programming";

int length = str.length(); // Getting length of the string

System.out.println("Length of the string: " + length); // Output: Length of the string: 17

4. Accessing Characters

char firstChar = str.charAt(0); // Accessing first character

char lastChar = str.charAt(str.length() - 1); // Accessing last character

System.out.println("First character: " + firstChar); // Output: First character: J

System.out.println("Last character: " + lastChar); // Output: Last character: g


5. Substrings

String substring1 = str.substring(5); // Starting from index 5 to end

String substring2 = str.substring(5, 12); // From index 5 to 12 (exclusive)

System.out.println("Substring 1: " + substring1); // Output: Substring 1: Programming

System.out.println("Substring 2: " + substring2); // Output: Substring 2: Program

6. String Comparison

String str3 = "java";

String str4 = "Java";

boolean isEqual = str3.equals(str4); // Case-sensitive comparison

boolean isEqualIgnoreCase = str3.equalsIgnoreCase(str4); // Case-insensitive comparison

System.out.println("isEqual: " + isEqual); // Output: isEqual: false

System.out.println("isEqualIgnoreCase: " + isEqualIgnoreCase); // Output: isEqualIgnoreCase:


true

7. Searching within Strings

String sentence = "Java is a popular programming language";

int index1 = sentence.indexOf("Java"); // Finding index of substring

int index2 = sentence.lastIndexOf("language"); // Finding last occurrence

System.out.println("Index of 'Java': " + index1); // Output: Index of 'Java': 0


System.out.println("Index of 'language': " + index2); // Output: Index of 'language': 30

8. String Modification

String oldString = " Trim me! ";

String newString = oldString.trim(); // Removing leading and trailing whitespace

System.out.println("Original string: '" + oldString + "'");

System.out.println("Trimmed string: '" + newString + "'");

9. Converting Case

String mixedCase = "jAVa pROgRAMmiNG";

String lowerCase = mixedCase.toLowerCase(); // Converting to lowercase

String upperCase = mixedCase.toUpperCase(); // Converting to uppercase

System.out.println("Lowercase: " + lowerCase); // Output: lowercase: java programming

System.out.println("Uppercase: " + upperCase); // Output: UPPERCASE: JAVA PROGRAMMING

10. Formatting Strings

String formattedString = String.format("The value of pi is %.2f", Math.PI); // Formatting numbers

System.out.println(formattedString); // Output: The value of pi is 3.14

These examples cover various aspects of string handling in Java, including basic operations like
concatenation and substring extraction, searching within strings, modifying string content, and
formatting strings for specific output. String handling is a fundamental skill in Java programming
due to its extensive use in handling textual data efficiently.
STRING BUFFER CLASS
A StringBuffer class in Java is used to create mutable (modifiable) strings. Unlike the String class,
which creates immutable objects, StringBuffer allows you to modify the string content without
creating a new object. Here's an overview of some common methods of the StringBuffer class,
along with examples.

Common Methods of StringBuffer

append(): Adds text to the end of the current string.

insert(): Inserts text at a specified position.

replace(): Replaces text within a specified range.

delete(): Deletes text within a specified range.

reverse(): Reverses the sequence of characters.

capacity(): Returns the current capacity of the buffer.

length(): Returns the length (number of characters) of the string.

setLength(): Sets the length of the buffer.

Examples

Example 1: Creating and Appending Strings

public class StringBufferExample {

public static void main(String[] args) {

StringBuffer sb = new StringBuffer("Hello");

sb.append(" World");

System.out.println(sb); // Output: Hello World


}

Example 2: Inserting Strings

public class StringBufferExample {

public static void main(String[] args) {

StringBuffer sb = new StringBuffer("Hello");

sb.insert(5, " Java");

System.out.println(sb); // Output: Hello Java

Example 3: Replacing Strings

public class StringBufferExample {

public static void main(String[] args) {

StringBuffer sb = new StringBuffer("Hello World");

sb.replace(6, 11, "Java");

System.out.println(sb); // Output: Hello Java

Example 4: Deleting Strings

public class StringBufferExample {

public static void main(String[] args) {

StringBuffer sb = new StringBuffer("Hello Java");


sb.delete(5, 10);

System.out.println(sb); // Output: Hello

Example 5: Reversing Strings

public class StringBufferExample {

public static void main(String[] args) {

StringBuffer sb = new StringBuffer("Hello");

sb.reverse();

System.out.println(sb); // Output: olleH

Example 6: Capacity and Length

public class StringBufferExample {

public static void main(String[] args) {

StringBuffer sb = new StringBuffer("Hello");

System.out.println("Capacity: " + sb.capacity()); // Output: Capacity: 21

System.out.println("Length: " + sb.length()); // Output: Length: 5

sb.append(" Java Programming");

System.out.println("Capacity after append: " + sb.capacity()); // Output: Capacity after


append: 42

System.out.println("Length after append: " + sb.length());


// Output: Length after append: 22

Example 7: Setting Length

public class StringBufferExample {

public static void main(String[] args) {

StringBuffer sb = new StringBuffer("Hello");

sb.setLength(10);

System.out.println(sb); // Output: Hello

System.out.println("Length: " + sb.length()); // Output: Length: 10

These examples demonstrate how you can use the StringBuffer class to perform various
operations on strings in Java.

You might also like