KEMBAR78
Bca IV Sem Unit II (Java) | PDF | Data Type | Java (Programming Language)
0% found this document useful (0 votes)
15 views22 pages

Bca IV Sem Unit II (Java)

The document provides an overview of Java programming concepts, focusing on arrays, constructors, garbage collection, and the final keyword. It explains the structure and types of arrays, including single-dimensional, multidimensional, and jagged arrays, as well as the use of constructors for object initialization. Additionally, it covers garbage collection mechanisms in Java and the implications of using the final keyword in variable, method, and class definitions.

Uploaded by

Sahil Chouhan
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)
15 views22 pages

Bca IV Sem Unit II (Java)

The document provides an overview of Java programming concepts, focusing on arrays, constructors, garbage collection, and the final keyword. It explains the structure and types of arrays, including single-dimensional, multidimensional, and jagged arrays, as well as the use of constructors for object initialization. Additionally, it covers garbage collection mechanisms in Java and the implications of using the final keyword in variable, method, and class definitions.

Uploaded by

Sahil Chouhan
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/ 22

RENAISSANCE UNIVERSITY, INDORE

BCA IV SEM
Subject: Java Programming
Unit I:

Array

Normally, an array is a collection of similar type of elements which has contiguous memory
location.
Java array is an object which contains elements of a similar data type. Additionally, The elements
of an array are stored in a contiguous memory location. 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 0th index, 2nd element is
stored on 1st index and so on.

Types of Array in java


There are two types of array.

1. Single Dimensional Array


2. Multidimensional Array

Single Dimensional Array in Java


Syntax to Declare an Array in Java

dataType[] arr;
dataType []arr;
dataType arr[];

Instantiation of an Array in Java

arrayRefVar=new datatype[size];

Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:

int a[]={33,3,4,5};//declaration, instantiation and initialization

1|Page
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit I:

1. class ArrayDemo{
2. public static void main(String args[]){
3. int a[]=new int[5];//declaration and instantiation
4. a[0]=10;//initialization
5. a[1]=20;
6. a[2]=70;
7. a[3]=40;
8. a[4]=50;
9. //Displaying the elements of array
10. for(int i=0;i<a.length;i++)//length is the property of array
11. System.out.println(a[i]);
12. }}

For-each Loop for Java Array


We can also print the Java array using for-each loop. The Java for-each loop prints the array
elements one by one. It holds an array element in a variable, then executes the body of the loop.

The syntax of the for-each loop is given below:

for(data_type variable:array){
//body of the loop
}

1. //Java Program to print the array elements using for-each loop


2. class Testarray1{
3. public static void main(String args[]){
4. int arr[]={33,3,4,5};
5. //printing array using for-each loop
6. for(int i:arr)
7. System.out.println(i);
8. }}

2|Page
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit I:

Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java

dataType[][] arrayRefVar; (or)


dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java

int[][] arr=new int[3][3]; //3 row and 3 column

Example of Multidimensional Java Array

1. //Java Program to illustrate the use of multidimensional array


2. class Testarray{
3. public static void main(String args[]){
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6. //printing 2D array
7. for(int i=0;i<3;i++){
8. for(int j=0;j<3;j++){
9. System.out.print(arr[i][j]+" ");
10. }
11. System.out.println();
12. }
13. }}

3|Page
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit I:

Jagged Array in Java

If we are creating odd number of columns in a 2D array, it is known as a jagged array. In other
words, it is an array of arrays with different number of columns.

1. //Java Program to illustrate the jagged array


2. class JaggedArray{
3. public static void main(String[] args){
4. //declaring a 2D array with odd columns
5. int arr[][] = new int[3][];
6. arr[0] = new int[3];
7. arr[1] = new int[4];
8. arr[2] = new int[2];
9. //initializing a jagged array
10. int count = 0;
11. for (int i=0; i<arr.length; i++)
12. for(int j=0; j<arr[i].length; j++)
13. arr[i][j] = count++;
14.
15. //printing the data of a jagged array
16. for (int i=0; i<arr.length; i++){
17. for (int j=0; j<arr[i].length; j++){
18. System.out.print(arr[i][j]+" ");
19. }
20. System.out.println();//new line
21. }
22. }
23. }

