KEMBAR78
Java-Detailed Notes-1 | PDF | Integer (Computer Science) | Programming
0% found this document useful (0 votes)
45 views30 pages

Java-Detailed Notes-1

Uploaded by

harishramaraops
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views30 pages

Java-Detailed Notes-1

Uploaded by

harishramaraops
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Introduction To Java

Java is an object-oriented, class-based programming language. The language is


designed to have as few dependencies implementations as possible. The intention
of using this language is to give relief to the developers from writing codes for
every platform. The term WORA, write once and run everywhere is often
associated with this language. It means whenever we compile a Java code, we get
the byte code (.class file), and that can be executed (without compiling it again)
on different platforms provided they support Java. In the year 1995, Java
language was developed. It is mainly used to develop web, desktop, and mobile
devices. The Java language is known for its robustness, security, and simplicity
features. That is designed to have as few implementation dependencies as
possible.

The Java Features:

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

Interpreted and High Performance

As described earlier, Java enables the creation of cross-platform


programs by compiling into an intermediate representation called Java
bytecode. This code can be interpreted on any system that provides a Java
Virtual Machine. Most previous attempts at cross platform solutions have done
so at the expense of performance. Other interpreted systems, such as BASIC,
Tcl, and PERL, suffer from almost insurmountable performance deficits. Java,
however, was designed to perform well on very low-power CPUs.

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

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte


Boolean Data Type
The Boolean data type is used to store only two possible values: true and false.
This data type is used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be
defined precisely.

Example:

Boolean one = false

Byte Data Type


The byte data type is an example of primitive data type. It isan 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its
minimum value is -128 and maximum value is 127. Its default value is 0.

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:

byte a = 10, byte b = -20

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-range
lies between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and
maximum value is 32,767. Its default value is 0.

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:

short s = 10000, short r = -5000

Int Data Type


The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its
minimum value is - 2,147,483,648and maximum value is 2,147,483,647. Its
default value is 0.The int data type is generally used as a default data type for
integral values unless if there is no problem about memory.

Example:

int a = 100000, int b = -200000

Long Data Type


The long data type is a 64-bit two's complement integer. Its value-range lies
between -9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63
-1)(inclusive). Its minimum value is - 9,223,372,036,854,775,808and maximum
value is 9,223,372,036,854,775,807. Its default value is 0. The long data type is
used when you need a range of values more than those provided by int.

Example:

long a = 100000L, long b = -200000L

Float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating point.Its value
range is unlimited. It is recommended to use a float (instead of double) if you
need to save memory in large arrays of floating point numbers. The float data
type should never be used for precise values, such as currency. Its default value
is 0.0F.

Example:

float f1 = 234.5f

Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating point. Its
value range is unlimited. The double data type is generally used for decimal
values just like float. The double data type also should never be used for precise
values, such as currency. Its default value is 0.0d.

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:

char letterA = 'A'

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:

• Variables must be declared before they can be used.


• The data type of a variable determines the type of data it can hold.
• Variable names should be meaningful and descriptive.

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:

• Initialization assigns a value to a declared variable.


• Variables can be initialized at the time of declaration or later in the
program.
• Initializing a variable at the time of declaration is optional but
recommended.

3. Declaration and Initialization of Variables:


• Definition: Variables can be declared and initialized in a single statement.
• Syntax:

data_type variable_name = value;

Example:

int age = 25;

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.

Variable Name Rules:


• Variable names must begin with a letter (a-z, A-Z), underscore (_), or
dollar sign ($).
• After the first character, variable names can contain letters, digits (0-9),
underscores, or dollar signs.
• Variable names are case-sensitive, meaning age and Age are considered
different variables.
• Avoid using Java keywords or reserved words as variable names.
• Use meaningful and descriptive names that reflect the purpose of the
variable.

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:

public void exampleMethod() {

int localVar = 10; // Local variable

System.out.println(localVar);

Instance Variables (Non-Static Fields):


• Instance variables are declared within a class but outside any method,
constructor, or block of code.
• They are created when an object of the class is instantiated and exist as
long as the object exists.
• Each object of the class has its own copy of instance variables.
• Instance variables are initialized with default values if not explicitly
initialized.

Example:

public class MyClass {

int instanceVar = 20; // Instance variable

}
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:

public class MyClass {

static int classVar = 30; // Class variable

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

Operator Category Precedence


Type

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative * / %

additive + -

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive ^

OR

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ? :

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=


1. Arithmetic Operators:
Arithmetic operators are used to perform basic mathematical operations like
addition, subtraction, multiplication, division, and modulus.
• Addition: +
• Subtraction: -
• Multiplication: *
• Division: /
• Modulus (Remainder): %

public class Test{

public static void main(String args[]){

int a =10,b =20,c =25,d =25;

System.out.println("a + b = "+(a + b));

System.out.println("a - b = "+(a - b));

System.out.println("a * b = "+(a * b));

System.out.println("b / a = "+(b / a));

}
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;)

public class OperatorExample{

public static void main(String args[]){

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: <=

public class Test{

public static void main(String args[]){

int a =10,b =20;

System.out.println("a == b = "+(a == b));

System.out.println("a != b = "+(a != b));

System.out.println("a > b = "+(a > b));

System.out.println("a < b = "+(a < b));

System.out.println("b >= a = "+(b >= a));

System.out.println("b <= a = "+(b <= a));

}}

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: !

public class Test{

public static void main(String args[]){

boolean a =true;

boolean b =false;

System.out.println("a && b = "+(a&&b));

System.out.println("a || b = "+(a||b));

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: >>>

public class BitwiseExample {

public static void main(String[] args) {

int a = 5;

int b = 3;

int resultAND = a & b;

System.out.println("Result of bitwise AND: " + resultAND);

int resultOR = a | b;

System.out.println("Result of bitwise OR: " + resultOR);

int resultXOR = a ^ b;

System.out.println("Result of bitwise XOR: " + resultXOR)

int resultNOT = ~a;

System.out.println("Result of bitwise NOT: " + resultNOT);

int leftShift = a << 2;

System.out.println("Left Shift Result: " + leftShift);

int rightShift = a >> 2;

System.out.println("Right Shift Result: " + rightShift);


}
}

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.:

o incrementing/decrementing a value by one


o negating an expression
o inverting the value of a boolean

public class OperatorExample{

public static void main(String args[]){

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

7. Conditional Operator (Ternary Operator):


The conditional operator ? : is used for decision-making based on a condition.

public class OperatorExample{

public static void main(String args[]){

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:

int x = 10; if (x > 5) {

System.out.println("x is greater than 5");

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) {

System.out.println("x is greater than 5");


}

else {

System.out.println("x is less than or equal to 5");

c. Nested If-else Statement:


• Description: The nested if-else statement consists of multiple if-else
statements inside each other. It is used to check multiple conditions based
on the outcome of previous conditions.
• Syntax:
if (condition1)
{
if (condition2) {
// Code to be executed if both conditions are true
}
else { // Code to be executed if condition1 is true and condition2 is false
}
} else { // Code to be executed if condition1 is false
}
• Example:
int x = 10, y = 20;
if (x > 5) {
if (y > 10) {
System.out.println("Both x and y are greater than their respective
limits");
} else {
System.out.println("x is greater than 5 but y is not greater than
10");
}
} else { System.out.println("x is not greater than 5");
}

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:

public int add(int a, int b) {


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

Array

• Normally, array is a collection of similar type of elements that have


contiguous memory location.
• Java array is an object the contains elements of similar data type. It is a
data structure where we store similar elements. We can store only fixed
set of elements in a java array.
• Array in java is index based, first element of the array is stored at 0
index.
Advantage of Java Array
• Code Optimization: It makes the code optimized, we can retrieve or sort
the data easily.
• Random access: We can get any data located at any index position.
Disadvantage of Java Array
• Size Limit: We can store only fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in java.
Array Creation in Java:
Arrays in Java are objects that store multiple variables of the same type. They
provide a convenient way to group multiple variables under a single name.
Here's how you create arrays in Java:
1. Syntax:
For one-dimensional arrays:
data_type[] array_name = new data_type[size];
For multidimensional arrays:
data_type[][] array_name = new data_type[size1][size2]...[sizeN];
2. Example:
One-dimensional array:
int[] arr = new int[5]; // Creates an array of integers with size 5
Multidimensional array:
int[][] arr = new int[3][3]; // Creates a 2D array of integers with size
3x3
Array Syntax in Java:
1. One-dimensional array:
• Declaration: data_type[] array_name
• Initialization: new data_type[size]
• Accessing elements: array_name[index]
2. Multidimensional array:
• Declaration: data_type[][] array_name
• Initialization: new data_type[size1][size2]...[sizeN]
• Accessing elements: array_name[row_index][column_index]
Types of Arrays in Java:
1. One-dimensional arrays:
• An array with a single row of elements.
• Used to represent lists or vectors.
Example:
int[] arr = new int[5]; // One-dimensional array with 5 elements
2. Multidimensional arrays:
• Arrays of arrays, where each element is itself an array.
• Used to represent tables, matrices, or higher-dimensional data
structures.
• Example:

int[][] matrix = new int[3][3]; // 2D array (3x3)


int[][][] cube = new int[3][3][3]; // 3D array (3x3x3)
Introduction to oops

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:

[access_modifier] class ClassName


{ // Attributes // Constructors // Methods
}
• Access Modifier: It specifies the visibility of the class. It can be public,
protected, private, or default (no modifier).
• class: It's a keyword used to declare a class.
• ClassName: It's the name of the class. By convention, it should start with
an uppercase letter.
• Attributes: These are variables that represent the state of objects of the
class.
• Constructors: These are special methods used for initializing objects of
the class.
• Methods: These are functions that define the behavior of objects of the
class.

Example

public class Person {


// Data members (attributes)
static String name = "John";
static int age = 25;

// Method
void eat() {
System.out.println(name + " is eating."); // Displaying a simple
message
}

// Main method (for testing purposes)


public static void main(String[] args) {
// Creating an instance of the Person class
Person person = new Person();

// Calling the eat() method


person.eat(); // Output: John is eating.
}
}

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 {

// Data members (attributes)


static String name = "John";
static int age = 25;

// Method
void eat() {
System.out.println(name + " is eating."); // Displaying a simple message
}

// Main method (for testing purposes)


public static void main(String[] args) {
// Creating an instance of the Person class
Person person = new Person();

// Calling the eat() method


person.eat(); // Output: John is eating.
}
}

You might also like