Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
16 views

Java Programming language

Good

Uploaded by

Dinesh Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Java Programming language

Good

Uploaded by

Dinesh Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Java Programming Language

What is Programming Language

A programming language is a set of rules and instructions that allows humans to communicate with
computers and write software. It enables us to create programs by defining what tasks the computer
should perform, step by step. Just like spoken languages help people communicate with each other,
programming languages allow us to give commands to computers.

Why Java?

Here are some lesser-known facts about Java:

1. Originally Called Oak: Java was originally called "Oak" after an oak tree that stood outside the
office of James Gosling, the creator of Java. The name was later changed to Java after the island of
Java in Indonesia, which is famous for its coffee.

2. Java Was Initially Designed for Interactive TV: Java was first developed by Sun Microsystems with
the idea of using it for interactive television. However, it was too advanced for the digital cable
television industry at that time, so it was repurposed for the Internet.

3. Java Was Inspired by C++: Java was designed as a simpler, more secure alternative to C++. Many of
its features are similar to C++, but it eliminated some of the more complex and error-prone aspects
of C++, like pointer arithmetic.

4. Java’s Write Once, Run Anywhere: One of Java’s most famous slogans is "Write Once, Run
Anywhere" (WORA). This means that Java code can be written on one platform (like Windows) and
run on another platform (like Linux or macOS) without modification.

5. Java is Not the Same as JavaScript: Despite the similar names, Java and JavaScript are entirely
different programming languages with different use cases. Java is a full-fledged, general-purpose
programming language, while JavaScript is primarily used for adding interactivity to web pages.

6. Java Is One of the Most Popular Programming Languages: Java has been consistently ranked as one
of the most popular programming languages in the world for many years, largely due to its
widespread use in enterprise applications, Android development, and big data technologies.

7. Java is Open Source: In 2006, Sun Microsystems made Java an open-source project under the GNU
General Public License (GPL). This allows developers around the world to contribute to and use the
Java Development Kit (JDK) for free.

8. JVM as a Multi-Language Platform: The Java Virtual Machine (JVM), which runs Java bytecode, can
also run code written in other languages like Kotlin, Groovy, Scala, and Clojure. This makes the JVM a
versatile platform for many different programming languages.

9. Garbage Collection: Java was one of the first mainstream programming languages to feature
automatic garbage collection, which helps manage memory automatically by cleaning up unused
objects, reducing the chances of memory leaks and other related issues.

1
Other Language

In Other Programming Languages, Your source code will be compiled with the help of the compiler
and later it will be compiled object file this file will only on the same os when it was compiled unless
it will not be executed.

In Java Language

But in Java Programming Language the compiler will not directly produce the object file instead it will
convert the source code into byte code like o and 1 after that JVM(java virtual machine) will convert
and compile the byte code and send the code to the processor for execution. So we don’t need the
same os for execution of code instead we can execute the code in different platform, byecode is

2
common for all processor. This is also one of the reason java is popular language and also plantform
Independent.

Understanding the Java platform involves knowing about three key components: JVM, JRE, and JDK.
Here’s a simple breakdown of each:

1. JVM (Java Virtual Machine):

What it is: The JVM is the runtime environment that executes Java bytecode. It provides a platform-
independent way of executing Java programs.

Function: When you compile a Java program, the code is converted into bytecode (a platform-
independent intermediate form). The JVM reads this bytecode and translates it into machine code
specific to the host operating system, allowing the program to run.

Platform Independence: JVM allows Java to achieve the "Write Once, Run Anywhere" capability
because the same bytecode can run on any platform that has a compatible JVM.

2. JRE (Java Runtime Environment):

What it is: The JRE is a package of everything needed to run a Java program, including the JVM, core
libraries, and supporting files.

Function: The JRE provides the libraries, Java Virtual Machine, and other components to run
applications written in Java. It does not include development tools like compilers or debuggers.

Use Case: If you just want to run Java applications on your machine, you only need to install the JRE.

3
3. JDK (Java Development Kit):

what it is: The JDK is a complete software development kit that includes the JRE, a compiler (`javac`),
and various tools like `javadoc`, `javap`, and more.

Function: The JDK is used for developing Java applications and applets. It provides tools for
compiling, debugging, and executing Java programs.

Use Case: If you want to develop Java applications, you need the JDK. It includes everything in the
JRE, plus additional tools necessary for development.

Relationship Between Them:

JVM is a part of the JRE.

JRE is included in the JDK.

Data Types

In Java, data types are divided into two categories: primitive data types and reference/object data
types. Each type is designed to store specific kinds of information.

1. Primitive Data Types

Primitive data types are the most basic data types in Java. They are predefined by the language and
named by a reserved keyword. Java has 8 primitive data types:

a. Integer Types:

• byte:

o Size: 8 bits

