[go: up one dir, main page]

0% found this document useful (0 votes)
11 views14 pages

assignment2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 14

1.What is class?

Explain class with its


general structure.
A class in Java is a set of objects which shares common
characteristics/ behavior and common properties/ attributes. It is a
user-defined blueprint or prototype from which objects are created. For
example, Student is a class while a particular student named Ravi is
an object.

Class Declaration in Java


access_modifier class <class_name>
{
data member;
method;
constructor;
nested class;
interface;
}

In general, class declarations can include these components, in order:


1. Modifiers : A class can be public or has default access.

2. Class keyword: class keyword is used to create a class.

3. Class name: The name should begin with an initial letter (capitalized

by convention).
4. 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.
5. 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.
6. Body: The class body is surrounded by braces, { }.

class Student {
// data member (also instance variable)
int id;
// data member (also instance variable)
String name;
public static void main(String args[])
{
// creating an object of
// Student
Student s1 = new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}

2. How objects are created? Explain


refrence variable and assignment
An object in Java is a basic unit of Object-Oriented Programming and
represents real-life entities. Objects are the instances of a class that
are created to use the attributes and methods of a class. A typical
Java program creates many objects, which as you know, interact by
invoking methods. An object consists of :
1.State : It is represented by attributes of an object. It also reflects the

properties of an object.//variables
2.Behavior : It is represented by the methods of an object. It also

reflects the response of an object with other objects.//methods


3.Identity : It gives a unique name to an object and enables one

object to interact with other objects.//class name


Example of an object: dog
Declaring Objects (Also called instantiating a class)
When an object of a class is created, the class is said to
be instantiated . All the instances share the attributes and the
behavior of the class. But the values of those attributes, i.e. the state
are unique for each object. A single class may have any number of
instances.

Understanding Reference variable


1. Reference variable is used to point object/values.
2. Classes, interfaces, arrays, enumerations, and, annotations are
reference types in Java. Reference variables hold the objects/values of
reference types in Java.
3. Reference variable can also store null value. By default, if no object
is passed to a reference variable then it will store a null value.
4. You can access object members using a reference variable
using dot syntax.
<reference variable name >.<instance variable_name /
method_name>

// Java program to demonstrate reference


// variable in java

import java.io.*;

class Demo {
int x = 10;
int display()
{
System.out.println("x = " + x);
return 0;
}
}

class Main {
public static void main(String[] args)
{
Demo D1 = new Demo(); // point 1

System.out.println(D1); // point 2

System.out.println(D1.display()); // point
3
}
}

3. What is method? Explain parameterized


method with different parameters.
The method in Java or Methods of Java is a collection of statements
that perform some specific tasks and return the result to the caller. A
Java method can perform some specific tasks without returning
anything. Java Methods allows us to reuse the code without retyping
the code. In Java, every method must be part of some class that is
different from languages like C, C++, and Python.
A method is like a function i.e. used to expose the behavior of an
object.
It is a set of codes that perform a particular task.
Syntax of Method:
<access_modifier> <return_type> <method_name>( list_of_parameters)
{
//body
}
Advantage of Method:
Code Reusability
Code Optimization

n general, method declarations have 6 components:

1. Modifier: It defines the access type of the method i.e. from where
it can be accessed in your application. In Java, there 4 types of access
specifiers.
public: It is accessible in all classes in your application.

protected: It is accessible within the class in which it is defined and

in its subclasses.
private: It is accessible only within the class in which it is defined.

default: It is declared/defined without using any modifier. It is

accessible within the same class and package within which its class is
defined.
Note: It is Optional in syntax.
2. The return type: The data type of the value returned by the
method or void if does not return a value. It is Mandatory in syntax.

3. Method Name: the rules for field names apply to method names
as well, but the convention is a little different. It is Mandatory in
syntax.
4. Parameter list: Comma-separated list of the input parameters is
defined, preceded by their data type, within the enclosed parenthesis.
If there are no parameters, you must use empty parentheses (). It
is Optional in syntax.
5. Exception list: The exceptions you expect by the method can
throw; you can specify these exception(s). It is Optional in syntax.
6. Method body: it is enclosed between braces. The code you need
to be executed to perform your intended operations. It is Optional in
syntax.
class Addition {

// Initially taking sum as 0


// as we have not started computation
int sum = 0;

// Method
// To add two numbers
public int addTwoInt(int a, int b)
{

// Adding two integer value


sum = a + b;

// Returning summation of two values


return sum;
}
}

// Class 2
// Helper class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating object of class 1 inside main() method


Addition add = new Addition();

// Calling method of above class


// to add two integer
// using instance created
int s = add.addTwoInt(1, 2);

// Printing the sum of two numbers


System.out.println("Sum of two integer values :"
+ s);
}
}

4. What is constructor? Explain


parameterized constructor with different
parameters.
Java constructors or constructors in Java is a terminology used to
construct something in our programs. 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.

