Java || 3rd semester || 1st term 2019

Uncategorized

Asian

Very short answer

  1. what do you mean by instance variable?

Ans=      Instance variable in Java is used by Objects to
store their states. Variables which are defined without
the STATIC keyword and are Outside any method declaration
are Object-specific and are known as instance variables.
They are called so because their values are instance
specific and are not shared among instances.
 

  1. how can you declare array?

Ans=int[] num = newint[5];

intnum[] = {1, 2, 3, 4, 5};
 

  1. how can you achieve polymorphism in java?

Ans=       polymorphism in java is achieved by method overloading
and method overriding.

  1. difference between constructor and method.

Ans=

CONSTRUCTORS METHODS
A Constructor is a block of code that initializes a newly created object. A Method is a collection of statements which returns a value upon its execution.
A Constructor can be used to initialize an object. A Method consists of Java code to be executed.
A Constructor is invoked implicitly by the system. A Method is invoked by the programmer.
A Constructor is invoked when a object is created using the keyword new. A Method is invoked through method calls.
A Constructor doesn’t have a return type. A Method must have a return type.
A Constructor initializes a object that doesn’t exist. A Method does operations on an already created object.
  1. . define literal with example.

Ans=Literal : Any constant value which can be assigned to the variable is called as literal/constant.
// Here 100 is a constant/literal.
int x = 100;

  1. how continue is differ from break?

Ans=

break statement continue statement
It terminates the execution of the remaining iteration of the loop. It terminates only the current iteration of the loop.
break resumes the control of the program to the end of loop enclosing that ‘break’. continue resumes the control of the program to the next iteration of that loop enclosing continue.
It causes early termination of a loop. It causes early execution of the next iteration.
break stops the continuation of the loop. continuation of loop. continue do not stop the continuation of the loop, it only stops the current iteration.
the break can be used with switch, label. continue can not be executed with switch and labels.

 

  1. what is inheritance? list its types.

Ans=Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system).
Types:

  • Single inheritance.
  • Multi-level inheritance.
  • Multiple inheritance.
  • Multipath inheritance.
  • Hierarchical Inheritance.
  • Hybrid Inheritance.

 

  1. what is the range of character data type?

Ans=

Type Size in Bytes Range
float 4 bytes approximately ±3.40282347E+38F (6-7 significant decimal digits) Java implements IEEE 754 standard
double 8 bytes approximately ±1.79769313486231570E+308 (15 significant decimal digits)
char 2 byte 0 to 65,536 (unsigned)
boolean not precisely defined* true or false
  1. What is the difference between println( ) and print( ) function?

Ans=

Sr. No. Key print() println()
1 Implementation print method is implemented as it prints the text on the console and the cursor remains at the end of the text at the console. On the other hand, println method is implemented as prints the text on the console and the cursor remains at the start of the next line at the console and the next printing takes place from next line.
2 Nature The prints method simply print text on the console and does not add any new line. While println adds new line after print text on console.
3 Arguments print method works only with input parameter passed otherwise in case no argument is passed it throws syntax exception. println method works both with and without parameter and do not throw any type of exception.

 

  1. what is the purpose of object in java?

Ans= When you do work in Java, you use objects to get the job done. You create objects, modify them, move them around, change their variables, call their methods, and combine them with other objects. You develop classes, create objects out of those classes, and use them with other classes and objects
 
Short Answer question

  1. Explain three OOP principle in java.

