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

Unit 2 Java

Uploaded by

Anuj Suthar
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)
7 views14 pages

Unit 2 Java

Uploaded by

Anuj Suthar
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/ 14

PRAYOSHA ENGINEERING CLASSES Advanced Object Oriented Programming (CE SEM 4)

----------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------

UNIT 2 Object Oriented Programming 18 Marks


---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Q.1 – What is Diff. between Procedure-Oriented vs. Object-Oriented Programming

Procedure Oriented Programming (POP) Object Oriented Programming (OOP)

importance is on doing things not on data importance is on data rather than procedure
Main focus is on the function and procedure Main focus is on the data that is being operated
that operate on data
Top Down approach in program design Bottom Up approach in program design
Large programs are divided into smaller Large programs are divided into classes and
programs known as functions objects
Most of the functions share global data Data is tied together with function in the data
structure.
Data moves openly in the system from one Data is hidden and cannot be accessed by external
function to another function functions
Adding of data and function is difficult Adding of data and function is easy
Concepts like inheritance, polymorphism, data Concepts like inheritance, polymorphism, data
encapsulation, abstraction, access specifier are encapsulation, abstraction, access specifier are
missing available and can be used easily
Examples: C, Fortran, Pascal, etc… Examples: C++, Java, C#, etc…

Q.2 – Explain Basics of OOP.?

 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

N.S.PATEL - 7600031265 N.K.PATEL - 9429235711


PRAYOSHA ENGINEERING CLASSES Advanced Object Oriented Programming (CE SEM 4)
----------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------
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

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

 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.
Q.3 – Explain public, private, protected, default ?

 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.
 Private: The access level of a private modifier is only within the class. It cannot be accessed from outside
the class.
 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.
 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.
Q.4 – Explain This Keyword.?

 There can be a lot of usage of Java this keyword.


 In Java, this is a reference variable that refers to the current object.

N.S.PATEL - 7600031265 N.K.PATEL - 9429235711


PRAYOSHA ENGINEERING CLASSES Advanced Object Oriented Programming (CE SEM 4)
----------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------
 Here is given the 6 usage of java this keyword.
 this can be used to refer current class instance variable.
 this can be used to invoke current class method (implicitly)
 this() can be used to invoke current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
 this can be used to return the current class instance from the method.
 Example
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 Test
{
public static void main(String args[])
{
Student s1=new Student(111,"Nirmal",5000f);
Student s2=new Student(112,"Nihar",6000f);
s1.display();
s2.display();
}
}
-----------------------------------------------------------------------------------------------
Output :
111 Nirmal 5000.0
112 Nihar 6000.0

Q.5 – Explain Static Keyword.?

 The static keyword in Java is used for memory management mainly.


 We can apply static keyword with variables, methods, blocks and nested classes.
 The static keyword belongs to the class than an instance of the class.
N.S.PATEL - 7600031265 N.K.PATEL - 9429235711
PRAYOSHA ENGINEERING CLASSES Advanced Object Oriented Programming (CE SEM 4)
----------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------
 The static can be:

 Variable (also known as a class variable)


 Method (also known as a class method)
 Block
 Nested class

 If you declare any variable as static, it is known as a static variable.


 The static variable can be used to refer to the common property of all objects (which is not unique for
each object), for example, the company name of employees, college name of students, etc.
 The static variable gets memory only once in the class area at the time of class loading.

 Advantages of static variable


 It makes your program memory efficient (i.e., it saves memory).

 Example:
