0% found this document useful (0 votes)
176 views

Derived Syntactical Constructs in Java: (Type Here)

The document discusses various derived syntactical constructs in Java such as constructors, parameterized constructors, command line arguments, garbage collection and finalize method. It provides examples of default constructor, parameterized constructor and copy constructor. It explains the use of parameterized constructor with an example. Command line arguments are explained along with programs to accept numbers from command line arguments and perform operations. Garbage collection and finalize method are described. Access control parameters and example of default access modifier are also summarized.

Uploaded by

Amaan Shaikh
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)
176 views

Derived Syntactical Constructs in Java: (Type Here)

The document discusses various derived syntactical constructs in Java such as constructors, parameterized constructors, command line arguments, garbage collection and finalize method. It provides examples of default constructor, parameterized constructor and copy constructor. It explains the use of parameterized constructor with an example. Command line arguments are explained along with programs to accept numbers from command line arguments and perform operations. Garbage collection and finalize method are described. Access control parameters and example of default access modifier are also summarized.

Uploaded by

Amaan Shaikh
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/ 25

[Type here]

DERIVED SYNTACTICAL Java Programming

CONSTRUCTS IN JAVA
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

1) What are the types of constructors? (Winter 15, summer 16,


summer 18) 4 marks
Types of constructors in java:
a) Default constructor (no-arg constructor)
b) Parameterized constructor
c) Copy constructor

1. Default constructor: A constructor is called "Default


Constructor" when it doesn't have any parameter.

Syntax of default constructor:


<class_name>()
{}

Example:
class Bike1{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}

2. Parameterized constructor: A constructor which has a


specific number of parameters is called parameterized
constructor.
Parameterized constructor is used to provide different values
to the distinct objects

Example:
class Student4{
int id;
String name;

Student4(int i,String n){


id = i;
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

name = n;
}
void display()
{ System.out.println(id+" "+name);}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}

3. Copy constructor: A copy constructor is used for copying


the values of one object to another object.

Example:
class Student6{
int id;
String name;
Student6(int i,String n)
{
id = i;
name = n;
}
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1); //copy constructor called
s1.display();
s2.display();
}
}
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

2) What is constructor? Describe the use of parameterized


constructor with suitable example. (Winter 15) 4 marks

Constructor:
a) A constructor is a special method which initializes an object
immediately upon creation
b) It has the same name as class name in which it resides and
it is syntactically similar to any method.
c) When a constructor is not defined, java executes a default
constructor which initializes all numeric members to zero and
other types to null or spaces.
d) Once defined, constructor is automatically called immediately
after the object is created before new operator completes.
e) Constructors do not have return value, but they don‟t require
“void” as implicit data type as data type of class constructor
is the class type itself.

Parameterized constructor:
It is used to pass the values while creating the objects

Example:
class Rect
{
int length, breadth;
Rect(int l, int b) // parameterized constructor
{
length=l;
breadth=b;
}
public static void main(String args[])
{
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

Rect r = new Rect(4,5); // constructor with parameters


Rect r1 = new Rect(6,7);
System.out.println(“Area : ” +(r.length*r.breadth));
System.out.println(“Area : ” +(r1.length*r1.breadth));
}
}

3) Define constructor. Explain parameterized constructor with


example. (Summer 16) 4 marks
Constructor:
a) A constructor is a special member which initializes an object
immediately upon creation.
b) It has the same name as class name in which it resides and
it is syntactically similar to any method.
c) When a constructor is not defined, java executes a default
constructor which initializes all numeric members to zero and
other types to null or spaces.
d) Once defined, constructor is automatically called immediately
after the object is created before new operator completes.
Parameterized constructor: When constructor method is defined
with parameters inside it, different value sets can be provided to
different constructor with the same name

Example:
ClassRect
{
int length, breadth;
Rect(int l, int b) // parameterized constructor
{
length=l;
breadth=b;
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

}
public static void main(String args[])
{
Rect r = new Rect(4,5); // constructor with parameters
Rect r1 = new Rect(6,7);
System.out.println(“Area : ” +(r.length*r.breadth)); // o/p Area : 20
System.out.println(“Area : ” +(r1.length*r1.breadth)); // o/p Area :
42
}
}