Ans=Object-Oriented Principles
Encapsulation, inheritance, and polymorphism are usually given as the three fundamental principles of object-oriented languages (OOLs) and object-oriented methodology. These principles depend somewhat on the type of the language.
Encapsulation
There are two important aspects of encapsulation:
• Access restriction – preventing one object from accessing another’s internal state, for example.
• Namespaces/scopes – allowing the same name to have different meanings in different contexts.
Encapsulation mechanisms are essential for reducing couplings between software components. Many encapsulation mechanisms originated with non-object-oriented languages. Object-oriented languages add additional encapsulation mechanisms.
Inheritance
There are two types of inheritance in OOLs
• interface inheritance and
• implementation inheritance.
Interface inheritance is only necessary in typed OOLs. This is best understood when considering delegation-based design patterns.
Implementation inheritance mechanisms depend on the type of OOL.
• For class-based OOLs, classes inherit from classes.
• For classless OOLs, objects inherit from objects.
Polymorphism
Polymorphism refers to the ability of different objects to respond to the same message in different ways. Polymorphism is essential for modeling our world including our social environment. We frequently use the same phrases and sentences to mean different things in different contexts. Often there is an abstract sameness, but concrete differences.
For example, say the following sentence to two different architects and you will likely get two houses: “Build me a house”. Abstractly, both architects will do the same thing but many of the details will differ.
In early structured design methodology there were three principle types of control or data structure elements: sequence, alteration, and repetition. Polymorphism is often used as an alternative to alternation.
Polymorphism is implemented with a dispatch mechanism. This mechanism may only be dependent on the object that receives a message or it may also be dependent on message parameters
 

  1. What is inheritance? What are advantages of it? Explain the types of inheritance with examples.
    Ans= Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system).
    The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also.
    Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
    Advantages of inheritance:
    o Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.
    o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.
    o Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.
    o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.
    TYPES OF INHERITANCE:
    Single Inheritance Example
    class Animal{
    void eat(){System.out.println(“eating…”);}
    }
    class Dog extends Animal{
    void bark(){System.out.println(“barking…”);}
    }
    class TestInheritance{
    public static void main(String args[]){
    Dog d=new Dog();
    bark();
    d.eat();
    }}
    Output:
    barking…
    eating…
    Multilevel Inheritance Example
    File: TestInheritance2.java
    class Animal{
    void eat(){System.out.println(“eating…”);}
    }
    class Dog extends Animal{
    void bark(){System.out.println(“barking…”);}
    }
    class BabyDog extends Dog{
    void weep(){System.out.println(“weeping…”);}
    }
    class TestInheritance2{
    public static void main(String args[]){
    BabyDog d=new BabyDog();
    d.weep();
    d.bark();
    d.eat();
    }}
    Output:
    weeping…
    barking…
    eating…
    Hierarchical Inheritance Example
    File: TestInheritance3.java
    class Animal{
    void eat(){System.out.println(“eating…”);}
    }
    class Dog extends Animal{
    void bark(){System.out.println(“barking…”);}
    }
    class Cat extends Animal{
    void meow(){System.out.println(“meowing…”);}
    }
    class TestInheritance3{
    public static void main(String args[]){
    Cat c=new Cat();
    c.meow();
    c.eat();
    //c.bark();//C.T.Error
    }}
  2. Write a program to display numbers form 1 to 100 that are not divisible by 7.

Ans                                class aa11
{
public static void main(String agrs[])
{
int i;
for(i=1;i<=100;i++)
{
if(i%7!=0)
{
System.out.print(i +(” “));
}
}
}
}

  1. Write a program to create a super class ASmt have two instance variable and show() method to display data instance. Create a sub-class library that inherited form Asmt having necessary instance variable  and method. Create another sub-class lab from ASMT with necessary data instance and method. Create  object sub-class lab and retrieve all the information.

Ans                class asmt
{
int a;
int b;
void show(int x, int y)
{
a=x;
b=y;
}
public void display()
{
System.out.println(“a=”+a);
System.out.println(“b=”+b);
}
class library extends asmt
{
int c;
void show1(int m)
{
c=m;
}
public void display1()
{
 
int r=super.a+super.b+c;
System.out.println(“resuyis”+r);
}
class Lab extends asmt
{
int d;
void show2(int e)
{
d=e;
}
public void display2()
{
int s=super.a+super.b+d;
System.out.println(“results is”+s);
}
}
}
}
class demo
{
public static void main(String args[])
{
Lab ob=new Lab();
ob.show(2,3);
ob.show2(1);
ob.display();
ob.display2();
}
}

  1. Write a program to print area of a rectangle by creating a class name ‘area’ taking a values of its length and breadth as parameter of its setdata method another method having a name ‘returnarea’which return area of the rectangle.Length and breadth of rectangle are passed through method.

