Java Programming language
Java 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?
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:
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.
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.
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.
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 Usage: Useful for saving memory in large arrays where the memory savings actually
matter.
• short:
o Size: 16 bits
o Usage: Also used to save memory, short is a smaller data type than int.
• int:
o Size: 32 bits
4
• long:
o Size: 64 bits
b. Floating-Point Types:
• float:
o Size: 32 bits
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 Usage: Default data type for decimal values, generally the best choice for real
numbers.
c. Character Type:
• char:
o Range: 0 to 65,535
o Usage: Used to store a single character (e.g., 'a', 'A', '1', etc.).
d. Boolean Type:
• boolean:
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:
Summary Table:
These data types are the building blocks of any Java program, and understanding them is crucial for
effective programming in Java.
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 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.
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.
1. Signature:
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.
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.
System.out.println("Hello, World!");
Explanation:
1. Class Declaration:
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 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 static means you don’t need to create an instance of the class to call this method.
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.
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.
o Besides the console, Scanner can read from files, strings, and other input streams.
Here’s a simple example demonstrating how to use Scanner to read user input from the console:
import java.util.Scanner;
9
// Display the collected information
scanner.close();
Explanation:
1. Import Statement:
o Creates a Scanner object to read input from the standard input stream (the console).
3. Reading Input:
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.
• 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.
10
• hasNextInt(): Checks if the next token is an integer.
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
• Example:
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:
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:
Output:
Age: 25 years
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:
• Usage:
o The comment starts with // and continues to the end of the line.
• Example:
12
}
2. Multi-Line Comments
• Syntax:
/*
*/
• Usage:
o The comment starts with /* and ends with */. You can use * to align comment text
for readability, but it's optional.
Example:
/*
*/
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:
Syntax:
13
// Combined declaration and initialization
Example:
2. Variable Types
Example:
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.
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.
Example:
14
System.out.println("Double value: " + doubleValue);
In this example:
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:
Example:
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
2. Relational Operators
These operators are used to compare two values and return a boolean result (true or false).
• Greater than or equal to (>=): Checks if one value is greater than or equal to another.
• Less than or equal to (<=): Checks if one value is less than or equal to another.
3. Logical Operators
These operators are used to perform logical operations and are commonly used in conditional
statements.
16
• Logical OR (||): Returns true if at least one of the operands is true.
4. Assignment Operators
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
int a = +5; // a is 5
int a = -5; // a is -5
17
• Increment (++): Increases the value of a variable by 1.
int a = 5;
a++; // a is now 6
int a = 5;
a--; // a is now 4
6. Bitwise Operators
18
}
Explanation:
Explanation:
• Unsigned Right Shift (>>>): Shifts bits to the right, filling with zeros.
• Syntax:
• Example:
int a = 5;
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.
You can also create a string using the new keyword, which creates a new String object.
The String class provides many methods for manipulating and querying strings:
1. Length of a String
2. Concatenation
// or
3. Substring
4. Replace
20
5. To Upper Case / Lower Case
6. Trim
8. Check Equality
9. Split
10. Char At
21
boolean startsWith = str.startsWith("Hello"); // 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:
System.out.println(str1 == str2); // true, because both refer to the same object in the string pool
For mutable sequences of characters, Java provides StringBuilder and StringBuffer. Unlike String,
these classes allow modification of the sequence without creating new objects.
sb.append(" World");
sb.append(" 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.
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.
1. Absolute Value
2. Power
3. Square Root
5. Trigonometric Functions
6. Rounding
23
• Floor: Returns the largest integer less than or equal to a given number.
• Ceiling: Returns the smallest integer greater than or equal to a given number.
8. Random Numbers
double random = Math.random(); // Returns a random number between 0.0 and 1.0
Example Usage
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
if (number > 0) {
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.
if (number > 0) {
} else {
The if-else if-else statement is used when you need to evaluate multiple conditions.
int number = 0;
if (number > 0) {
} else {
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:
break;
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.
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.
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) {
i++;
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 {
i++;
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.
if (i == 5) {
2. continue: Skips the current iteration and proceeds to the next iteration of the loop.
if (i % 2 == 0) {
3. return: Exits the method and, optionally, returns a value. This can also terminate loops if
used inside a method.
28
for (int i = 0; i < 10; i++) {
if (i == 5) {
• while Loop: Use when the number of iterations is not known and depends on a condition.
• 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.
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.
Instantiation
You create an array by using the new keyword and specifying the size.
29
Initialization
You can initialize an array with specific values at the time of declaration or later.
Array elements are accessed using their index, which starts from 0.
3. Array Length
The length of an array is obtained using the length property, which provides the number of elements
in the array.
5. Multi-Dimensional Arrays
Java supports multi-dimensional arrays, such as 2D arrays (arrays of arrays). They are useful for
representing matrices or grids.
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Accessing Elements
6. Array Operations
Copying Arrays
30
import java.util.Arrays;
Sorting Arrays
import java.util.Arrays;
Arrays.sort(numbers);
Searching Arrays
You can search for elements using Arrays.binarySearch, but the array must be sorted.
import java.util.Arrays;
Example Code
// 1D Array
System.out.println("1D Array:");
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++) {
System.out.println();
// Array Copy
System.out.println("Copied Array:");
System.out.println(num);
// Sorting
Arrays.sort(numbers);
System.out.println("Sorted Array:");
System.out.println(num);
// Searching
Summary
32
• Multi-Dimensional: Use arrays of arrays for more complex data structures.
Arrays are a fundamental concept in Java programming and are essential for handling collections of
data efficiently.
33