[Go to site: main page, start]

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

Java Student Class Constructors

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
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)
8 views12 pages

Java Student Class Constructors

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
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

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() {
[Link]("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
[Link]= n;
[Link] = a;
}
void display() {
[Link](name + " " + age);
}
public static void main(String args[]) {
Student s1 = new Student("Anu", 20);
[Link]();
}
}

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) {
[Link] = i;
[Link] = n;
}
//constructor to initialize another object
Student(Student s) {
[Link] = [Link];
[Link] = [Link];
}
void display() {
[Link](id + " " + name);
}

public static void main(String args[]) {


Student s1 = new Student(101, "Anu");
Student s2 = new Student(s1);
[Link]();
[Link]();
}
}

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 [Link](), 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);
[Link]("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[]){
[Link]("Your first argument is: "+args[0]);
}
}
Note:-
compile by using cmd prompt > javac [Link]
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
[Link] = "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

[Link] 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 < [Link]; i++) //length is the property of array
[Link](a[i]);
}
}

[Link] 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 [Link].*;
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++) {
[Link](num[i][j] + " ");
}
[Link]();
}
}
}

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 [Link] 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 [Link].*;
public class VectorExample {
public static void main(String args[]) {
//Create an empty Vector
Vector < Integer > num = new Vector <> ();
//Add elements in the vector
[Link](10);
[Link](20);
[Link](30);
[Link](20);
[Link](40);

//Display the vector elements


[Link]("Values in vector: " + num);
//use remove() method to delete the first occurence of an element
[Link]("Remove first occourence of 20:" + [Link]((Integer)20));
//Display the vector elements afre remove() method
[Link]("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';
[Link](myInt);
[Link](myDouble);
[Link](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 = [Link];

Example:-

public class Main {


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

Common questions

Powered by AI

Combining command-line arguments and arrays in Java enhances program flexibility by allowing dynamic data input at runtime, which can be stored and manipulated in arrays for efficient processing. Command-line arguments are passed to the main method's string array (String[] args), which serves as the initial input data source . This setup enables programs to handle a variable number of inputs without hardcoding them, facilitating their use in batch processing, testing with different datasets, and user-directed activities more effectively.

Arrays in Java are preferable when the size of the data structure is fixed, and performance is a critical concern, as arrays are more efficient in accessing elements because they provide constant time retrieval . They also require less memory overhead compared to vectors. Vectors are suitable when the data size may fluctuate, and thread safety is necessary as they are synchronized . However, vectors are generally slower due to synchronization overhead. Choosing between arrays and vectors depends on whether fixed size and higher performance or dynamic sizing and safety are more important in the application's context.

The three types of constructors in Java are the default constructor, parameterized constructor, and copy constructor. The default constructor is automatically generated by the compiler if no other constructor is defined; it is used to instantiate objects without specific initial values . The parameterized constructor includes arguments and is used to initialize objects with specific data at the time of creation . The copy constructor creates a new object using values from an existing object, useful for duplicating objects with the same state .

Enumerated types in Java improve code readability and reliability by encapsulating related constants in a single entity with a descriptive name. This reduces the risk of errors from using literal constants, which can be misread or mistyped, leading to bugs. Enums enforce compile-time checking and restrict the values to predefined options, improving maintainability and reducing runtime errors . By using enums, developers can avoid the ambiguity of magic values and make the code more intuitive for others to understand and modify.

The "this" keyword in Java refers to the current object within a method or constructor, helping to differentiate between class attributes and parameters with the same names. It can also invoke constructors or methods of the current class, return the current class object, and be used in calling methods and constructors . Command-line arguments allow users to pass data to the program at runtime, which the program can then use as input, adding versatility to method functionality .

The 'static' keyword in Java indicates that a method or variable belongs to the class rather than any instance of the class. Static members are shared across all instances, providing a global point of access to class-level resources . This contrasts with instance members, which have distinct values for each object. Static methods can be called without object instantiation, allowing them to perform operations irrespective of object states. Since they do not have access to instance variables, they are often used for utility or helper methods that operate on provided arguments without affecting instance data.

Java arrays starting from index 0 is significant as it aligns with zero-based indexing used in many programming languages, facilitating memory addressing and simplifying mathematical calculations in algorithms. It corresponds to the way memory is accessed; the index is used as an offset from the array's base address, making memory lookups consistent and efficient . Zero-based indexing ensures that the distance in terms of elements from the start is the same as the array index itself, aiding in the development of efficient algorithms and reducing off-by-one errors in loop designs and conditional statements.

Garbage collection in Java automates memory management by identifying and removing objects that are no longer used, freeing up space and ensuring efficient memory utilization . This process minimizes memory leaks and potential crashes in applications. The finalize() method allows classes to define cleanup operations before an object is collected by the garbage collector, providing an opportunity to release system resources such as file handles . However, relying heavily on finalize() can lead to performance issues and is generally discouraged as it does not guarantee timely execution.

Wrapper classes in Java allow primitive data types to be used as objects, which is required in contexts where primitives cannot be used, such as generic collections (e.g., ArrayList<Integer> instead of ArrayList<int>). They offer flexibility in such scenarios and provide methods for manipulating data types. However, they introduce additional memory overhead due to object creation and can affect performance. Auto-boxing and unboxing also add to computational overhead when converting between primitive types and wrapper classes, leading to potential inefficiencies in critical code paths.

Visibility control and access modifiers in Java are crucial for encapsulation, a key principle of object-oriented design. They restrict access to different parts of a class and its members, protecting the internal state of objects. Public, protected, package-private (default), and private modifiers provide varying levels of access control, shielding the internal workings from unwanted interference and enforcing a data-hiding mechanism . By controlling visibility, developers can expose only necessary parts of the code, reducing complexity and enhancing maintainability and security.

You might also like