Output :

0 1 2
3 4 5 6
7 8

4|Page
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit I:

Java Constructors

A constructor in Java is a special method that is used to initialize objects. The constructor is called
when an object of a class is created. It can be used to set initial values for object attributes:

In Java, a constructor is a block of codes similar to the method. It is called when an instance of the
class is created. At the time of calling constructor, memory for the object is allocated in the
memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is called.

It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.

There are two types of constructors in Java: no-arg constructor (default Constructor) , and
parameterized constructor.

Rules for creating Java constructor:


There are two rules defined for the constructor.

• Constructor name must be the same as its class name


• A Constructor must have no explicit return type
• A Java constructor cannot be abstract, static, final, and synchronized

5|Page
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit I:

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:

1. //Java Program to create and call a default constructor


2. class Bike{
3. //creating a default constructor
4. Bike(){System.out.println("Bike is created");}
5. //main method
6. public static void main(String args[]){
7. //calling a default constructor
8. Bike b=new Bike();
9. }
10. }

6|Page
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit I:

Java Parameterized Constructor


A constructor which has a specific number of parameters is called a parameterized constructor. The
parameterized constructor is used to provide different values to distinct objects.

11. //Java Program to demonstrate the use of the parameterized cons


tructor.
12. class Student{
13. int id;
14. String name;
15. //creating a parameterized constructor
16. Student(int i,String n){
17. id = i;
18. name = n;
19. }
20. //method to display the values
21. void display(){System.out.println(id+" "+name);}
22.
23. public static void main(String args[]){
24. //creating objects and passing values
25. Student s1 = new Student(101,"Kunal");
26. Student s2 = new Student(102,"Pooja");
27. //calling method to display the values of object
28. s1.display();
29. s2.display();
30. }
31. }

Output :

101 Kunal

102 Pooja

7|Page
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit I:

Garbage Collection

Garbage collection in Java is the process by which Java programs perform automatic memory
management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or
JVM for short. When Java programs run on the JVM, objects are created on the heap, which is a
portion of memory dedicated to the program. Eventually, some objects will no longer be needed.
The garbage collector finds these unused objects and deletes them to free up memory.

What is Garbage Collection?


In C/C++, a programmer is responsible for both the creation and destruction of objects. Usually,
programmer neglects the destruction of useless objects. Due to this negligence, at a certain point,
sufficient memory may not be available to create new objects, and the entire program will terminate
abnormally, causing OutOfMemoryErrors.

But in Java, the programmer need not care for all those objects which are no longer in use. Garbage
collector destroys these objects. The main objective of Garbage Collector is to free heap memory by
destroying unreachable objects. The garbage collector is the best example of the Daemon thread as
it is always running in the background.

How Does Garbage Collection in Java works?


Java garbage collection is an automatic process. Automatic garbage collection is the process of
looking at heap memory, identifying which objects are in use and which are not, and deleting the
unused objects. An in-use object, or a referenced object, means that some part of your program still
maintains a pointer to that object. An unused or unreferenced object is no longer referenced by any
part of your program. So the memory used by an unreferenced object can be reclaimed. The
programmer does not need to mark objects to be deleted explicitly. The garbage collection
implementation lives in the JVM.

Types of Activities in Java Garbage Collection


Two types of garbage collection activity usually happen in Java. These are:

1. Minor or incremental Garbage Collection: It is said to have occurred when unreachable objects
in the young generation heap memory are removed.
2. Major or Full Garbage Collection: It is said to have occurred when the objects that survived the
minor garbage collection are copied into the old generation or permanent generation heap memory
are removed. When compared to the young generation, garbage collection happens less frequently
in the old generation.

8|Page
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit I:

Important Concepts Related to Garbage Collection in Java

1. Unreachable objects: An object is said to be unreachable if it doesn’t contain any reference