o Range: -128 to 127

o Usage: Useful for saving memory in large arrays where the memory savings actually
matter.

• short:

o Size: 16 bits

o Range: -32,768 to 32,767

o Usage: Also used to save memory, short is a smaller data type than int.

• int:

o Size: 32 bits

o Range: -2^31 to 2^31 - 1

o Usage: Default data type for integers in Java.

4
• long:

o Size: 64 bits

o Range: -2^63 to 2^63 - 1

o Usage: Used when a wider range than int is needed.

b. Floating-Point Types:

• float:

o Size: 32 bits

o Range: Approximately ±3.40282347E+38F (6-7 significant decimal digits)

o Usage: Useful for saving memory in large arrays of floating-point numbers. Sufficient
for storing 6 to 7 decimal digits.

• double:

o Size: 64 bits

o Range: Approximately ±1.79769313486231570E+308 (15 significant decimal digits)

o Usage: Default data type for decimal values, generally the best choice for real
numbers.

c. Character Type:

• char:

o Size: 16 bits (using Unicode encoding)

o Range: 0 to 65,535

o Usage: Used to store a single character (e.g., 'a', 'A', '1', etc.).

d. Boolean Type:

• boolean:

o Size: 1 bit (the exact size is not precisely defined)

o Values: true or false

o Usage: Used for simple flags that track true/false conditions.

2. Reference/Object Data Types

Reference types are used to refer to objects. They are created using defined classes and interfaces.
Unlike primitive data types, reference types do not hold the data value directly; instead, they store
the memory address where the object is located.

Examples:

• String:

o A String is a sequence of characters. In Java, strings are objects of the String class.

5
o Example: String greeting = "Hello, World!";

• Arrays:

o An array is an object that holds multiple values of the same type.

o Example: int[] numbers = {1, 2, 3, 4, 5};

• Classes and Interfaces:

o Any user-defined class or interface can be used as a data type.

o Example: Person person = new Person();

Summary Table:

Type Description Size Example

byte 8-bit integer 8 bits byte b = 100;

short 16-bit integer 16 bits short s = 10000;

int 32-bit integer 32 bits int i = 100000;

long 64-bit integer 64 bits long l = 100000L;

float 32-bit floating-point 32 bits float f = 234.5f;

double 64-bit floating-point 64 bits double d = 123.4;

char Single 16-bit Unicode character 16 bits char c = 'A';

boolean Boolean value (true or false) 1 bit boolean flag = true;

String A sequence of characters (reference type) N/A String str = "Hello";

These data types are the building blocks of any Java program, and understanding them is crucial for
effective programming in Java.

Why Use import java.util.*;?

When you use the statement import java.util.*; in a Java program, you are importing all the classes
and interfaces from the java.util package. This allows you to use any of the classes or interfaces from
that package without having to specify the full package name each time.

1. Convenience:

o Instead of importing each class individually, like import java.util.ArrayList;, import


java.util.HashMap;, etc., you can use import java.util.*; to import all the classes in
one go.

o This is particularly useful when you need to use multiple classes from the same
package, saving you from writing multiple import statements.

6
2. Commonly Used Classes:

o The java.util package contains many commonly used utility classes, such as ArrayList,
HashMap, Date, Calendar, Collections, Scanner, etc. Since these classes are
frequently used, importing the entire package can make coding faster and easier.

Why the Main method?

The main method in Java serves as the entry point for the execution of any Java application. When
you run a Java program, the Java Virtual Machine (JVM) looks for the main method to start the
program's execution. This method is where the program begins and ends its execution.

Key Characteristics of the main Method:

1. Signature:

o The main method has a specific signature that must be followed:

public static void main(String[] args)

o public: The method must be public so that it is accessible by the JVM from outside
the class.

o static: The method must be static because it is called by the JVM without creating an
instance of the class.

o void: The method does not return any value. It simply executes the code within it.

o String[] args: This is an array of String objects that stores command-line arguments
passed to the program. If no arguments are passed, this array is empty.

2. Purpose:

o Entry Point: The main method is the starting point for the JVM to start executing the
code in a Java application. Without it, the JVM wouldn’t know where to begin.

o Execution Flow: The code inside the main method is executed sequentially, starting
from the first line to the last.

o Command-Line Arguments: The main method can accept command-line arguments


via the String[] args parameter. These arguments can be used to influence the
behavior of the program at runtime.

3. Example of a Simple main Method:

