0% found this document useful (0 votes)
18 views12 pages

Java Notes Unit II

The document discusses different types of Java constructors including default, parameterized, and copy constructors. It also discusses Java methods, the 'this' keyword, command line arguments, garbage collection, and arrays including single and multi-dimensional arrays.

Uploaded by

aiden.atz78
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
18 views12 pages

Java Notes Unit II

The document discusses different types of Java constructors including default, parameterized, and copy constructors. It also discusses Java methods, the 'this' keyword, command line arguments, garbage collection, and arrays including single and multi-dimensional arrays.

Uploaded by

aiden.atz78
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 12

Java Constructors

While performing some logic functions, the constructor will be executed first before
accessing other variables or functions. A constructor in Java is similar to a method
that is invoked when an object of the class is created. At the time of calling the
constructor, memory for the object is allocated in the memory.
Rules for creating Java constructor
There are three rules defined for the constructor.
• Constructor name must be the same as its class name
• A Constructor must have no return type
• A Java constructor cannot be static. We know static keyword belongs to a class
rather than the object of a class. A constructor is called when an object of a
class is created, so no use of the static constructor.
Types of Java constructors
There are three types of constructors in Java:
• Default constructor
• Parameterized constructor
• Copy constructor
1. Default Constructor:
The term default constructor can refer to a constructor that is automatically generated
by the compiler in the absence of any programmer-defined constructors. A
constructor is called "Default Constructor" when it doesn't have any parameter.
syntax:
class_name(){}
Example:
class Student {
//creating a default constructor
Student() {
System.out.println("Welcome to ShapeAI and This is Constructor");
}
//main method
public static void main(String args[]) {
//calling a default constructor
Student s1 = new Student();
}
}

2. 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.
syntax:
class_name(parameter-list){}

Example:
public class Student {
String name;
int age;
//constructor
Student(String n, int a) { // parameterized constructor with parameters
this.name= n;
this.age = a;
}
void display() {
System.out.println(name + " " + age);
}
public static void main(String args[]) {
Student s1 = new Student("Anu", 20);
s1.display();
}
}

3. Copy Constructor:
A copy constructor is a constructor that creates a new object using an existing object
of the same class. It returns a duplicate copy of an existing object of the class.
syntax:
Class_name(Class_name object_name){ }

Example:
public class Student {
int id;
String name;
//constructor to initialize integer and string
Student(int i, String n) {
this.id = i;
this.name = n;
}
//constructor to initialize another object
Student(Student s) {
this.id = s.id;
this.name = s.name;
}
void display() {
System.out.println(id + " " + name);
}

public static void main(String args[]) {


Student s1 = new Student(101, "Anu");
Student s2 = new Student(s1);
s1.display();
s2.display();
}
}

Java Methods:-
A method is a block of code which only runs when it is called. You can
pass data, known as parameters, into a method. Methods are used to
perform certain actions, and they are also known as functions.
Create Method:-
A method must be declared within a class. It is defined with the name of
the method, followed by parentheses (). Java provides some pre-defined
methods, such as System.out.println(), but you can also create your own
methods to perform certain actions.
Example:-
public class Main {
static void myMethod() {
// code to be executed
}
}

Call a Method:-
To call a method in Java, write the method's name followed by two
parentheses () and a semicolon; In the above example, myMethod() is
used to print a text (the action), when it is called.

“this” Keyword:-
The this keyword refers to the current object in a method or constructor. The most
common use of the this keyword is to eliminate the confusion between class
attributes and parameters with the same name.
“this” can also be used to:
• Invoke current class constructor
• Invoke current class method
• Return the current class object
• Pass an argument in the method call
• Pass an argument in the constructor call
Example:-
public class Main {
int x;
// Constructor with a parameter
public Main(int x) {
this.x = x;
}
// Call the constructor
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println("Value of x = " + myObj.x);
}
}

Java Command Line Arguments:-


The java command-line argument is an argument i.e. passed at the time of running
the java program. The arguments passed from the console can be received in the java
program and it can be used as an input.
Example:-
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
Note:-
compile by using cmd prompt > javac CommandLineExample.java
run by cmd prompt > java CommandLineExample GOPAL
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. The garbage collector finds unused objects and deletes them to free
up memory.

finalize() method:-
The finalize() method in Java is a method of the Object class used to perform cleanup
activity before destroying any object. Garbage collector calls it before destroying the
objects from memory. finalize method in Java is called by default for every object
before its deletion.