to it. Also, note that objects which are part of the island of isolation are also unreachable.

Integer i = new Integer(4);


// the new Integer object is reachable via the reference in 'i'
i = null;
// the Integer object is no longer reachable.

2. Eligibility for garbage collection: An object is said to be eligible for GC(garbage collection) if
it is unreachable. After i = null, integer object 4 in the heap area is suitable for garbage collection in
the above image.

Ways to make an object eligible for Garbage Collector

Even though the programmer is not responsible for destroying useless objects but it is highly
recommended to make an object unreachable(thus eligible for GC) if it is no longer required.
9|Page
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit I:

There are generally four ways to make an object eligible for garbage collection.

• Nullifying the reference variable


• Re-assigning the reference variable
• An object created inside the method
• Island of Isolation

Ways for requesting JVM to run Garbage Collector

Once we make an object eligible for garbage collection, it may not destroy immediately by the
garbage collector. Whenever JVM runs the Garbage Collector program, then only the object will be
destroyed. But when JVM runs Garbage Collector, we can not expect.

We can also request JVM to run Garbage Collector. There are two ways to do it :

1) Using System.gc() method: System class contain static method gc() for requesting JVM to
run Garbage Collector.
2) Using Runtime.getRuntime().gc() method: Runtime class allows the application to interface
with the JVM in which the application is running. Hence by using its gc() method, we can
request JVM to run Garbage Collector.
3) There is no guarantee that any of the above two methods will run Garbage Collector.
4) The call System.gc() is effectively equivalent to the call : Runtime.getRuntime().gc()

Advantages of Garbage Collection in Java

The advantages of Garbage Collection in Java are:

• It makes java memory-efficient because the garbage collector removes the unreferenced
objects from heap memory.
• It is automatically done by the garbage collector(a part of JVM), so we don’t need extra
effort.

10 | P a g e
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit I:

Final & Static keywords

Final Keyword In Java

The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:

1) variable
2) method
3) 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. We will have
detailed learning of these. Let's first learn the basics of final keyword.

1) Java final variable

If you make any variable as final, you cannot change the value of final variable(It will be constant).

Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but It can't be
changed because final variable once assigned a value can never be changed.

1. class Bike{
2. final int speedlimit=90; //final variable
3. void run(){
4. speedlimit=400; //Error - can not change
5. }
6. public static void main(String args[]){
7. Bike obj=new Bike();
8. obj.run();
9. }
10. }

11 | P a g e
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit I:

2) Java final method

If you make any method as final, you cannot override it.

Example of final method

1. class Bike{
2. final void run(){
3. System.out.println("running");
4. }
5. }
6.
7. class Honda extends Bike{
8. void run() //Error – can not override
9. {System.out.println("running safely with 100kmph");
10. }
11. public static void main(String args[]){
12. Honda honda= new Honda();
13. honda.run();
14. }
15. }

12 | P a g e
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit I:

3) Java final class

If you make any class as final, you cannot extend it.

Example of final class

1. final class Bike{}


2.
3. class Honda1 extends Bike //Error – can not Inherit
4. {
5. void run(){System.out.println("running safely with 100kmph");}
6.
7. public static void main(String args[]){
8. Honda1 honda= new Honda1();
9. honda.run();
10. }
11. }

13 | P a g e
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit I:

static Keyword in Java

The static keyword in Java is mainly used for memory management. The static keyword in Java is
used to share the same variable or method of a given class. The users can apply static keywords
with variables, methods, blocks, and nested classes. The static keyword belongs to the class than an
instance of the class. The static keyword is used for a constant variable or a method that is the same
for every instance of a class.

The static keyword is a non-access modifier in Java that is applicable for the following:

1) Blocks
2) Variables
3) Methods
4) Classes

Characteristics of static keyword:

Here are some characteristics of the static keyword in Java:

• Shared memory allocation: Static variables and methods are allocated memory space only
once during the execution of the program. This memory space is shared among all instances
of the class, which makes static members useful for maintaining global state or shared
functionality.
• Accessible without object instantiation: Static members can be accessed without the need to
create an instance of the class. This makes them useful for providing utility functions and
constants that can be used across the entire program.
• Associated with class, not objects: Static members are associated with the class, not with
individual objects. This means that changes to a static member are reflected in all instances
of the class, and that you can access static members using the class name rather than an
object reference.
• Cannot access non-static members: Static methods and variables cannot access non-static
members of a class, as they are not associated with any particular instance of the class.
• Can be overloaded, but not overridden: Static methods can be overloaded, which means
that you can define multiple methods with the same name but different parameters.
However, they cannot be overridden, as they are associated with the class rather than with a
particular instance of the class.

14 | P a g e
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit I:

// Java program to demonstrate that a static member


// can be accessed before instantiating a class

class Test
{
// static method
static void m1()
{
System.out.println("from m1");
}

public static void main(String[] args)


{
// calling m1 without creating
// any object of class Test
m1();
}
}

15 | P a g e
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit I:

Array of Objects in Java

Java is an object-oriented programming language. Most of the work done with the help of objects.
We know that an array is a collection of the same data type that dynamically creates objects and can
have elements of primitive types. Java allows us to store objects in an array. In Java, the class is
also a user-defined data type. An array that conations class type elements are known as an array of
objects. It stores the reference variable of the object.

Creating an array of class objects in Java is similar to creating an array of any other type. The
syntax for creating an array of class objects is as follows:

ClassName[] arrayName = new ClassName[size];

For example, to create an array of objects of the class "Person", we would use the following code:

Person[] people = new Person[10];

This creates an array named "people" that can hold up to 10 objects of the class "Person". However,
it should be noted that the array is initially filled with null values and the objects needs to be
initialized before they can be used.

people[0] = new Person("John Smith");

people[1] = new Person("Jane Doe");

Arrays of class objects also allow us to use the functionality of the class they are holding. For
example, if we have a class "Car" which has the method "drive()", we can use this method on all the
elements of the array of cars.

Car[] cars = new Car[5];

cars[0] = new Car("Honda Civic");

cars[1] = new Car("Toyota Camry");

for (int i = 0; i < cars.length; i++) {

cars[i].drive();

16 | P a g e
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit I:

Variable Argument (Varargs):

The varrags allows the method to accept zero or muliple arguments. Before varargs either we use
overloaded method or take an array as the method parameter but it was not considered good
because it leads to the maintenance problem. If we don't know how many argument we will have to
pass in the method, varargs is the better approach.

Advantage of Varargs:

We don't have to provide overloaded methods so less code.

Syntax of varargs:

The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows:

return_type method_name(data_type... variableName)

Simple Example of Varargs in java:

1. class VarargsExample{
2.
3. static void display(String... values){
4. System.out.println("display method invoked ");
5. }
6.
7. public static void main(String args[]){
8.
9. display();//zero argument
10. display("my","name","is","varargs");//four arguments
11. }
12. }

17 | P a g e
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit I:

this keyword in Java

There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to
the current object.

Usage of Java this keyword

Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

18 | P a g e
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit I:

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}

class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

19 | P a g e
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit I:

OOPs (Object-Oriented Programming System)

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:

• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• 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 -

Collection of objects is called class. It is a logical entity.

A class can also be defined as a blueprint from which you can create an individual object. Class
doesn't consume any space.

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.

20 | P a g e
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit I:

Polymorphism -

If one task is performed in different ways, it is known as polymorphism. For example: to convince
the customer differently, to draw something, for example, shape, triangle, rectangle, etc.

In Java, we use method overloading and method overriding to achieve 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.

21 | P a g e
Study Notes (For Private Circular Only)
RENAISSANCE UNIVERSITY, INDORE
BCA IV SEM
Subject: Java Programming
Unit I:

Access Modifier:

There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or
class. We can change the access level of fields, constructors, methods, and class by applying the
access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within
the class, outside the class, within the package and outside the package.

22 | P a g e
Study Notes (For Private Circular Only)

You might also like