Unit-1 Java Notes
Unit-1 Java Notes
1)Class
The class is a group of similar entities. It is only a logical component and not the physical entity.
For example, if you had a class called “Expensive Cars” it could have objects like Mercedes,
BMW, Toyota, etc. Its properties (data) can be price or speed of these cars. While the methods
may be performed with these cars are driving, reverse, braking etc.
2) Object
An object can be defined as an instance of a class, and there can be multiple instances of a class
in a program. An Object contains both the data and the function, which operates on the data. For
example - chair, bike, marker, pen, table, car, etc.
3) Inheritance
Inheritance is an OOPS concept in which one object acquires the properties and behaviors of the
parent object. It‟s creating a parent-child relationship between two classes. It offers robust and
natural mechanism for organizing and structure of any software.
4) Polymorphism
Polymorphism refers to the ability of a variable, object or function to take on multiple forms. For
example, in English, the verb “run” has a different meaning if you use it with “a laptop,” “a foot
race, and ”business.&rdquo Here, we understand the meaning of “run” based on the other words
used along with [Link] same also applied to Polymorphism.
5) Abstraction
Encapsulation is an OOP technique of wrapping the data and code. In this OOPS concept, the
variables of a class are always hidden from other classes. It can only be accessed using the
methods of their current class. For example - in school, a student cannot exist without a class.
7) Association
Association is a relationship between two objects. It defines the diversity between objects. In this
OOP concept, all object have their separate lifecycle, and there is no owner. For example, many
students can associate with one teacher while one student can also associate with multiple
teachers.
8) Aggregation
In this technique, all objects have their separate lifecycle. However, there is ownership such that
child object can‟t belong to another parent object. For example consider class/objects department
and teacher. Here, a single teacher can‟t belong to multiple departments, but even if we delete
the department, the teacher object will never be destroyed.
9) Composition
1. OOP offers easy to understand and a clear modular structure for programs.
2. Objects created for Object-Oriented Programs can be reused in other programs. Thus it
saves significant development cost.
3. Large programs are difficult to write, but if the development and designing team follow
OOPS concept then they can better design with minimum flaws.
4. It also enhances program modularity because every object exists independently.
1.3 Data types in Java
There are majorly two types of languages. First one is Statically typed language where each
variable and expression type is already known at compile time. Once a variable is declared to be
of a certain data type, it cannot hold values of other data types. Example: C,C++, Java.
Other, Dynamically typed languages: These languages (Ruby, Python) can receive different
data types over the time.
Java is statically typed and also a strongly typed language because in Java, each type of data
(such as integer, character, hexadecimal, packed decimal, and so forth) is predefined as part of
the programming language and all constants or variables defined for a given program must be
described with one of the data types.
Java has two categories of data:
Primitive data (e.g., number, character)
Object data (programmer created types)
boolean: boolean data type represents only one bit of information either true or false . Values
of type boolean are not converted implicitly or explicitly (with casts) to any other type. But the
programmer can easily write conversion code.
// A Java program to demonstrate boolean data type
class GeeksforGeeks
{
public static void main(String args[])
{
boolean b = true;
if (b == true)
[Link]("Hi Geek");
}
}
byte: The byte data type is an 8-bit signed two‟s complement integer. The byte data type is
useful for saving memory in large arrays.
Size: 8-bit
Value: -128 to 127
// Java program to demonstrate byte data type in Java
class GeeksforGeeks
{
public static void main(String args[])
{
byte a = 126;
a++;
[Link](a);
short s = 56;
Normally, an array is a collection of similar type of elements that have a contiguous memory
location.
Java array is an object which contains elements of a similar data type. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java array.
Array in java is index-based, the first element of the array is stored at the 0 index.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the 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 which grows
automatically.
There are two types of array.
o Single Dimensional Array
o Multidimensional Array
1. EXAMPLE ARRAY INITIALIZATION (single dimension)
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}}
class Testarray2{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<[Link];i++)
if(min>arr[i])
min=arr[i];
[Link](min);
}
public static void main(String args[]){
int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}}
Multidimensional Array in Java
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
[Link](arr[i][j]+" ");
}
[Link]();
}
}}
1.5 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.
additive +-
equality == !=
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
A program executes from top to bottom except when we use control statements, we can control
the order of execution of the program, based on logic and values.
In Java, control statements can be divided into the following three categories:
Selection Statements
Iteration Statements
Jump Statements
Example switch
import [Link];
Repeating the same code fragment several times until a specified condition is satisfied is called
iteration. Iteration statements execute the same set of instructions until a termination condition is
met.
Java provides the following loop for iteration statements:
The while loop
The for loop
The do-while loop
The for each loop
Unlabeled Break Statement: This is used to jump program control out of the specific loop on
the specific condition.
int returnCall()
{
return 5;
}
}
A class is a user defined blueprint or prototype from which objects are created. It represents the
set of properties or methods that are common to all objects of one type. In general, class
declarations can include these components, in order:
1. Modifiers : A class can be public or has default access (Refer this for details).
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. Superclass(if any): The name of the class‟s parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
5. Body: The class body surrounded by braces, { }.
Example classes
class Lamp {
boolean isOn;
void turnOn() {
isOn = true;
}
void turnOff() {
isOn = false;
}
}
class ClassObjectsExample {
public static void main(String[] args) {
Lamp l1 = new Lamp(); // create l1 object of Lamp class
Lamp l2 = new Lamp(); // create l2 object of Lamp class
}
}
1.7 Methods in Java
A method is a collection of statements that perform some specific task and return result to the
caller. A method can perform some specific task without returning anything. Methods allow us
to reuse the code without retyping the code. In Java, every method must be part of some class
which is different from languages like C, C++ and Python.
Methods are time savers and help us to reuse the code without retyping the code.
Method Declaration
In general, method declarations has six components :
Modifier-: Defines access type of the method i.e. from where it can be accessed in your
application. In Java, there 4 type of the access specifiers.
public: accessible in all class in your application.
protected: accessible within the class in which it is defined and in its subclass(es)
private: accessible only within the class in which it is defined.
default (declared/defined without using any modifier) : accessible within same class
and package within which its class is defined.
The return type : The data type of the value returned by the the method or void if does not
return a value.
Method Name : the rules for field names apply to method names as well, but the
convention is a little different.
Parameter list : Comma separated list of the input parameters are defined, preceded with
their data type, within the enclosed parenthesis. If there are no parameters, you must use
empty parentheses ().
Exception list : The exceptions you expect by the method can throw, you can specify these
exception(s).
Method body : it is enclosed between braces. The code you need to be executed to perform
your intended operations.
Example methods
class Add
{
public static void main(String[] arg)
{
int a,b,c;
Scanner sc=new Scanner([Link]);
[Link]("Enter first number");
a=[Link]();
[Link]("Enter second number");
b=[Link]();
c=addition(a,b);
[Link](" Addition of two numbers is : "+c);
}
static int addition(int x,int y)
{
return x+y;
}
}
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
Note: Multiple inheritance and hybrid is not supported in Java through class.
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}}
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
Like a class, an interface can have methods and variables, but the methods declared in interface
are by default abstract (only method signature, no body).
Interfaces specify what a class must do and not how. It is the blueprint of the class.
An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move(). So it specifies a set of
methods that the class has to implement.
If a class implements an interface and does not provide method bodies for all functions
specified in the interface, then class must be declared abstract.
A Java library example is, Comparator Interface. If a class implements this interface, then it
can be used to sort a collection.
Java inner class is defined inside the body of another class. Java inner class can be declared
private, public, protected, or with default access whereas an outer class can have only public or
default access.
Java Nested classes are divided into two types.
a. static nested class
If the nested class is static, then it‟s called static nested class. Static nested classes can access
only static members of the outer class. Static nested class is same as any other top-level class and
is nested for only packaging convenience.
Any non-static nested class is known as inner class in java. Java inner class is associated with the
object of the class and they can access all the variables and methods of the outer [Link]
inner classes are associated with instance, we can‟t have any static variables in them.
class Outer {
// Simple nested inner class
class Inner {
public void show() {
[Link]("In a nested class method");
}
}
}
class Main {
public static void main(String[] args) {
[Link] in = new Outer().new Inner();
[Link]();
}
}
Output:
In a nested class method
END OF UNIT-1
In Object-Oriented Programming, association, aggregation, and composition different kinds of relationships between classes. Association is a general binary relationship emphasizing linkage without ownership; objects have independent lifecycles. Aggregation is a form of association with an ownership context, where the child object can exist independently of the parent but is typically part of it. For example, a 'Teacher' and 'Department' are aggregated because a teacher can exist without a department, unlike composition. Composition is a strong form of aggregation with a 'death' relationship; the lifecycle of child objects is tied to that of the parent. If the parent is deleted, so are the children, such as 'House' and 'Room'; a room cannot exist independently of a house .
Selection and iteration statements are fundamental elements that enhance programming logic and control flow in Java. Selection statements, such as if-else and switch, allow a program to make decisions based on conditions, thus directing the flow of execution along different paths. Iteration statements, like for, while, and do-while loops, enable the repeated execution of a block of code as long as a specified condition evaluates to true. These control constructs allow developers to write efficient, complex, and flexible code by managing scenarios such as choosing among different actions or repeating tasks .
In Java, control flow statements like break and continue are used to manage the execution within loops and various control structures. The break statement terminates the loop or switch statement, directing control to the statement immediately following the loop or switch. This mechanism can be used to exit from both simple and nested loops. The continue statement skips the current iteration of a loop and proceeds to the next iteration. Used within loops, continue allows specific iterations to be bypassed based on conditions. These statements help control the flow, optimize execution, and manage scenarios effectively, like exiting prematurely from loops or skipping remaining code in the current iteration .
Primitive data types in Java include int, byte, char, and boolean, among others. They represent raw data and are predefined by the language, stored directly in memory for efficient low-level processing without inherent methods. Object data types, on the other hand, are instances of classes, including arrays, strings, and user-defined classes. These are more complex, encapsulating data and behavior, and are stored in the heap memory. Primitive types offer performance advantages and memory efficiency, while object data types provide the capability of utilizing OOP concepts such as inheritance and encapsulation, offering more extensive functionality .
Polymorphism, a core feature of Object-Oriented Programming, allows objects, methods, or functions to process in different ways depending on their form. It provides the flexibility to call the same method for different types, leading to code that's more flexible and easier to extend. This differs from overloading, which happens at compile time and involves methods with the same name but different parameters within the same class. Polymorphism is dynamic or runtime binding, whereas overloading involves static binding. This distinction makes polymorphism powerful for implementing extensible and adaptable systems, as it decouples the user code from specific type actions, enabling greater flexibility .
Interfaces in Java define a contract that classes can implement, declaring methods without providing any implementation. They specify 'what' a class must do, but not 'how.' A class can implement multiple interfaces, facilitating a form of multiple inheritance. Abstract classes, on the other hand, can provide both method declarations and implementations. They can only be subclassed once in a hierarchy, but unlike interfaces, they can maintain state with instance fields. This makes interfaces ideal for defining capabilities, while abstract classes provide partial implementation and shared code among subclasses. This distinction allows for architectural flexibility in Java applications .
Object-Oriented Programming (OOP) offers several advantages in software development, including a clear modular structure, making programs easier to understand. OOP promotes code reuse through objects that can be utilized across different programs, reducing development costs. Its modular structure allows development teams to better design extensive programs with fewer errors. Because each object exists independently, OOP enhances program modularity, aiding in maintenance and scalability .
Java is a statically typed language, meaning each variable and expression type is determined at compile time. This requires that every variable be explicitly declared with a data type, such as int, float, or boolean, ensuring type safety and performance optimization. Once a variable is declared with a specific type, it cannot hold values of other types, which prevents runtime errors that result from type confusion. Compared to dynamically typed languages like Python, Java's static typing reduces flexibility but increases robustness and reliability. Java also supports both primitive data types, like int and boolean, and object data types, allowing a combination of precision and object-oriented capabilities .
Encapsulation is an OOP concept that involves bundling the data (variables) and methods (functions) that operate on the data into a single unit, typically a class. By restricting access to certain details of an object and only allowing interaction through a defined interface, encapsulation shields the internal representation of the object. This prevents arbitrary access to class members, thereby protecting the integrity of the data. Encapsulation ensures that objects maintain a well-defined interface and that changes to the implementation do not affect outside code. It is significant for data security as it protects against unauthorized access and misuse, maintaining data integrity and consistency .
The core principles of Object-Oriented Programming (OOP) include classes, objects, inheritance, polymorphism, abstraction, and encapsulation. Classes serve as blueprints for creating objects, representing a group of similar entities. Objects are instances of classes, encapsulating data and functions. Inheritance allows one object to acquire properties and behaviors of a parent object, enhancing software organization and design by establishing a hierarchical relationship between classes. Polymorphism enables variables, functions, or objects to take multiple forms, allowing for flexibility in programming. Abstraction involves representing essential features without background details, simplifying complex systems by focusing on relevant components. Encapsulation restricts access to certain components of an object, enhancing security and control. These principles facilitate modular, maintainable, and reusable code, critical for efficient software design .