Visibility Control/Access Modifier:-

Modifier Description

Default declarations are visible only within the package (package private)

Private declarations are visible within the class only

Protected declarations are visible within the package or all subclasses

Public declarations are visible everywhere

Example:-
class Data {
// private variable
private String name;
}
public class Main {
public static void main(String[] main){

// create an object of Data


Data d = new Data();
// access private variable and field from another class
d.name = "Kapil";
}
}

Java Arrays:-
An array is a group of related data items that have a common name. It is a data
structure where we store similar elements. We can store only a fixed set of elements
in a Java array. Array index starts from 0. The main advantage of the array is Random
access. We can get any data located at an index position.

There are two types of array.


• Single Dimensional Array
• Two Dimensional Array

1.Single Dimensional Array:


A one-dimensional array (or single dimension array) is a type of linear array.
Accessing its elements involves a single subscript that can either represent a row or
column index.
syntax:
data type []arrayname; (or)
data type arrayname[];

Instantiation of an Array:
An array is instantiated to create memory using new keyword.
arrayname = new data type[size];

Initialization of Arrays:
arrayname[subscript/index] = value; // initialization of arrays
type arrayname[] = { list of values }; // declaration and initialization of
arrays
Example:-
Example:
class ArrayExample {
public static void main(String args[]) {
int a[] = new int[5]; //declaration and instantiation
a[0] = 10; //initialization
a[1] = 20;
a[2] = 30;
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]);
}
}

2.Two Dimensional Array:


The two-dimensional array can be defined as an array of arrays with two
subscripts. The two-dimensional array is organized as matrices which can be
represented as the collection of rows and columns.

syntax:
type arrayname[rows][columns];
Instantiation of an Array:
An array is instantiated to create memory using new keyword.
arrayname = new type[row-size][column-size];
Initialization of Arrays:
arrayname[subscript][subscript] = value; // initialization of arrays

type arrayname[][] = { list of values }; // declaration and initialization of arrays


Example:
import java.lang.*;
class ArrayExample {
public static void main(String args[]) {
//declaring and initializing 2D array
int num[][] = {
{1,2,3},
{4,5,6},
{7,8,9}
};
//printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(num[i][j] + " ");
}
System.out.println();
}
}
}

Vectors:- The Vector class is used to create a generic dynamic array known
as vectors that can hold objects of any type and any number. It is contained
in java.util package. Arrays can be easily implemented as vectors.

• It is convenient to use vectors to store objects.


• A vector can be used to store a list of objects that may vary in size.
• We can add and delete objects from the list.

Creating vectors:

Vector <data type> vector_name = new Vector <data type> (); //declaring without size
Vector <data type> vector_name = new Vector <data type> (3);// declaring with size

Example :
import java.util.*;
public class VectorExample {
public static void main(String args[]) {
//Create an empty Vector
Vector < Integer > num = new Vector <> ();
//Add elements in the vector
num.add(10);
num.add(20);
num.add(30);
num.add(20);
num.add(40);

//Display the vector elements


System.out.println("Values in vector: " + num);
//use remove() method to delete the first occurence of an element
System.out.println("Remove first occourence of 20:" + num.remove((Integer)20));
//Display the vector elements afre remove() method
System.out.println("Values in vector: " + num);;

}
}

Java Wrapper Classes:-

Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as
objects. The table below shows the primitive type and the equivalent wrapper class:

Primitive Data Type Wrapper Class


byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character

Example:-

ArrayList<int> myNumbers = new ArrayList<int>(); // Invalid

ArrayList<Integer> myNumbers = new ArrayList<Integer>(); // Valid

To create a wrapper object, use the wrapper class instead of the primitive type.
To get the value, you can just print the object.

Example

public class Main {


public static void main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
System.out.println(myInt);
System.out.println(myDouble);
System.out.println(myChar);
}
}

Enumerated types in java:-

Enums:-

An enum is a special "class" that represents a group of constants (unchangeable


variables, like final variables).

To create an enum, use the enum keyword (instead of class or interface), and separate
the constants with a comma. Note that they should be in uppercase letters.

Example:-

enum Level {

LOW,

MEDIUM,

HIGH

You can access enum constants with the dot syntax:

Level myVar = Level.MEDIUM;

Example:-

public class Main {


enum Level {
LOW,
MEDIUM,
HIGH
}
public static void main(String[] args) {
Level myVar = Level.MEDIUM;
System.out.println(myVar);
} }

You might also like