S12BLH31 Unit I Java
S12BLH31 Unit I Java
Unit – I
Java is a powerful and versatile programming language known for its platform independence and
wide range of features.
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) 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:
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
o Loads code
o Verifies code
o Executes code
o Memory area
o Register set
o Garbage-collected heap
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.
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
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.
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.
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.
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.
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.
class prg{
public static void main(String args[]){
System.out.println("Sathyabama");
System.out.println("CSE ");
}
}
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:
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:
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 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:
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.
public static void main(String[] args) { // Keywords: public, class, static, void, main, String
// Single-line comment
Key Points:
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.
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.
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
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");}
}
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.
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.
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.
//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
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.
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:
Example:
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).
3. Logical Operators:
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 (=): 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 num2 = 5;
num1 += num2;
Increment (++) and decrement (--) operators are used to increase or decrease the value of a
variable by 1, respectively.
Example:
int count = 5;
6. Bitwise Operators:
Example:
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:
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];
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.
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)
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
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:
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];
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)
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
}
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.
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.
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:
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.
c. else-if ladder:
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:
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:
b. continue Statement:
The continue statement skips the current iteration of a loop and continues with the next
iteration.
The return statement exits from the current method, optionally returning a value.
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.
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:
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:
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 Methods: The String class provides various methods for manipulating strings, such as:
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
2. String Concatenation
3. String Length
4. Accessing Characters
6. String Comparison
8. String Modification
9. Converting Case
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.
Examples
sb.append(" World");
sb.reverse();
sb.setLength(10);
These examples demonstrate how you can use the StringBuffer class to perform various
operations on strings in Java.