public class MainExample {

public static void main(String[] args) {

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

o In this example, the program prints "Hello, World!" to the console when executed.
The main method is the entry point where this action begins.

7
Basic Java Program Example:

// This is a simple Java program that prints "Hello, World!" to the console.

public class HelloWorld {

// The main method is the entry point of any Java application.

public static void main(String[] args) {

// The System.out.println method prints the string to the console.

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

Explanation:

1. Class Declaration:

o public class HelloWorld { ... }

o Defines a public class named HelloWorld. In Java, every application must have at
least one class. The name of the file should match the class name, so this file should
be named HelloWorld.java.

2. Main Method:

o public static void main(String[] args) { ... }

o This is the main method, which is the entry point for the Java application. The JVM
looks for this method to start executing the program.

o public makes it accessible from outside the class.

o static means you don’t need to create an instance of the class to call this method.

o void means this method does not return any value.

o String[] args is an array of String arguments that can be passed to the program from
the command line. It is not used in this simple example.

3. System.out.println:

o System.out.println("Hello, World!");

o This line prints the string "Hello, World!" to the console. System.out is a reference to
the standard output stream, and println is a method that prints the given message
followed by a newline.

8
The Scanner class in Java is part of the java.util package and is used for reading input from various
sources, including user input from the console, files, and other input streams. It provides methods
for parsing and converting different types of input into usable data types.

Key Features of Scanner:

1. Reading User Input:

o Commonly used to read input from the console. For example, reading strings,
integers, and floating-point numbers.

2. Parsing Input:

o Can parse input into different types (e.g., int, double, String) using its various
methods.

3. Flexible Input Sources:

o Besides the console, Scanner can read from files, strings, and other input streams.

Basic Usage of Scanner:

Here’s a simple example demonstrating how to use Scanner to read user input from the console:

import java.util.Scanner;

public class ScannerExample {

public static void main(String[] args) {

// Create a Scanner object to read input from the console

Scanner sc = new Scanner(System.in);

// Prompt the user for their name

System.out.print("Enter your name: ");

String name = scanner.nextLine(); // Read a line of text

// Prompt the user for their age

System.out.print("Enter your age: ");

int age = scanner.nextInt(); // Read an integer

// Prompt the user for their height

System.out.print("Enter your height in meters: ");

double height = scanner.nextDouble(); // Read a double

9
// Display the collected information

System.out.println("Hello, " + name + "!");

System.out.println("You are " + age + " years old.");

System.out.println("Your height is " + height + " meters.");

// Close the Scanner object to free resources

scanner.close();

Explanation:

1. Import Statement:

o import java.util.Scanner; is necessary to use the Scanner class.

2. Creating a Scanner Object:

o Scanner scanner = new Scanner(System.in);

o Creates a Scanner object to read input from the standard input stream (the console).

3. Reading Input:

o scanner.nextLine(): Reads a line of text input from the user.

o scanner.nextInt(): Reads the next integer from the input.

o scanner.nextDouble(): Reads the next double value from the input.

4. Closing the Scanner:

o scanner.close(); is used to close the Scanner object. This is a good practice to free up
resources, though it's not always strictly necessary for console input.

Common Methods of Scanner:

• next(): Reads the next token from the input as a String. Useful for reading single words or
tokens.

• nextLine(): Reads the entire line of input as a String. Useful for reading full sentences or
lines.

• nextInt(): Reads the next token as an int. Throws an exception if the input is not a valid
integer.

• nextDouble(): Reads the next token as a double. Throws an exception if the input is not a
valid double.

• hasNext(): Checks if there is another token in the input.

10
• hasNextInt(): Checks if the next token is an integer.

• hasNextDouble(): Checks if the next token is a double.

Java Output

In Java, generating output typically involves displaying information to the console or a graphical user
interface (GUI). Here are some common methods for producing output in Java:

1. Console Output

Using System.out.println

• Purpose: Print a line of text to the console followed by a newline.

• Example:

public class ConsoleOutputExample {

public static void main(String[] args) {

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

Output:

Hello, World!

Using System.out.print

• Purpose: Print text to the console without adding a newline at the end.

• Example:

public class ConsoleOutputExample {

public static void main(String[] args) {

System.out.print("Hello, ");

System.out.print("World!");

Output:

Hello, World!

11
Using System.out.printf

• Purpose: Print formatted text to the console, similar to printf in C/C++. Allows for formatting
strings, numbers, etc.

• Example:

public class ConsoleOutputExample {

public static void main(String[] args) {

int age = 25;

double height = 5.9;

System.out.printf("Age: %d years%n", age);

System.out.printf("Height: %.1f feet%n", height);

Output:

Age: 25 years

Height: 5.9 feet

Java Comments

Java, comments are used to explain and annotate code, making it easier to understand and maintain.
They are ignored by the Java compiler and do not affect the execution of the program. Java supports
three types of comments:

1. Single-Line Comments

• Syntax:

// This is a single-line comment

• Usage:

o Used to comment on a single line of code.

o The comment starts with // and continues to the end of the line.

• Example:

public class SingleLineCommentExample {

public static void main(String[] args) {

// Print a greeting to the console

System.out.println("Hello, World!"); // This prints a message

12
}

2. Multi-Line Comments

• Syntax:

/*

* This is a multi-line comment.

* It can span multiple lines.

*/

• Usage:

o Used for longer explanations or to comment out multiple lines of code.

o The comment starts with /* and ends with */. You can use * to align comment text
for readability, but it's optional.

Example:

public class MultiLineCommentExample {

public static void main(String[] args) {

/*

* This block of code prints a message to the console.

* It demonstrates the use of multi-line comments.

*/

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

Variables

In Java, variables are used to store data that can be used and manipulated throughout a program.
Variables are fundamental to programming and come with specific rules and characteristics in Java.
Here’s a breakdown of the basics:

1. Variable Declaration and Initialization

• Declaration: Specifies the variable's name and type.

• Initialization: Assigns a value to the variable.

Syntax:

type variableName; // Declaration

variableName = value; // Initialization

13
// Combined declaration and initialization

type variableName = value;

Example:

int age; // Declaration

age = 30; // Initialization

int year = 2024; // Declaration and initialization

2. Variable Types

Variables in Java are classified into two main types:

Example:

int age = 30; // 32-bit integer

float height = 5.9f; // 32-bit floating-point number

char initial = 'A'; // 16-bit Unicode character

boolean isStudent = true; // Represents true or false

Type Casting in Java

In Java, type casting is the process of converting a variable from one data type to another. This
can be done implicitly (automatic) or explicitly (manual) depending on the data types involved.

1. Implicit Casting (Automatic Conversion)

Also known as widening conversion, implicit casting occurs when you convert a smaller data
type to a larger one. This type of casting is done automatically by the Java compiler because it
is safe and does not result in data loss.

Widening Casting (Implicit)

• From byte to short, int, long, float, double

• From short to int, long, float, double

• From int to long, float, double

• From long to float, double

• From float to double

Example:

public class ImplicitCastingExample {

public static void main(String[] args) {

int intValue = 10;

double doubleValue = intValue; // Implicit casting from int to double

14
System.out.println("Double value: " + doubleValue);

In this example:

• int (32-bit) is automatically converted to double (64-bit) without data loss.

2. Explicit Casting (Manual Conversion)

Also known as narrowing conversion, explicit casting is required when converting a larger data
type to a smaller one. This type of casting must be done manually using a cast operator, and it
may result in data loss or overflow if the value exceeds the range of the target type.

Syntax:

targetType variableName = (targetType) expression;

Narrowing Casting (Explicit)

• From double to float, long, int, short, byte

• From float to long, int, short, byte

• From long to int, short, byte

• From int to short, byte

• From short to byte

Example:

public class ExplicitCastingExample {

public static void main(String[] args) {

double doubleValue = 9.78;

int intValue = (int) doubleValue; // Explicit casting from double to int

System.out.println("Integer value: " + intValue);

In this example:

• double (64-bit) is cast to int (32-bit), resulting in loss of the fractional part. The value of
intValue will be 9.

Operators in Java

In Java, operators are special symbols that perform operations on variables and values. They are
essential for performing calculations, making comparisons, and manipulating data. Java operators
can be categorized into several types:

15
1. Arithmetic Operators

These operators are used for mathematical operations.

• Addition (+): Adds two values.

int sum = 5 + 3; // sum is 8

• Subtraction (-): Subtracts one value from another.

int difference = 5 - 3; // difference is 2

• Multiplication (*): Multiplies two values.

int product = 5 * 3; // product is 15

• Division (/): Divides one value by another.

int quotient = 6 / 3; // quotient is 2

• Modulus (%): Returns the remainder of a division operation.

int remainder = 5 % 3; // remainder is 2

2. Relational Operators

These operators are used to compare two values and return a boolean result (true or false).

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

boolean isEqual = (5 == 3); // isEqual is false

• Not equal to (!=): Checks if two values are not equal.

boolean isNotEqual = (5 != 3); // isNotEqual is true

• Greater than (>): Checks if one value is greater than another.

boolean isGreater = (5 > 3); // isGreater is true

• Less than (<): Checks if one value is less than another.

boolean isLess = (5 < 3); // isLess is false

• Greater than or equal to (>=): Checks if one value is greater than or equal to another.

boolean isGreaterOrEqual = (5 >= 3); // isGreaterOrEqual is true

• Less than or equal to (<=): Checks if one value is less than or equal to another.

boolean isLessOrEqual = (5 <= 3); // isLessOrEqual is false

3. Logical Operators

These operators are used to perform logical operations and are commonly used in conditional
statements.

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

boolean result = (5 > 3 && 8 > 6); // result is true

16
• Logical OR (||): Returns true if at least one of the operands is true.

boolean result = (5 > 3 || 8 < 6); // result is true

• Logical NOT (!): Returns true if the operand is false.

boolean result = !(5 > 3); // result is false

4. Assignment Operators

These operators are used to assign values to variables.

• Simple Assignment (=): Assigns a value to a variable.

int a = 5; // Assigns 5 to a

• Add and Assign (+=): Adds the right operand to the left operand and assigns the result.

int a = 5;

a += 3; // Equivalent to a = a + 3; a is now 8

• Subtract and Assign (-=): Subtracts the right operand from the left operand and assigns the
result.

int a = 5;

a -= 3; // Equivalent to a = a - 3; a is now 2

• Multiply and Assign (*=): Multiplies the left operand by the right operand and assigns the
result.

int a = 5;

a *= 3; // Equivalent to a = a * 3; a is now 15

• Divide and Assign (/=): Divides the left operand by the right operand and assigns the result.

int a = 6;

a /= 3; // Equivalent to a = a / 3; a is now 2

• Modulus and Assign (%=): Takes the modulus of the left operand by the right operand and
assigns the result.

int a = 5;

a %= 3; // Equivalent to a = a % 3; a is now 2

5. Unary Operators

These operators operate on a single operand.

• Unary Plus (+): Indicates a positive value (usually optional).

int a = +5; // a is 5

• Unary Minus (-): Negates the value.

int a = -5; // a is -5

17
• Increment (++): Increases the value of a variable by 1.

int a = 5;

a++; // a is now 6

• Decrement (--): Decreases the value of a variable by 1.

int a = 5;

a--; // a is now 4

• Logical NOT (!): Inverts the boolean value.

boolean flag = true;

flag = !flag; // flag is now false

6. Bitwise Operators

These operators perform operations on binary representations of integers.

• AND (&): Performs a bitwise AND.

int a = 5; // 0101 in binary

int b = 3; // 0011 in binary

int result = a & b; // result is 1 (0001 in binary)

• OR (|): Performs a bitwise OR.

int result = a | b; // result is 7 (0111 in binary)

• XOR (^): Performs a bitwise XOR.

int result = a ^ b; // result is 6 (0110 in binary)

• Complement (~): Inverts all the bits.

int result = ~a; // result is -6 (inverts 0101 to 1010)

• Left Shift (<<): Shifts bits to the left.

int result = a << 1; // result is 10 (1010 in binary)

public class LeftShiftExample {

public static void main(String[] args) {

int a = 5; // Binary: 0000 0101

int result = a << 2; // Shift left by 2 positions

// Binary result: 0001 0100 (which is 20 in decimal)

System.out.println("Result of left shift: " + result); // Output: 20

18
}

Explanation:

• Binary representation of 5 is 0000 0101.

• Shifting left by 2 positions: 0000 0101 becomes 0001 0100.

• Decimal value 0001 0100 is 20.

• Right Shift (>>): Shifts bits to the right.

int result = a >> 1; // result is 2 (0010 in binary)

public class RightShiftExample {

public static void main(String[] args) {

int a = 20; // Binary: 0001 0100

int result = a >> 2; // Shift right by 2 positions

// Binary result: 0000 0101 (which is 5 in decimal)

System.out.println("Result of right shift: " + result); // Output: 5

Explanation:

• Binary representation of 20 is 0001 0100.

• Shifting right by 2 positions: 0001 0100 becomes 0000 0101.

• Decimal value 0000 0101 is 5.

• Unsigned Right Shift (>>>): Shifts bits to the right, filling with zeros.

int result = a >>> 1; // result is 2 (0010 in binary)

7. Conditional (Ternary) Operator

This operator is a shorthand for the if-else statement.

• Syntax:

condition ? expressionIfTrue : expressionIfFalse;

• Example:

int a = 5;

int b = (a > 3) ? 10 : 20; // b is 10 because a > 3 is true

19
Java Strings

In Java, strings are a fundamental data type used to represent sequences of characters. The String
class in Java is part of the java.lang package and provides various methods for manipulating and
working with strings.

Creating Strings

1. String Literal

You can create a string using double quotes. This is known as a string literal.

String str1 = "Hello, World!";

2. Using the new Keyword

You can also create a string using the new keyword, which creates a new String object.

String str2 = new String("Hello, World!");

Common String Methods

The String class provides many methods for manipulating and querying strings:

1. Length of a String

String str = "Hello";

int length = str.length(); // Returns 5

2. Concatenation

Combine two strings using the + operator or the concat() method.

String str1 = "Hello";

String str2 = "World";

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

// or

String result2 = str1.concat(" ").concat(str2); // "Hello World"

3. Substring

Extract a substring from a string.

String str = "Hello, World!";

String sub = str.substring(7, 12); // "World"

4. Replace

Replace characters or substrings within a string.

String str = "Hello, World!";

String newStr = str.replace("World", "Java"); // "Hello, Java!"

20
5. To Upper Case / Lower Case

Convert the string to upper case or lower case.

String str = "Hello, World!";

String upper = str.toUpperCase(); // "HELLO, WORLD!"

String lower = str.toLowerCase(); // "hello, world!"

6. Trim

Remove leading and trailing whitespace.

String str = " Hello, World! ";

String trimmed = str.trim(); // "Hello, World!"

7. Index of a Character or Substring

Find the index of a character or substring.

String str = "Hello, World!";

int index = str.indexOf('W'); // 7

int indexSub = str.indexOf("World"); // 7

8. Check Equality

Compare strings for equality.

String str1 = "Hello";

String str2 = "Hello";

boolean isEqual = str1.equals(str2); // true

boolean isEqualIgnoreCase = str1.equalsIgnoreCase("hello"); // true

9. Split

Split a string into an array of substrings based on a delimiter.

String str = "Java,Python,C++";

String[] languages = str.split(","); // ["Java", "Python", "C++"]

10. Char At

Retrieve a character at a specific index.

String str = "Hello";

char ch = str.charAt(1); // 'e'

11. Starts With / Ends With

Check if the string starts or ends with a specific substring.

String str = "Hello, World!";

21
boolean startsWith = str.startsWith("Hello"); // true

boolean endsWith = str.endsWith("World!"); // true

String Immutability

In Java, strings are immutable, which means once a String object is created, it cannot be modified.
Any operation that seems to modify a string actually creates a new String object. This immutability
ensures thread safety and allows strings to be reused effectively.

String Pool

Java maintains a special memory area called the String Pool (or interned string pool) where string
literals are stored. When you create a string literal, Java checks the pool first to see if the string
already exists. If it does, Java reuses the existing string object instead of creating a new one. This
optimizes memory usage.

Example:

String str1 = "Java";

String str2 = "Java";

System.out.println(str1 == str2); // true, because both refer to the same object in the string pool

StringBuilder and StringBuffer

For mutable sequences of characters, Java provides StringBuilder and StringBuffer. Unlike String,
these classes allow modification of the sequence without creating new objects.

• StringBuilder: Not synchronized, recommended for use in single-threaded scenarios.

StringBuilder sb = new StringBuilder("Hello");

sb.append(" World");

String result = sb.toString(); // "Hello World"

• StringBuffer: Synchronized, recommended for use in multi-threaded scenarios.

StringBuffer sb = new StringBuffer("Hello");

sb.append(" World");

String result = sb.toString(); // "Hello World"

Java Math

In Java, mathematical operations and functions are provided by the Math class, which is part of the
java.lang package. This class includes a variety of methods for performing basic and advanced
mathematical computations, such as arithmetic operations, trigonometric functions, logarithmic
functions, and more.

Key Features of the Math Class

1. Basic Arithmetic Operations

22
o Addition, Subtraction, Multiplication, and Division: These are straightforward
operations you can perform using standard arithmetic operators (+, -, *, /).

2. Static Methods: All methods in the Math class are static, which means you can call them
directly on the class without creating an instance.

Commonly Used Methods

1. Absolute Value

Returns the absolute value of a number.

int absValue = Math.abs(-5); // Returns 5

double absValueDouble = Math.abs(-3.14); // Returns 3.14

2. Power

Raises a number to the power of another number.

double power = Math.pow(2, 3); // Returns 8.0 (2^3)

3. Square Root

Returns the square root of a number.

double sqrt = Math.sqrt(16); // Returns 4.0

4. Exponential and Logarithmic Functions

• Exponential: Returns e raised to the power of a given number.

double exp = Math.exp(1); // Returns approximately 2.71828 (e^1)

• Natural Logarithm: Returns the natural logarithm (base e) of a number.

double log = Math.log(10); // Returns approximately 2.30259 (log base e of 10)

• Base-10 Logarithm: Returns the base-10 logarithm of a number.

double log10 = Math.log10(100); // Returns 2.0 (log base 10 of 100)

5. Trigonometric Functions

• Sine: Returns the sine of an angle (in radians).

double sin = Math.sin(Math.PI / 2); // Returns 1.0

• Cosine: Returns the cosine of an angle (in radians).

double cos = Math.cos(0); // Returns 1.0

• Tangent: Returns the tangent of an angle (in radians).

double tan = Math.tan(Math.PI / 4); // Returns 1.0

6. Rounding

• Round: Rounds a floating-point number to the nearest integer.

long rounded = Math.round(3.6); // Returns 4

23
• Floor: Returns the largest integer less than or equal to a given number.

double floor = Math.floor(3.6); // Returns 3.0

• Ceiling: Returns the smallest integer greater than or equal to a given number.

double ceiling = Math.ceil(3.6); // Returns 4.0

7. Minimum and Maximum

• Minimum: Returns the smaller of two values.

int min = Math.min(5, 10); // Returns 5

• Maximum: Returns the larger of two values.

int max = Math.max(5, 10); // Returns 10

8. Random Numbers

Generates a random number between 0.0 (inclusive) and 1.0 (exclusive).

double random = Math.random(); // Returns a random number between 0.0 and 1.0

Example Usage

Here's an example that demonstrates the use of several Math methods:

public class MathExample {

public static void main(String[] args) {

double num1 = -9.5;

double num2 = 16.0;

double num3 = 2.0;

double num4 = 10.0;

System.out.println("Absolute value of " + num1 + ": " + Math.abs(num1));

System.out.println("Square root of " + num2 + ": " + Math.sqrt(num2));

System.out.println(num3 + " raised to the power of 3: " + Math.pow(num3, 3));

System.out.println("Natural logarithm of " + num4 + ": " + Math.log(num4));

System.out.println("Sine of PI/2 radians: " + Math.sin(Math.PI / 2));

System.out.println("Ceiling of 3.6: " + Math.ceil(3.6));

System.out.println("Random number between 0.0 and 1.0: " + Math.random());

24
Conditional Statements

In Java, conditional statements allow you to execute certain blocks of code based on whether a
specified condition is true or false. These statements are fundamental for controlling the flow of a
program. The primary conditional constructs in Java are if, else, else if, switch, and ternary operators.

1. if Statement

The if statement is used to execute a block of code if a specified condition is true.

int number = 10;

if (number > 0) {

System.out.println("The number is positive.");

2. if-else Statement

The if-else statement allows you to execute one block of code if the condition is true, and another
block if it is false.

int number = -5;

if (number > 0) {

System.out.println("The number is positive.");

} else {

System.out.println("The number is not positive.");

3. if-else if-else Statement

The if-else if-else statement is used when you need to evaluate multiple conditions.

int number = 0;

if (number > 0) {

System.out.println("The number is positive.");

} else if (number < 0) {

System.out.println("The number is negative.");

} else {

System.out.println("The number is zero.");

4. switch Statement

The switch statement is used to select one of many code blocks to be executed. It is an alternative to
if-else if-else when dealing with multiple possible values of a single variable.

25
int day = 3;

String dayName;

switch (day) {

case 1:

dayName = "Monday";

break;

case 2:

dayName = "Tuesday";

break;

case 3:

dayName = "Wednesday";

break;

case 4:

dayName = "Thursday";

break;

case 5:

dayName = "Friday";

break;

case 6:

dayName = "Saturday";

break;

case 7:

dayName = "Sunday";

break;

default:

dayName = "Invalid day";

break;

System.out.println("The day is: " + dayName);

26
5. Ternary Operator

The ternary operator is a shorthand for the if-else statement. It is used to evaluate a condition and
return one of two values based on whether the condition is true or false.

int number = 10;

String result = (number % 2 == 0) ? "Even" : "Odd";

System.out.println("The number is " + result);

Loops Statements

In Java, loops are used to execute a block of code repeatedly based on a condition or until a specific
condition is met. Java provides several types of loops:

1. for Loop

The for loop is used when the number of iterations is known beforehand. It consists of three parts:
initialization, condition, and increment/decrement.

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

System.out.println("Iteration: " + i);

• Initialization: int i = 0 (executes once at the start)

• Condition: i < 5 (evaluated before each iteration; if false, loop exits)

• Increment/Decrement: i++ (executes after each iteration)

2. while Loop

The while loop is used when the number of iterations is not known and depends on a condition that
is evaluated before each iteration.

int i = 0;

while (i < 5) {

System.out.println("Iteration: " + i);

i++;

• Condition: i < 5 (evaluated before each iteration; if false, loop exits)

3. do-while Loop

The do-while loop is similar to the while loop but guarantees that the block of code is executed at
least once, as the condition is evaluated after the loop's body.

27
int i = 0;

do {

System.out.println("Iteration: " + i);

i++;

} while (i < 5);

• Condition: i < 5 (evaluated after each iteration; if false, loop exits)

4. Enhanced for Loop (for-each Loop)

The enhanced for loop (or for-each loop) is used to iterate over arrays or collections. It simplifies
iterating through elements without using an index.

int[] numbers = {1, 2, 3, 4, 5};

for (int num : numbers) {

System.out.println("Number: " + num);

• num: Each element in the numbers array (one at a time)

Loop Control Statements

1. break: Exits the loop immediately, regardless of the condition.

for (int i = 0; i < 10; i++) {

if (i == 5) {

break; // Exits the loop when i is 5

System.out.println("Iteration: " + i);

2. continue: Skips the current iteration and proceeds to the next iteration of the loop.

for (int i = 0; i < 10; i++) {

if (i % 2 == 0) {

continue; // Skips even numbers

System.out.println("Odd number: " + i);

3. return: Exits the method and, optionally, returns a value. This can also terminate loops if
used inside a method.

public void loopExample() {

28
for (int i = 0; i < 10; i++) {

if (i == 5) {

return; // Exits the method (and thus the loop) when i is 5

System.out.println("Iteration: " + i);

Summary of Loop Types

• for Loop: Use when the number of iterations is known.

• while Loop: Use when the number of iterations is not known and depends on a condition.

• do-while Loop: Similar to while, but executes at least once.

• Enhanced for Loop: Simplifies iteration over arrays and collections.

• Control Statements: break exits the loop, continue skips the current iteration, and return
exits the method.

Loops are essential for repetitive tasks and processing collections of data in Java, providing flexibility
and control over program execution.

Arrays In Java

In Java, arrays are used to store multiple values of the same type in a single variable. Arrays are
fundamental for handling collections of data and are crucial for many programming tasks.

1. Declaring and Creating Arrays

Arrays in Java are objects that hold multiple values of the same type. You need to declare an array,
allocate memory for it, and then initialize it.

Declaration

You declare an array by specifying the type of its elements followed by square brackets.

int[] numbers; // Declaration of an array of integers

String[] names; // Declaration of an array of strings

Instantiation

You create an array by using the new keyword and specifying the size.

numbers = new int[5]; // Creates an array of 5 integers

names = new String[3]; // Creates an array of 3 strings

29
Initialization

You can initialize an array with specific values at the time of declaration or later.

int[] numbers = {1, 2, 3, 4, 5}; // Array with initial values

String[] names = {"Alice", "Bob", "Charlie"}; // Array with initial values

2. Accessing Array Elements

Array elements are accessed using their index, which starts from 0.

int firstNumber = numbers[0]; // Accesses the first element

names[1] = "David"; // Modifies the second element

3. Array Length

The length of an array is obtained using the length property, which provides the number of elements
in the array.

int length = numbers.length; // Returns 5

5. Multi-Dimensional Arrays

Java supports multi-dimensional arrays, such as 2D arrays (arrays of arrays). They are useful for
representing matrices or grids.

Declaration and Initialization

int[][] matrix = new int[3][3]; // Creates a 3x3 matrix

// Initialize 2D array with values

int[][] matrix = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

Accessing Elements

int element = matrix[1][2]; // Accesses the element at row 1, column 2 (value 6)

matrix[2][1] = 10; // Modifies the element at row 2, column 1

6. Array Operations

Copying Arrays

You can copy arrays using methods like System.arraycopy or Arrays.copyOf.

int[] source = {1, 2, 3, 4};

int[] destination = new int[4];

System.arraycopy(source, 0, destination, 0, source.length);

30
import java.util.Arrays;

int[] original = {1, 2, 3, 4};

int[] copy = Arrays.copyOf(original, original.length);

Sorting Arrays

You can sort arrays using Arrays.sort.

import java.util.Arrays;

int[] numbers = {4, 2, 7, 1, 9};

Arrays.sort(numbers);

Searching Arrays

You can search for elements using Arrays.binarySearch, but the array must be sorted.

import java.util.Arrays;

int[] numbers = {1, 2, 4, 7, 9};

int index = Arrays.binarySearch(numbers, 4); // Returns 2

Example Code

Here’s a complete example demonstrating various array operations:

public class ArrayExample {

public static void main(String[] args) {

// 1D Array

int[] numbers = {1, 2, 3, 4, 5};

System.out.println("1D Array:");

for (int num : numbers) {

System.out.println(num);

// 2D Array

int[][] matrix = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

System.out.println("2D Array:");

31
for (int i = 0; i < matrix.length; i++) {

for (int j = 0; j < matrix[i].length; j++) {

System.out.print(matrix[i][j] + " ");

System.out.println();

// Array Copy

int[] copy = Arrays.copyOf(numbers, numbers.length);

System.out.println("Copied Array:");

for (int num : copy) {

System.out.println(num);

// Sorting

Arrays.sort(numbers);

System.out.println("Sorted Array:");

for (int num : numbers) {

System.out.println(num);

// Searching

int index = Arrays.binarySearch(numbers, 3);

System.out.println("Index of 3: " + index);

Summary

• Arrays: Containers for multiple values of the same type.

• Declaration: Define an array type and size.

• Access: Use indices to access or modify elements.

• Iteration: Use loops to traverse arrays.

32
• Multi-Dimensional: Use arrays of arrays for more complex data structures.

• Operations: Copy, sort, and search arrays using built-in methods.

Arrays are a fundamental concept in Java programming and are essential for handling collections of
data efficiently.

33

You might also like