4) Explain command line arguments.


a) Java command-line argument is an argument i.e. passed at
the time of running the Java program.
b) In the command line, the arguments passed from the
console can be received in the java program and they can be
used as input.
c) The users can pass the arguments during the execution
bypassing the command-line arguments inside the main()
method.
d) We need to pass the arguments as space-separated values.
e) When command-line arguments are supplied to JVM, JVM
wraps these and supplies them to args[].
f) Internally, JVM wraps up these command-line arguments
into the args[ ] array that we pass into the main() function.
g) JVM stores the first command-line argument at args[0], the
second at args[1], the third at args[2], and so on.
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

5) Write a program to accept a number as command line


argument and print the number is even or odd.
(Summer 15) 4 marks
public class oe
{
public static void main(String key[])
{
int x=Integer.parseInt(key[0]);
if (x%2 ==0)
{
System.out.println("Even Number");
}
else
{
System.out.println("Odd Number");
}
}
}

6) Write a program to accept two numbers as command line


arguments and print the addition of those numbers.
(Summer 17) 4 marks
class addition
{
public static void main(String args[])
{
int a,b;
a= Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
int c= a+b;
System.out.println("Addition= "+c);
}
}
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

7) Write a program to accept number from command line and


print square root of the number. (Winter 17) 4 marks
class test1
{
public static void main(String args[])
{
intnum;
num= Integer.parseInt(args[0]);
doublesq=Math.sqrt(num);
System.out.println("square root of "+ num +" is +sq);
}}

8) How garbage collection is done in Java? Which methods are


used for it?. (Winter 16) 4 marks
a) Garbage collection is a process in which the memory
allocated to objects, which are no longer in use can be freed
for further use.
b) Garbage collector runs either synchronously when system is
out of memory or asynchronously when system is idle.
c) In Java it is performed automatically. So it provides better
memory management.

Method used for Garbage Collection:


The java.lang.Object.finalize() is called by garbage collector on an
object when garbage collection determines that there are no more
reference to the object.
A subclass override the finalize method to dispose of system
resources or to perform other cleanup.

General Form :
protected void finalize()
{ // finalization code here
}
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

9) What is garbage collection in Java? Explain finalize method in


Java. (Summer 17) 6 marks
Garbage collection:
a) Garbage collection is a process in which the memory
allocated to objects, which are no longer in use can be freed
for further use.
b) Garbage collector runs either synchronously when system is
out of memory or asynchronously when system is idle.
c) In Java it is performed automatically. So it provides better
memory management
d) A garbage collector can be invoked explicitly by writing
statement
System.gc(); //will call garbage collector.
Example:
public class A
{
int p;
A()
{
p = 0;
}
}
class Test
{
public static void main(String args[])
{
A a1= new A();
A a2= new A();
a1=a2; // it deallocates the memory of object a1
}
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

Method used for Garbage Collection finalize:


a) The java.lang.Object.finalize() is called by garbage collector
on an object when garbage collection determines that there
are no more reference to the object.
b) A subclass override the finalize method to dispose of system
resources or to perform other cleanup.
c) Inside the finalize() method, the actions that are to be
performed before an object is to be destroyed, can be
defined. Before an object is freed, the java run-time calls the
finalize() method on the object.

General Form:
protected void finalize()
{ // finalization code here
}

10) What are the access control parameters? Explain the


concept with suitable example. (Winter 16) 6 marks
Java provides a number of access modifiers to set access levels
for classes, variables, methods and constructors.
a) Default Access Modifier - No keyword:
A variable or method declared without any access control
modifier is available to any other class in the same package.
Visible to all class in its package
E.g:
Variables and methods can be declared without any modifiers,
as in the following Examples:
String version = "1.5.1";
boolean processOrder()
{
return true;
}
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

b) Private Access Modifier - private:


Methods, Variables and Constructors that are declared private
can only be accessed within the declared class itself.
Private access modifier is the most restrictive access level.
Class and interfaces cannot be private.
Using the private modifier is the main way that an object
encapsulates itself and hide data from the outside world.
Examples:
private String format;
private void get() { }

c) Public Access Modifier - public:


A class, method, constructor, interface etc declared public can
be accessed from any other class. Therefore fields, methods,
blocks declared inside a public class can be accessed from any
class belonging to the Java Universe. However, if the public
class we are trying to access is in a different package, then the
public class still need to be imported. Because of class
inheritance, all public methods and variables of a class are
inherited by its subclasses.
Examples:
public double pi = 3.14;
public static void main(String[] arguments)
{
// ...
}

d) Protected Access Modifier - protected:


Variables, methods and constructors which are declared
protected in a super class can be accessed only by the
subclasses in other package or any class within the package of
the protected members' class.
The protected access modifier cannot be applied to class and
interfaces. Methods, fields can be declared protected, however
methods and fields in a interface cannot be declared protected.
Protected access gives the subclass a chance to use the helper
method or variable, while preventing a nonrelated class from
trying to use it.
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

E.g
The following parent class uses protected access control, to
allow its child class override
protected void show( )
{}

e) private protected:
Variables, methods which are declared protected in a super
class can be accessed only by the subclasses in same
package. It means visible to class and its subclasses.
Example:
private protected void show( )
{}

11) Describe access control specifiers with example.


(Winter 17) 4 marks
There are 4 types of java access modifiers:
1. private
2. default
3. protected
4. public

a) private access modifier:


The private access modifier is accessible only within
class.
Example:
class test
{
private int data=40;
private void show()
{
System.out.println("Hello java");
}
}
public class test1{
public static void main(String args[]){
testobj=new test();
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

System.out.println(obj.data);//Compile Time Error


obj.show();//Compile Time Error
}
}
In this example, we have created two classes test and
test1. test class contains private data member and private
method. We are accessing these private members from
outside the class, so there is compile time error

b) default access specifier:


If you don’t specify any access control specifier, it is
default, i.e. it becomes implicit public and it is accessible
within the program anywhere.
Example:
class test
{
int data=40; //default access
void show() // default access
{
System.out.println("Hello java");
}
}
public class test1{
public static void main(String args[]){
testobj=new test();
System.out.println(obj.data);
obj.show();
}
}

c) protected access specifier:


The protected access specifier is accessible within
package and outside the package but through inheritance
only.
Example:
test.java
packagemypack;
public class test
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

{
protected void show()
{
System.out.println("Hello java");
}
}
test1.java
importmypack.test;
class test1 extends test
{
public static void main(String args[])
{
test1obj=new test1();
obj.show();
}
}

d) public access specifier:


The public access specifier is accessible everywhere. It
has the widest scope among all other modifiers.
Example:
test.java
packagemypack;
public class test
{
public void show()
{
System.out.println("Hello java");
}
}
test1.java
importmypack.test;
class test1 ///inheritance not required
{
public static void main(String args[])
{
test1obj=new test1();
obj.show();
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

}
}

12) Perform following string/ string buffer operations, write


java program.
(i) Accept a password from user
(ii) Check if password is correct then display “Good”, else
display “Wrong”
(iii) Display the password in reverse order.
(iv) Append password with “welcome”
(Winter 16) 4 marks
import java.io.*;
class passwordtest
{
public static void main(String args[])
{
int i;
BufferedReaderbr = new BufferedReader(new
InputStreamReader(System.in));
String pass1="abc123";
String passwd="";
//Accepting password from user
try
{
System.out.println("enter password :");
passwd=br.readLine();
}
catch(Exception e)
{}
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

// compare two passwords


int n= passwd.compareTo(pass1);
if(n==0)
System.out.println("Good");
else
System.out.println("Wrong");
//Reversing password
StringBuffer s1= new StringBuffer(passwd);
System.out.println("Reverse of entered password :");
System.out.println(s1.reverse());
//Append welcome to password
System.out.println("Welcome appended to password :
"+s1.append("Welcome"));
}
}

13) Write a program to implement a vector class and its