Ans                                class area
{
int length;
int breadth;
public void setdata(intl,int b)
{
length=l;
breadth=b;
System.out.println(“length is”+l);
System.out.println(“breadth is”+b);
}
public intreturnData()
{
return(length*breadth);
 
}
}
class demo2
{
public static void main(String args[])
{
area ob=new area();
ob.setdata(2,3);
 
System.out.println(“result is”+ob.returnData());
}
}

  1. Write a program to print the area and rectangles havimg sides(4,5) and(5,8) respectively by creating a class name name ‘Retangle’ with method named ‘Area’ which return the area and length and breadth passed as parameters to its construction.

Ans                                class rectangle
{
int length;
int breadth;
rectangle(intl,int b)
{
length=l;
breadth=b;
}
public int Area()
{
return(length*breadth);
}
void peri()
{
int p=2*(length+breadth);
System.out.println(“perimenter is:”+p);
}
}
class demo3
{
public static void main(String args[])
{
rectangle ob=new rectangle(4,5);
ob.Area();
System.out.println(“result is:”+ob.Area());
rectangle ob1=new rectangle(5,8);
ob1.peri();
}
}
 
 
Surkhet
JAVA PAPER SOLUTION:
1.why was java developed although there were a number of language already existing?
ans: java was developed although there were a number of language already exist because to make an easy to code cross platform language so that you can write an application and run it anywhere that has a valid java virtual machine.
2.What is operator? list bitwise operator.
An operator, in Java, is a special symbols performing specific operations on one, two or three operands and then returning a result. The operators are classified and listed according to precedence order. Java operators are generally used to manipulate primitive data types. The Java operators are classified into eight different categories: assignment, arithmetic, relational, logical, bitwise, compound assignment, conditional and type comparison operators.
Bitwise  operators are: bitwise AND, bitwise OR, bitwise exclusive or,etc..
 

  1. What is an object? How if created?

ans:  An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the banking system.
A class provides the blueprints for objects. So basically, an object is created from a class. In Java, the new keyword is used to create new objects.
There are three steps when creating an object from a class −

  • Declaration − A variable declaration with a variable name with an object type.
  • Instantiation − The ‘new’ keyword is used to create the object.
  • Initialization − The ‘new’ keyword is followed by a call to a constructor. This call initializes the new object.

 

  1. Define constructor. Why it is needed?

constructor  is a method in a class that is executed automatically when object are created. constructor name is same as class name and it doesnot have any return type (even void).
 

  1. what is the difference between public and private access specifier?

public: public method or variable can be accessible  from anywhere.  we can access them inside the class,outside the class and in child class.
private: method or property with private visibility can only be accessible in side a class . we cannot access private method or variable outside the class.
 
 

  1. what is the use of final keywords?

Final keyword is used to initialized the variable at the time of declaration. Final keyword makes a variable constant.
eg: final double PI=3.145
 

  1. why is java a robust language?

java is robust because of its different features that make the program complete.
for eg: java is strictly typed language it check the code both at complied time and run time and also have automatic garbage collection.
 
 
 
 
group b

  1. Write a program to find reverse of a number

import java.util.Scanner;
public class Reverse
{
public static void main(String[]args)
{
int n,rev=0,d;
Scanner obj=new Scanner(System.in);
System.out.println(“Enter a number”);
n=obj.nextInt();
while(n>0)
{
d=n%10;
rev=rev*10+d;
n=n/10;
}
System.out.println(“reserve=”+rev);
}
}
 
 
 

  1. creat a class ‘Room’ with attribute length and breadth . the class contains methods set Dim to set dimension of  the room, computer Area to compute area of the room and display Area to display area. Write a program with main methods that creates two object of Room class, computes afrea of room and display the area of smaller room.

solution..
class Room
{
int l,b,area;
void Setdata(int x , int y)
{
l=x;
b=y;
}
int Comptarea()
{
area=l*b;
return area;
}
void Display()
{
System.out.println(” area is : “+area);
}
}
public class Roommain
{
public static void main(String[]args)
{
Room r1=new Room();
r1.Setdata(2,3);
int x=r1.Comptarea();
r1.Display();
Room r2=new Room();
r2.Setdata(2,5);
int y=r2.Comptarea();
r2.Display();
System.out.println(“LARGER”);
if(x>y)
{
r1.Display();
}
else
{
r2.Display();
}
}
}
 
 
 
 
 