//Java Program to demonstrate the use of static variable
class Student
{
int rollno; //instance variable
String name;
static String college ="Prayosha"; //static variable
//constructor
Student(int r, String n)
{
rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects

public class TestStaticVariable


{
public static void main(String args[])
{
Student s1 = new Student(111,"N.S.Patel");
Student s2 = new Student(222,"N.K.Patel");

//we can change the college of all objects by the single line of code
//Student.college="GP Himatnagar";

s1.display();
s2.display();
}
}

N.S.PATEL - 7600031265 N.K.PATEL - 9429235711


PRAYOSHA ENGINEERING CLASSES Advanced Object Oriented Programming (CE SEM 4)
----------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------

Q.6 – Explain Final Keyword.?

 The final keyword in java is used to restrict the user.


 The java final keyword can be used in many context.

 Final Keyword 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.
 We will have detailed learning of these. Let's first learn the basics of final keyword.

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

class Bike
{
final int speedlimit=90; //final variable
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike obj=new Bike9();
obj.run();
}

 Example of final method


class Bike
{
final void run()
{
System.out.println("running");
}
N.S.PATEL - 7600031265 N.K.PATEL - 9429235711
PRAYOSHA ENGINEERING CLASSES Advanced Object Oriented Programming (CE SEM 4)
----------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------
}

class Honda extends Bike


{
void run()
{
System.out.println("running safely with 100kmph");
}

public static void main(String args[])


{
Honda honda= new Honda();
honda.run();
}
}

 Example of final class



final class Bike
{
}

class Honda1 extends Bike


{
void run()
{
System.out.println("running safely with 100kmph");
}

public static void main(String args[])


{
Honda1 honda= new Honda1();
honda.run();
}
}

Q.7 – Explain Constructors.? Types of Constructors explain with example.

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

N.S.PATEL - 7600031265 N.K.PATEL - 9429235711


PRAYOSHA ENGINEERING CLASSES Advanced Object Oriented Programming (CE SEM 4)
----------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------
 Types of Java constructors

 There are three types of constructors in Java:

 Default constructor (no-arg constructor)


 Parameterized constructor
 Copy constructor

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

class Bike
{
Bike() //creating a default constructor
{
System.out.println("Bike is created");
}
//main method
public static void main(String args[])
{
//calling a default constructor
Bike b=new Bike();
}
}

 Parameterized Constructor: A constructor which has a specific number of parameters is called a


parameterized constructor.

class Student
{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n)
{
id = i;
name = n;
}
//method to display the values
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
//creating objects and passing values
Student s1 = new Student(111,"Prayosha");
Student s2 = new Student(222,"Onewayakshar");

N.S.PATEL - 7600031265 N.K.PATEL - 9429235711


PRAYOSHA ENGINEERING CLASSES Advanced Object Oriented Programming (CE SEM 4)
----------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------
//calling method to display the values of object
s1.display();
s2.display();
}
}

 Copy Constructor: 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
 By clone() method of Object class

//Java program to initialize the values from one object to another object.

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

public static void main(String args[])


{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(s1);
s1.display();
s2.display();
}
}

N.S.PATEL - 7600031265 N.K.PATEL - 9429235711


PRAYOSHA ENGINEERING CLASSES Advanced Object Oriented Programming (CE SEM 4)
----------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------

Q.8 – Explain Method Overloading .?

 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.
 Suppose you have to perform addition of the given numbers but there can be any number of arguments, if
you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then
it may be difficult for you as well as other programmers to understand the behavior of the method
because its name differs.
 Example :
class Adder
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}

Q.9 – Explain Constructor Overloading.?

 In Java, a constructor is just like a method but without return type.

 It can also be overloaded like Java methods.

 Constructor overloading in Java is a technique of having more than one constructor with different

parameter lists.

 They are arranged in a way that each constructor performs a different task.

 They are differentiated by the compiler by the number of parameters in the list and their types.

N.S.PATEL - 7600031265 N.K.PATEL - 9429235711


PRAYOSHA ENGINEERING CLASSES Advanced Object Oriented Programming (CE SEM 4)
----------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------
 Example :
class Student
{
int id;
String name;
int age;
//creating two arg constructor
Student(int i,String n)
{
id = i;
name = n;
}
//creating three arg constructor
Student(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}

public static void main(String args[])


{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan",25);
s1.display();
s2.display();
}
}

Q.10 – Explain Wrapper Classes.?

 The wrapper class in Java provides the mechanism to convert primitive into object and object into