method for adding and removing elements. After remove
display remaining list. (Summer 16) 8 marks
import java.io.*;
import java.lang.*;
import java.util.*;
class vector2
{
public static void main(String args[])
{
vector v=new vector();
Integer s1=new Integer(1);
Integer s2=new Integer(2);
String s3=new String("fy");
String s4=new String("sy");
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

Character s5=new Character('a');


Character s6=new Character('b');
Float s7=new Float(1.1f);
Float s8=new Float(1.2f);
v.addElement(s1);
v.addElement(s2);
v.addElement(s3);
v.addElement(s4);
v.addElement(s5);
v.addElement(s6);
v.addElement(s7);
v.addElement(s8);
System.out.println(v);
v.removeElement(s2);
v.removeElementAt(4);
System.out.println(v);
}
}

14) Write a program to add 2 integer, 2 string and 2 float


objects to a vector. Remove element specified by user and
display the list. (Summer 17) 8 marks
importjava.util.*;
import java.io.*;
class Vect {
public static void main(String a[]) {
Vector<Object> v = new Vector<Object>();
v.addElement(new Integer(5));
v.addElement(new Integer(10));
v.addElement(new String("String 1"));
v.addElement(new String("String 2"));
v.addElement(new Float(5.0));
v.addElement(new Float(6.7));
int n=0;
BufferedReader b = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Following are the elements in the vector");
for(int i = 0; i <v.size();i++) {
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

System.out.println("Element at "+i+ "is "+v.elementAt(i));


}
System.out.println("Enter the position of the element to be
removed");
try {
n = Integer.parseInt(b.readLine());
} catch(Exception e) {
System.out.println("Exception caught!"+e);
}
System.out.println("The element at "+n +"is "+v.elementAt(n)+"
will be removed");
v.removeElementAt(n);
System.out.println("The following are the elements in the
vector");
for(int i = 0; i<v.size();i++) {
System.out.println(v.elementAt(i));
}
}
}

15) What is Add element() and Element at() command in


vectors.
a) Object elementAt(int index): Returns the component at the
specified index.
b) void addElement(Object obj): Adds the specified component
to the end of this vector, increasing its size by one.

16) Define wrapper class. Give the following wrapper class


methods with syntax and use
I. To convert integer number to string
II. To convert numeric string to integer number
III. To convert object numbers to primitive numbers
using type value() method
A Wrapper class is a class whose object wraps or contains
primitive data types. When we create an object to a wrapper class,
it contains a field and in this field, we can store primitive data
types. In other words, we can wrap a primitive value into a wrapper
class object.
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

a) To convert integer number to string


Syntax: Integer. toString(Variable/Number);
Use: We can convert int to String in java using
Integer.toString() method.
b) To convert numeric string to integer number
Syntax: Integer.parseInt(str);
Use: In Java, we can use Integer.parseInt() to convert a
string to an integer.
c) To convert object numbers to primitive numbers using type
value() method
Syntax: <variable>.<datatype>Value();
Use: After conversion it stores the value in a datatype which
is primitive.

17) What is the use of wrapper classes in java? Explain float


wrapper with its methods?
Wrapper classes provide a way to use primitive data types (int,
boolean, etc..) as objects.
Float wrapper class is used to create an object version of
a primitive float value.
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

18) Describe The following string class methods with


examples:
i. length()
ii. CharAt()
iii. CompareTo()
(Winter 15) 6 marks

a) length():
Syntax: int length()
It is used to return length of given string in integer.
Eg. String str=”INDIA”
System.out.println(str);
System.out.println(str.length()); // Returns 5

b) charAt():
Syntax: char charAt(int position)
The charAt() will obtain a character from specified position.
Eg. String s=”INDIA”
System.out.println(s.charAt(2)); // returns D