class Geek {
// data members of the class.
String name;
int id;

// Parameterized Constructor
Geek(String name, int id)
{
this.name = name;
this.id = id;
}

// Copy Constructor
Geek(Geek obj2)
{
this.name = obj2.name;
this.id = obj2.id;
}
}
class GFG {
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
System.out.println("First Object");
Geek geek1 = new Geek("Avinash", 68);
System.out.println("GeekName :" + geek1.name
+ " and GeekId :" + geek1.id);

System.out.println();

// This would invoke the copy constructor.


Geek geek2 = new Geek(geek1);
System.out.println(
"Copy Constructor used Second Object");
System.out.println("GeekName :" + geek2.name
+ " and GeekId :" + geek2.id);
}
}

5. What is method overloading? Explin it


with appropriate example.
In Java, Method Overloading allows different methods to have the
same name, but different signatures where the signature can differ by
the number of input parameters or type of input parameters, or a
mixture of both.
Method overloading in Java is also known as Compile-time
Polymorphism, Static Polymorphism, or Early binding. In
Method overloading compared to the parent argument, the child
argument will get the highest priority.

public class Sum {


// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y) { return (x + y); }

// Overloaded sum(). This sum takes three int parameters


public int sum(int x, int y, int z)
{
return (x + y + z);
}

// Overloaded sum(). This sum takes two double


// parameters
public double sum(double x, double y)
{
return (x + y);
}

// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
6. What is constructor overloading?
Explain it with appropriate example,

7. What is 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.

8. Explain this keyword with appropriate


example.
In Java, ‘this’ is a reference variable that refers to the current object,
or can be said “this” in Java is a keyword that refers to the current
object instance. It can be used to call current class methods and fields,
to pass an instance of the current class as a parameter, and to
differentiate between the local and instance variables. Using “this”
reference can improve code readability and reduce naming conflicts.

public class Person {

// Fields Declared
String name;
int age;

// Constructor
Person(String name, int age)
{
this.name = name;
this.age = age;
}

// Getter for name


public String get_name() { return name; }

// Setter for name


public void change_name(String name)
{
this.name = name;
}

// Method to Print the Details of


// the person
public void printDetails()
{
System.out.println("Name: " + this.name);
System.out.println("Age: " + this.age);
System.out.println();
}

// main function
public static void main(String[] args)
{
// Objects Declared
Person first = new Person("ABC", 18);
Person second = new Person("XYZ", 22);

first.printDetails();
second.printDetails();

first.change_name("PQR");
System.out.println("Name has been changed to: "
+ first.get_name());
}
}

9. Explain java access modifiers.


in Java, Access modifiers help to restrict the scope of a class,
constructor, variable, method, or data member. It provides security,
accessibility, etc to the user depending upon the access modifier used
with the element. Let us learn about Java Access Modifiers, their types,
and the uses of access modifiers in this article.

Types of Access Modifiers in Java


There are four types of access modifiers available in Java:
1.Default – No keyword required
2.Private
3.Protected
4.Public
1. Default Access Modifier
When no access modifier is specified for a class, method, or data
member – It is said to be having the default access modifier by
default. The data members, classes, or methods that are not declared
using any access modifiers i.e. having default access modifiers are
accessible only within the same package.

2. Private Access Modifier


The private access modifier is specified using the
keyword private. The methods or data members declared as private
are accessible only within the class in which they are declared.

3. Protected Access Modifier


The protected access modifier is specified using the
keyword protected.
The methods or data members declared as protected are accessible
within the same package or subclasses in different packages.

4. Public Access modifier


The public access modifier is specified using the keyword public.
The public access modifier has the widest scope among all other

access modifiers.
Classes, methods, or data members that are declared as public

are accessible from everywhere in the program. There is no


restriction on the scope of public data members.

10. What is recursion?Explain it with


appropriate example
11. What is varaible length arguments?
Explain it with appropriate example.
Variable Arguments (Varargs) in Java is a method that takes a variable
number of arguments. Variable Arguments in Java simplifies the
creation of methods that need to take a variable number of arguments

Syntax of Varargs
Internally, the Varargs method is implemented by using the single
dimensions arrays concept. Hence, in the Varargs method, we can
differentiate arguments by using Index. A variable-length argument is
specified by three periods or dots(…).
For Example,
public static void fun(int ... a)
{
// method body
}
This syntax tells the compiler that fun( ) can be called with zero or
more arguments. As a result, here, a is implicitly declared as an array
of type int[].
class Test1 {
// A method that takes variable
// number of integer arguments.
static void fun(int... a)
{
System.out.println("Number of arguments: "
+ a.length);

// using for each loop to display contents of a


for (int i : a)
System.out.print(i + " ");
System.out.println();
}

// Driver code
public static void main(String args[])
{
// Calling the varargs method with
// different number of parameters

// one parameter
fun(100);

// four parameters
fun(1, 2, 3, 4);

// no parameter
fun();
}
}

12. Explain following term with


appropriate examples
-->Pass object to methods
-->returning object
-->static method and static variable
-->static block
-->nested and inner class
-->overloading varagrs methods

You might also like