primitive.
 Java is an object-oriented programming language, so we need to deal with objects many times like in
Collections, Serialization, Synchronization, etc. Let us see the different scenarios, where we need to use
the wrapper classes.
 Change the value in Method: Java supports only call by value. So, if we pass a primitive value, it will not
change the original value. But, if we convert the primitive value in an object, it will change the original
value.
 Serialization: We need to convert the objects into streams to perform the serialization. If we have a
primitive value, we can convert it in objects through the wrapper classes.
 Synchronization: Java synchronization works with objects in Multithreading.
 java.util package: The java.util package provides the utility classes to deal with objects.

N.S.PATEL - 7600031265 N.K.PATEL - 9429235711


PRAYOSHA ENGINEERING CLASSES Advanced Object Oriented Programming (CE SEM 4)
----------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------
 Collection Framework: Java collection framework works with objects only. All classes of the collection
framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque,
etc.) deal with objects only.
 ArrayList<int> myNumbers = new ArrayList<int>(); // Invalid

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

 The eight classes of the java.lang package are known as wrapper classes in Java. The list of eight
wrapper classes are given below:

import java.util.ArrayList;

public class Main


{
public static void main(String[] args)
{
ArrayList<Integer> myNumbers = new ArrayList<Integer>();
myNumbers.add(10);
myNumbers.add(15);
myNumbers.add(20);
myNumbers.add(25);
for (int i : myNumbers)
{
System.out.println(i);
}
}
}

N.S.PATEL - 7600031265 N.K.PATEL - 9429235711


PRAYOSHA ENGINEERING CLASSES Advanced Object Oriented Programming (CE SEM 4)
----------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------

Q.11 – Explain following methods: charAt(), contains(), format(), length()

CharAt() :
*********************************************************
public class Main
{
public static void main(String[] args)
{
String myStr = "Hello";
char result = myStr.charAt(0);
System.out.println(result);
}
}
Output : H

contains():
****************************************************
public class Main {
public static void main(String[] args)
{
String myStr = "Hello";
System.out.println(myStr.contains("Hel"));
System.out.println(myStr.contains("e"));
System.out.println(myStr.contains("Hi"));
}
}
Output:
true
true
false

format() :
****************************************************
class Main
{
public static void main(String[] args)
{
String str = "Java";
// format string
String formatStr = String.format("Language: %s", str);
System.out.println(formatStr);

N.S.PATEL - 7600031265 N.K.PATEL - 9429235711


PRAYOSHA ENGINEERING CLASSES Advanced Object Oriented Programming (CE SEM 4)
----------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------
}
}

Output: Language: Java

length() :
**************************************************************
public class Main
{
public static void main(String[] args)
{
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(txt.length());
}
}
Output : 26

Q.12 – Explain Scanner Class with example.?

 The Scanner class is used to get user input, and it is found in the java.util package.
 To use the Scanner class, create an object of the class and use any of the available methods found in
the Scanner class documentation. In our example, we will use the nextLine() method, which is used to
read Strings:
 Example:
import java.util.Scanner; // import the Scanner class

class Main
{
public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);
String userName;

// Enter username and press Enter


System.out.println("Enter username");
userName = myObj.nextLine();

System.out.println("Username is: " + userName);


}
}
Q.13 – Explain Command Line Arguments with example.?

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

N.S.PATEL - 7600031265 N.K.PATEL - 9429235711


PRAYOSHA ENGINEERING CLASSES Advanced Object Oriented Programming (CE SEM 4)
----------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------

 So, it provides a convenient way to check the behavior of the program for the different values.

 You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.

 example of command-line argument in java

class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}

***************************
compile by > javac CommandLineExample.java

run by > java CommandLineExample Nirmal

Output: Your first argument is: Nirmal

 command-line argument that prints all the values


class A
{
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
**********************************************************
compile by > javac A.java
run by > java A Nirmal Patel 1 3 abc

Output:
Nirmal
Patel
1
3
abc

N.S.PATEL - 7600031265 N.K.PATEL - 9429235711

You might also like