c) CompareTo():
Syntax: int compareTo(Object o)
There are two variants of this method. First method
compares this String to another Object and second method
compares two strings lexicographically.
Eg. String str1 = "Strings are immutable";
String str2 = "Strings are immutable";
String str3 = "Integers are not immutable";
int result = str1.compareTo( str2 );
System.out.println(result);
result = str2.compareTo( str3 );
System.out.println(result);
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

19) Compare string class and StringBuffer class with any


four points. (Summer 15) 4 marks

20) Explain the following methods of string class with


syntax and example:
(i)substring()
(ii)replace()
(Summer 17) 4 marks

a) substring():
Syntax:
String substring(intstartindex)
startindex specifies the index at which the substring will
begin.It will returns a copy of the substring that begins at
startindex and runs to the end of the invoking string

Example :
System.out.println(("Welcome”.substring(3)); //come
System.out.println(("Welcome”.substring(3,5));//co

b) replace():
Syntax: String replace(char oldChar, char newChar)
This method returns a new string resulting from replacing all
occurrences of oldChar in this string with newChar.

Example:
String Str = new String("Welcome”);
System.out.println(Str.replace('o', 'T')); // WelcTme
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

21) Describe following string class method with example:


(i) compareTo( )
(ii) equalsIgnoreCase( )
(Winter 17) 4 marks

a) compareTo( ):
Syntax: intcompareTo(Object o)
There are two variants of this method. First method
compares this String to another Object and second method
compares two strings lexicographically.
Eg. String str1 = "Strings are immutable";
String str2 = "Strings are immutable";
String str3 = "Integers are not immutable";
int result = str1.compareTo( str2 );
System.out.println(result);
result = str2.compareTo( str3 );
System.out.println(result);

b) equalsIgnoreCase( ):
public boolean equalsIgnoreCase(String str)
This method compares the two given strings on the basis of
content of the string irrespective of case of the string.
Example:
String s1="javatpoint";
String s2="javatpoint";
String s3="JAVATPOINT";
String s4="python";
System.out.println(s1.equalsIgnoreCase(s2));//true because
content and case both are same.
System.out.println(s1.equalsIgnoreCase(s3));//true because
case is ignored.
System.out.println(s1.equalsIgnoreCase(s4));//false because
content is not same.
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

22) Write a java program to implement following functions of


string:
(1) Calculate length of string
(2) Compare between strings
(3) Concatenating strings
(Summer 18) 6 marks

class StringDemo
{
public static void main(String args[])
{
String str1="INDIA";
String str2="India";
String str3="My India";
String str4="India";
System.out.println("The length of string INDIA is "+str1.length());
//Length of string
System.out.println("Comparing String India and India
is"+str2.equals(str4));
System.out.println("Comparing String INDIA and India
is"+str1.equals(str2));
System.out.println("Comparing String INDIA and India with
equalsIgnoreCase is "+str1.equalsIgnoreCase(str2));
String str5="I Love";
System.out.println("Result of concatinating of string is
"+str5.concat(str3));
}
}
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

23) Differentiate vector and array with any 4 points.


(Summer 15) 4 marks

24) What is difference between array and vector? Explain


elementAt( ) and addElement( ) method. (Winter 15) 4 marks

a) elementAt( ): Returns the element at the location specified


by index.
Syntax: Object elementAt(int index)
Example:
Vector v = new Vector();
v.elementAt(2); //return 2nd element from vector

b) addElement ( ): Adds the specified component to the end of


this vector, increasing its size by one.
Syntax: void addElement(Object element)
Example:
DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

Vector v = new Vector();


v.addElement(new Integer(1)); //add integer object 1 to
vector

25) Explain following methods of vector class:


elementAt ()
addElement ()
removeElement ()
(Summer 15) 6 marks
a) Object elementAt(int index)
Returns the component at the specified index.

b) void addElement(Object obj)


Adds the specified component to the end of this vector,
increasing its size by one.

c) boolean removeElement(Object obj)


Removes the first (lowest-indexed) occurrence of the
argument from this vector.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy