Java-Detailed Notes-1
Java-Detailed Notes-1
1. Simple
2. Secure
3. Portable
4. Object-oriented
5. Robust
6. Multithreaded
7. Architecture-neutral
8. Interpreted
9. High performance
10.Distributed
11.Dynamic
Simple
Java was designed to be easy for the professional programmer to learn
and use effectively. Assuming that you have some programming experience,
you will not find Java hard to master. If you already understand the basic
concepts of object-oriented programming, learning Java will be even easier.
Best of all, if you are an experienced C++ programmer, moving to Java will
require very little effort. Because Java inherits the C/C++ syntax and many of
the object- oriented features of C++, most programmers have little trouble
learning Java..
Robust
The multi platformed environment of the Web places extraordinary
demands on a program, because the program must execute reliably in a variety
of systems. Thus, the ability to create robust programs was given a high priority
in the design of Java.
Multithreaded
Java was designed to meet the real-world requirement of creating
interactive, networked programs. To accomplish this, Java supports
multithreaded programming, which allows you to write programs that do many
things simultaneously. The Java run-time system comes with an elegant yet
sophisticated solution for multiprocess .synchronization that enables you to
construct smoothly running interactive systems
Distributed
Java is designed for the distributed environment of the Internet, because
it handles TCP/IP protocols. In fact, accessing a resource using a URL is not
much different from accessing a file. The original version of Java (Oak)
included features for intra address-space messaging. This allowed objects on
two different computers to execute procedures remotely. Java revived these
interfaces in a package called Remote MethodInvocation (RMI). This feature
brings an unparalleled level of abstraction to client/server programming.
Dynamic
Java programs carry with them substantial amounts of run-time type
information that is used to verify and resolve accesses to objects at run time.
This makes it possible to dynamically link code in a safe and expedient manner.
This is crucial to the robustness of the applet environment, in which small
fragments of bytecode may be dynamically updated on a running system.
DATA TYPES
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
The Boolean data type specifies one bit of information, but its "size" can't be
defined precisely.
Example:
The byte data type is used to save memory in large arrays where the memory
savings is most required. It saves space because a byte is 4 times smaller than an
integer. It can also be used in place of "int" data type.
Example:
The short data type can also be used to save memory just like byte data type. A
short data type is 2 times smaller than an integer.
Example:
Example:
Example:
Example:
float f1 = 234.5f
Example:
1. double d1 = 12.3
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies
between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used
to store characters.
Example:
Java Variables
A variable is a container which holds the value while the Java program is
executed. A variable is assigned with a data type.Variable is a name of memory
location. There are three types of variables in java: local, instance and static.
1. Declaration of Variables:
• Definition: Variable declaration is the process of specifying the data type
and name of a variable without assigning it a value.
Syntax:
data_type variable_name;
• Example:
int age;
Key Points:
2. Initialization of Variables:
• Definition: Variable initialization is the process of assigning an initial
value to a variable at the time of declaration or later in the program.
• Syntax:
variable_name = value;
• Example:
age = 25;
Key Points:
Example:
Additional Notes:
• Java is a statically typed language, meaning variables must have a
declared type.
• Variable names in Java are case-sensitive.
• Variables can be of primitive types or reference types (objects).
• Primitive types include int, float, double, boolean, etc.
• Reference types include classes, arrays, interfaces, etc.
• Variable scope determines where a variable can be accessed in a program.
Local Variables:
• Local variables are declared within a method, constructor, or block of
code.
• They are accessible only within the scope in which they are declared.
• Local variables must be initialized before they are used.
• They are destroyed once the method, constructor, or block of code in which
they are declared completes execution.
Example:
System.out.println(localVar);
Example:
}
Class Variables (Static Fields):
• Class variables, also known as static fields, are declared with the static
keyword within a class but outside any method, constructor, or block of
code.
• They are shared among all instances of the class.
• Class variables are initialized only once, at the start of the program
execution, and retain their values throughout the program's lifespan.
• They are typically used to represent properties or characteristics that are
common to all instances of the class.
Example:
Operators in Java
• Operator in Java is a symbol that is used to perform operations. For
example: +, -, *, / etc.
• There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Java Operator Precedence
Arithmetic multiplicative * / %
additive + -
equality == !=
bitwise exclusive ^
OR
bitwise inclusive OR |
logical OR ||
Ternary ternary ? :
}
Output
a + b =30
a - b =-10
a * b =200
b / a =2
2. Assignment Operators:
Assignment operators are used to assign values to variables.
• Assignment: =
• Compound Assignment: +=, -=, *=, /=, %= (e.g., x += 5; is equivalent
to x = x + 5;)
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}
Output
14
16
3. Comparison Operators:
Comparison operators are used to compare values and return a boolean result.
Equal to: ==
Not equal to: !=
Greater than: >
Less than: <
Greater than or equal to: >=
Less than or equal to: <=
}}
Output
a == b =false
a != b =true
a > b =false
a < b =true
b >= a =true
b <= a =false
4. Logical Operators:
Logical operators are used to perform logical operations on boolean values.
• Logical AND: &&
• Logical OR: ||
• Logical NOT: !
boolean a =true;
boolean b =false;
System.out.println("a || b = "+(a||b));
Output
a && b =false
a || b =true
!(a && b)=true
5. Bitwise Operators:
Bitwise operators perform operations on individual bits of integer operands.
• Bitwise AND: &
• Bitwise OR: |
• Bitwise XOR: ^
• Bitwise NOT: ~
• Left Shift: <<
• Right Shift: >>
• Unsigned Right Shift: >>>
•
int a = 5;
int b = 3;
int resultOR = a | b;
int resultXOR = a ^ b;
Output
Result of bitwise AND: 1
Result of bitwise OR: 7
Result of bitwise XOR: 6
Result of bitwise NOT: -6
Left Shift Result: 20
Right Shift Result: 1
6.Unary Operator
The Java unary operators require only one operand. Unary operators are used to
perform various operations i.e.:
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}
Output
10
12
12
10
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output
2
Conditional Statements:
a. If Statement:
• Description: The if statement evaluates a condition and executes a block
of code if the condition is true. If the condition is false, the code block
associated with the if statement is skipped.
• Syntax:
if (condition) { // Code to be executed if the condition is true }
• Example:
b. If-else Statement:
• Description: The if-else statement evaluates a condition and executes one
block of code if the condition is true, and another block of code if the
condition is false.
• Syntax:
if (condition) {
// Code to be executed if the condition is true
}
else {
// Code to be executed if the condition is false
}
Example:
int x = 10;
if (x > 5) {
else {
Looping Statements:
a. For Loop:
• Description: The for loop is used to execute a block of code repeatedly
for a specified number of times. It consists of three parts: initialization,
condition, and update.
• Syntax:
for (initialization; condition; update)
{
// Code to be executed repeatedly until the condition becomes false
}
• Example:
for (int i = 1; i <= 5; i++)
{
System.out.println("Iteration " + i);
}
b. While Loop:
• Description: The while loop is used to execute a block of code repeatedly
as long as a specified condition is true.
• Syntax:
while (condition) {
// Code to be executed repeatedly until the condition becomes false
}
• Example:
int i = 1;
while (i <= 5)
{
System.out.println("Iteration " + i);
i++;
}
c. Do-while Loop:
• Description: The do-while loop is similar to the while loop, but it always
executes the code block at least once before checking the condition.
• Syntax:
do {
// Code to be executed at least once and then repeatedly until the condition
becomes false
} while (condition);
Example:
int i = 1;
do { System.out.println("Iteration " + i);
i++; }
while (i <= 5);
3. Jumping Statements:
a. Break Statement:
• Description: The break statement is used to exit from the loop or switch
statement. It terminates the loop prematurely.
• Example:
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
break; // Exit the loop when i becomes 3
}
System.out.println("Iteration " + i);
}
b. Continue Statement:
• Description: The continue statement is used to skip the current iteration
of the loop and continue with the next iteration.
• Example:
for (int i = 1; i <= 5; i++) {
if (i == 3)
{
continue; // Skip the iteration when i becomes 3
} System.out.println("Iteration " + i); }
c. Return Statement:
• Description: The return statement is used to exit from a method and
optionally return a value to the caller.
• Example:
Array
OOP:
OOP allows us to decompose a problem into a number of entities called objects
and then builds
data and methods around these entities.
DEF: OOP is an approach that provides a way of modularizing programs by
creating portioned memory area for both data and methods that can used as
templates for creating copies of such modules on demand.
That is ,an object a considered to be a partitioned area of computer memory
that stores data and set of operations that can access that data. Since the
memory partitions are independent, the objects can be used in a variety of
different programs without modifications.
Advantage of OOP in Java:
• Modularity: OOP promotes code organization into modular components
(classes and objects), making it easier to understand, maintain, and reuse
code.
• Reusability: OOP facilitates code reuse through inheritance and
composition, reducing development time and effort.
• Extensibility: OOP supports the addition of new features and
functionalities to existing code without modifying the original
implementation.
• Flexibility: OOP allows for the creation of flexible and adaptable
software systems, enabling developers to respond to changing
requirements more effectively.
• Maintainability: OOP promotes code maintainability by organizing code
into smaller, coherent units (classes and objects), making it easier to
debug and enhance the software over time.
3. Disadvantages of OOP in Java:
• Overhead: OOP can introduce overhead in terms of memory usage and
performance, especially when dealing with large numbers of objects and
complex inheritance hierarchies.
• Complexity: OOP introduces additional complexity, especially for
beginners, due to its reliance on concepts such as inheritance,
polymorphism, and abstraction.
• Tight Coupling: Improper use of inheritance and tight coupling between
classes can lead to code that is difficult to maintain and modify.
• Performance Overhead: Encapsulation and method calls for accessing
and modifying data can introduce performance overhead, especially in
performance-critical applications.
• Learning Curve: OOP requires a paradigm shift for developers
accustomed to procedural programming, leading to a potentially steep
learning curve.
Class
Definition of a Class in Java:
A class in Java is a user-defined data type that encapsulates data (attributes)
and methods (behaviors) into a single unit. It serves as a blueprint for creating
objects, providing a template for their properties and behaviors.
Rules for Defining Classes in Java:
1. Class Declaration Syntax:
• A class declaration starts with the class keyword followed by the
class name.
• The class body is enclosed within curly braces {}.
• The class name should be meaningful and follow the camelCase
naming convention.
• The class name should start with an uppercase letter.
public class ClassName {
// Class members (attributes, constructors, methods)
}
Syntax of a Class in Java:
The syntax for declaring a class in Java is as follows:
Example
// Method
void eat() {
System.out.println(name + " is eating."); // Displaying a simple
message
}
Objects in Java:
In Java, an object is an instance of a class that encapsulates state and behavior.
a. Rules for Objects in Java:
• Objects are instances of classes, meaning they are created based on a
blueprint defined by a class.
• Each object has its own state (represented by instance variables) and
behavior (represented by methods).
• Objects interact with each other by invoking methods or accessing fields
of other objects.
b. Creation of Objects in Java:
Objects are created using the new keyword followed by a constructor of the
class.
Syntax:
ClassName objectName = new ClassName();
c. Advantage of Objects:
• Modularity: Objects allow you to break down complex systems into
smaller, manageable units, promoting modularity and reusability.
• Encapsulation: Objects encapsulate state and behavior, hiding internal
implementation details and providing a clean interface for interaction.
• Code Organization: Objects help in organizing code into logical units,
making it easier to understand, maintain, and extend.
d. Disadvantages of Objects:
• Overhead: Creating multiple objects can lead to memory overhead,
especially if each object contains a significant amount of data.
• Complexity: Dealing with a large number of objects and their
interactions can introduce complexity, making the system harder to
understand and debug.
• Performance: Object-oriented programs may suffer from performance
issues due to the overhead of method invocation and dynamic dispatch.
e. Syntax for Objects:
ClassName objectName = new ClassName();
Example:
public class Person {
// Method
void eat() {
System.out.println(name + " is eating."); // Displaying a simple message
}