java programming notes unit 3-4
java programming notes unit 3-4
Arrays
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
Declaring Array Variables:
To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable:
Creating Arrays:
You can create an array by using the new operator with the following syntax:
It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below:
The array elements are accessed through the index. Array indices are 0-based; that is, they
start from 0 to arrayRefVar.length-1.
Example:
Following statement declares an array variable, myList, creates an array of 10 elements of
double type and assigns its reference to myList:
Following picture represents array myList. Here, myList holds ten double values and the
indices are from 0 to 9.
Processing Arrays:
When processing array elements, we often use either for loop or for each loop because all of the
elements in an array are of the same type and the size of the array is known.
Example:
Here is a complete example of showing how to create, initialize and process arrays:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
Constructor in java is a special type of method that is used to initialize the object. Java
constructor is invoked at the time of object creation. It constructs the values i.e. provides data
for the object that is why it is known as constructor.
2. Parameterized constructor
Output:
111 Karan
222 Aryan
s2.display();
}}
Output:
111 Karan 0
222 Aryan 25
There is no copy constructor in java. But, we can copy the values of one object to another like
copy constructor in C++. There are many ways to copy the values of one object into another in
java. They are:
By constructor
By assigning the values of one object into another
In this example, we are going to copy the values of one object into another using java
constructor.
class Student6{
int id; String name;
Student6(int i,String n){ id = i;
name = n;
Output:
111 Karan
111 Karan
Java -Methods
A Java method is a collection of statements that are grouped together to perform an operation.
When you call the System.out.println() method, for example, the system actually executes
several statements in order to display a message on the console.
Creating Method
Syntax
Here,
a, b − formal parameters
Method definition consists of a method header and a method body. The same is shown in the
following syntax −
Syntax
modifier − It defines the access type of the method and it is optional to use.
nameOfMethod − This is the method name. The method signature consists of the
method name and the parameter list.
Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero parameters.
method body − The method body defines what the method does with the
statements.
There is only call by value in java, not call by reference. If we call a method passing a value, it
is known as call by value. The changes being done in the called method, is not affected in the
In case of call by value original value is not changed. Let's take a simple example:
class Operation{
int data=50;
Output:before change 50
after change 50
}
In Java, parameters are always passed by value. For example, following program prints i = 10,
j = 20.
// Test.java class Test {
// swap() doesn't swap i and j
public static void swap(Integer i, Integer j)
{ Integer temp = new Integer(i);
i = j;
j = temp;
}
public static void main(String[] args) { Integer i = new Integer(10);
Integer j = new Integer(20); swap(i, j);
System.out.println("i = " + i + ", j = " + j);
}
The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than instance of the class.
block
nested class
o The static variable can be used to refer the common property of all objects (that is not
unique for each object) e.g. company name of employees,college name of students etc.
o The static variable gets memory only once in class area at the time of class loading.
class Student{
int rollno;
String college="ITS";
5. }
class Student8{
int rollno;
String name;
s1.display();
s2.display();
}}
If you apply static keyword with any method, it is known as static method.
o A static method can be invoked without the need for creating an instance of a class.
Student9.change();
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display();
s2.display();
s3.display();
Access Control
default
protected
public
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
JAVA PROGRAMMING Page 14
class, so there is compile time error.
class A{
If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package.
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{
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
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
Example of public access modifier
//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
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
class Student
{ int rollno; String name; float fee;
Student(int rollno,String name,float fee){
Output:
111 ankit 5000
112 sumit 6000
Constructor must not have return type. Method must have return type.
Constructor name must be same as the Method name may or may not be same as
class name. class name.
There are many differences between constructors and methods. They are given belo
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
Output:
111 Karan 0
222 Aryan 25
If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers. In this example, we are
creating static methods so that we don't need to create instance for calling methods.
class Adder{
class TestOverloading1{
22
33
In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
Recursion in Java
Recursion in java is a process in which a method calls itself continuously. A method in java that
JAVA PROGRAMMING Page 21
calls itself is called recursive method.
Java Recursion Example 1: Factorial Number
public class RecursionExample3 {
if (n == 1) return 1; else
return(n * factorial(n-1));
}}
Output:
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies software development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes up
some space in memory. Objects can communicate without knowing the details of each other's
data or code. The only necessary thing is the type of message accepted and the type of response
returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Class
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
Another example can be to speak something; for example, a cat speaks meow, dog barks woof,
etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing. In Java, we use abstract class and interface to
achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation. For
example, a capsule, it is wrapped with different medicines. A java class is the example of
encapsulation. Java bean is the fully encapsulated class because all the data members are
private here.
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object. Inheritance represents the IS-A relationship, also known as
parent-child relationship.
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
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);
}}
File: TestInheritance.java
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();
}}
Output: barking...
eating...
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){ Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
A subclass includes all of the members of its super class but it cannot access those members of
the super class that have been declared as private. Attempt to access a private variable would
cause compilation error as it causes access violation. The variables declared as private, is only
accessible by other members of its own class. Subclass have no access to it.
The super keyword in java is a reference variable which is used to refer immediate parent class
object. Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
class Animal{
String color="white";
class TestSuper1{
}}
Output:
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
variable
method
class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the
static block only.
The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java. The Object class is beneficial if you want to refer any object whose type
you don't know. Notice that parent class reference variable can refer the child class object,
know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any
type like Employee,Student etc, we can use Object class reference to refer that object. For
example:
1. Object obj=getObject();//we don't know what object will be returned from this method
The Object class provides some common behaviors to all the objects such as object can be
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in java.
Usage of Java Method Overriding
1. class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
Output:
SBI Rate of Interest: 8
A class that is declared with abstract keyword is known as abstract class in java. It can have
abstract and non-abstract methods (method with body). It needs to be extended and its method
implemented. It cannot be instantiated.
abstract method
1. }
running safely..
Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in java is a mechanism to achieve abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve abstraction and multiple
inheritance in Java.
Java Interface also represents IS-A relationship. It cannot be instantiated just like abstract
class. There are mainly three reasons to use interface. They are given below.
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.
Output:drawing circle
Output:Hello
Welcome
1) Abstract class can have abstract Interface can have only abstract methods.
and non-abstract methods. Since Java 8, it can have default and
static methods also.
3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
6) Example: Example:
public abstract class shape public interface Drawable{
{ void draw();
Public abstract void draw(); }
}
Method overloading may or may not require Method overriding always needs
inheritance. inheritance.
Static binding is being used for overloaded Dynamic binding is being used for
methods. overriding methods.
The argument list should be different while The argument list should be the same in
doing method overloading. method overriding.
A functional interface is an interface that contains only one abstract method. They can have
only one functionality to exhibit. From Java 8 onwards, lambda expressions can be used to
represent the instance of a functional interface. A functional interface can have any number of
default methods. Runnable, ActionListener, and Comparable are some of the examples of
functional interfaces.
}).start();