Janapriya Multiple Campus(mid-term)
Java Programming – I
Group “A”

  1. Write the use of ++ operator.

Ans: The  ++ operator is a unary operator that is used in variables and increments the value they hold.

  1. Differentiate between short and int data types.

Ans: short data type is 2 byte and int is 4 byte data type. Short data type stores the range from -32768 to 32767 and int data type stores the range from – 2147483648 to 2147483648.

  1. What is Boolean literal?

Ans: Boolean literal represents only two values true or false in which the value of 1 is assumed as true and 0 is assumed as false.

  1. What do you mean by short-circuit logical operators?

Ans: Short-circuit logical operators means that logical operators (&&, //) in which the first statement is followed and then   the right statement is followed. For eg:  Incase of OR(//) operator if the 1st expression is true whole statement is true by default. And incase of AND(&&) operator 1st expression is evaluated then the rest of the expression need not to be evaluated.

  1. Write down the syntax of switch…case.

Ans: syntax of switch…case:
Switch(expression)
{
case constant1:
statements;
……….
……….
Break;
case constant2:
statements;
……….
……….
Break;
 
Default:
Statements:
}
 
 

  1. “Java is a strongly typed language.” What is the meaning of this statement?

Ans:  Java is a strongly typed language this means every variable must have a declared type .
 

  1. List any two uses of this keyword.

Ans: Any two uses of this keyword are:

  1. this keyword can be used to call current class method.
  2. this keyword can be used to invoke current class constructor.

 

  1. Why java is called architecture-neutral language?

Ans: Java is called architecture-neutral language because there are no implementation dependent features. For eg: the size of primitive types is fixed.
 

  1. What is method overloading?

Ans:  If a class has multiple methods having the same name but different in arguments /parameters then it is known as method overloading.
 

  1. What is dynamic initializing?

Ans: Dynamic initialization of object refers to initializing the objects at the run time i.e. the initial value of an object is to be provided during run time. This type of initialization is required to initialize the class variables during run time.
 
 
Group “B”

  • Write a program to input any ten integer numbers in an array and calculate the sum of all even numbers.

Ans:
import java.util.Scanner;
public class Summary
{
public static void main(String args[])
{
System.out.println(“Enter any 10 integer to find sum of even numbers among those:”);
Scanner sc=new Scanner(System.in);
int a[]=new int[10];
int sum=0;
for(int i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
}
for(int i=0;i<a.length;i++)
{
if(a[i]%2==0)
{
sum=sum+a[i];
}
}
System.out.println(“The sum of even numbers is:”+sum);
}
}

  • Write a program to input any integer number and calculate its factorial values.

Ans:
import java.util.scanner;
class FactorialValue
{
public static void main (string args[])
{
int fact=1,i,n;
scanner sc=new scanner(system.in);
 
system.out.println(“Factorial value of given numbers are”);
n=sc.nextInt();
for(i=1; i<=n; i++)
{
fact=fact*1;
}
System.out.println(“Factorial of” +num +” is =” +fact);
}
}

  1. Define a class rectangle having two instance variables length and breadth; one method to initialize these data, another method to calculate area, and one more method to calculate perimeter. Now define another class to create the one object of rectangle class and to display area and perimeter of rectangle.

Ans:
class Rectangle
{
double length;
double breadth;
void setData (double l, double b)
{
length=l;
breadth=b;
}
void calculateArea()
{
double a;
a=(length*breadth);
System.out.println(“Area=” +a);
}
void calculatePerimeter()
{
double p;
p=2*(length+breadth);
System.out.println(“Perimeter=” +p);
}
}
class TestRect
{
public static void main(String args[])
{
Rectangle r=new Rectangle ();
r.setData(20,5);
r.calculateArea();
r.calculatePerimeter();
}
}

  • Write a program to count the total number of objects created of a class.

Ans:
class Test {
 
static int noOfObjects = 0;
 
// Instead of performing increment in the constructor
// instance block is preferred to make this program generic.
{
noOfObjects += 1;
}
 
// various types of constructors
// that can create objects
public Test()
{
}
public Test(int n)
{
}
public Test(String s)
{
}
 
public static void main(String args[])
{
Test t1 = new Test();
Test t2 = new Test(5);
Test t3 = new Test(“GFG”);
 
// We can also write t1.noOfObjects or
// t2.noOfObjects or t3.noOfObjects
System.out.println(Test.noOfObjects);
}
}

  • Write a simple program to demonstrate the use of garbage collection.

Ans:
class TestGarbage
{
protected void finalize ()
{
System.out.println(“object is garbage collected”);
}
public static void main(string args[])
{
TestGarbage t1 =new TestGarbage();
TestGarbage t2 =new Test Garbage();
T1=null;
T2=null;
System.gc():
}
}
 
 
 
 
Hetauda School of Management
First-Term Examination 2020
                 IT 216:java programming
Short Answer Question:

  1. What is the role of “new”?
  • “new” is a java Keyword.it create a java object and allocated memory and also used for array creation.

2.Define array with example.

  • An array is an collection of similar data items.
  • For example:

                         int a[]=new int[5]
     This creates an integer array named a of sized 5.
3.Explain keyword “this”.

  • “this” keyword in java,it can be used inside the method of constructor of a class.

4.What is Execption?

  • Exception are events that occur during the execution of program that disrupt the normal flow of instruction.

5.What is byte code verifier?

  • The byte code verifier acts as a sort of gatekeeper:it ensure that code passed to the java interpreter is in a fit state to be executed and can rum without fear of breaking the java.
  1. Define package.
  • Package is a mechanism to encapsulate a group of classes,sub packages and interfaces.

7.Define interface.

  • An interface in the Java programming language is an abstract type that is used to specify a behavior that classes must implement.
  1. What do you mean by abstract method?
  • abstract method ,similar to methods within an interface, are declare without any implementation.
  1. What do you mean by Garbage Collection?
  • Garbage Collection is the process of reclaiming all the unused memory of the object or other entities during the runtime.It is automatically executed.
  1. Explain Literals.
  • Literals are the constant value which can be given to or assigned to the variables.eg: The number 5 is a literal, and

                            Int a=5;
           Implies that the variable a is given the literal 5 to     store.
 
 
 
 
 
 
 
 
 
 
 
SDC
 
Group “A”
Brief Answer question

  1. Why java is platform independent.
  • Java is platform independent because once the code is compiled it can run in any other machine.
  1. Write a syntax of for-each version of for lop in java.
  • for(type variable name: collection)

{………………………………
…………………
}

  1. How can you prepare right shift operation in java? Write a statement to perform right shift operation.
  • We prepare right shift operation in java by dividing number by 2 and converting it in its binary equivalent.
  • Statement is: a>>2(where a is any variable whose value is 2)
  1. What is garbage collector?
  • In java, memory held by the object are deallocated automatically, this statement is known as garbage collector.
  1. What is the use of “this keyword in java?
  • The use of “this” keyword in java is to prevent from data hiding.

Short answer question

  1. Write a program to demonstrate use of break statement in java.

 
package lab1.report;
import java.util.Scanner;
class prime {
    public static void main(String args[])
    {
    Scanner sc=new Scanner(System.in);
    boolean ch=true;
    System.out.println(“Enter a number:”);
    int a=sc.nextInt();
    for(int i=2;i<a;i++)
    {
        if(a%2==0)
            ch=false;
        break;
    }
    if(ch)
        System.out.println(a+” is a prime number”);
    else
        System.out.println(a+” is a composite number”);
    }
}
 

  1. Create a class Shape with two overloading methods getArea(double length) and getArea(double l, double b) to show the area of square and rectangle.

 
 
package lab3;
class Shape
{
    int length,l,b;
    public double getArea(double length)
    {
        return length*length;   
}
 public double getArea(double l,double b)
    {
       return l*b;
    }
}
public class Demo1 {
    public static void main(String args[])
    {
        Shape s=new Shape();
        System.out.println(“the area of square is:”+s.getArea(2.0));
        System.out.println(“the area of rectangle is:”+s.getArea(2.0,3.0));
    }
}

  1. Write a program to print:

1
12
123
1234
12345
 
               
package lab1.report;
 class pattern {
public static void main(String args[])
{
    for(int i=1;i<=5;i++)
    {
        for(int j=1;j<=i;j++)
        {
            System.out.print(j);
        }
       System.out.println(“”);
    }
}
 
}
 
Â