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 it.The 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)
System.out.println("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++;
System.out.println(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<a.length;i++)//length is the property of array
System.out.println(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<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(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++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
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 java.util.Scanner;
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(System.in);
System.out.println("Enter first number");
a=sc.nextInt();
System.out.println("Enter second number");
b=sc.nextInt();
c=addition(a,b);
System.out.println(" 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();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
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(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
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 class.Since
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() {
System.out.println("In a nested class method");
}
}
}
class Main {
public static void main(String[] args) {
Outer.Inner in = new Outer().new Inner();
in.show();
}
}
Output:
In a nested class method
END OF UNIT-1