Thanks to visit codestin.com
Credit goes to www.scribd.com

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

Practice Answers CT1 JPR

The document outlines various features of Java, including its simplicity, object-oriented nature, and portability. It explains package creation and access, differences between String and StringBuffer classes, types of errors, method overriding, and exception handling. Additionally, it covers thread creation, the lifecycle of threads, type casting, constructors, and inheritance, along with examples for each concept.

Uploaded by

prajwaljag22
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 views10 pages

Practice Answers CT1 JPR

The document outlines various features of Java, including its simplicity, object-oriented nature, and portability. It explains package creation and access, differences between String and StringBuffer classes, types of errors, method overriding, and exception handling. Additionally, it covers thread creation, the lifecycle of threads, type casting, constructors, and inheritance, along with examples for each concept.

Uploaded by

prajwaljag22
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/ 10

1) Enlist any four features of Java.

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
2) Write syntax to create a package and accessing package in java & Define the interface in java.
Syntax : to create/define package

package package_name;
e.g: package myPackage;

Syntax: to access package

Import specific class from a package:

import packagename.subpackagename.classname;

Import all classes from a package:

import packagename.subpackagename.*;

e.g:
import java.util.Vector; //access specific class Vector of util package
import java.util.*; //access all classes util package
import myPackage.*; //access user defined whole package myPackage

interface:
Interface is a kind of class containing collection of abstract methods(method without body) and final
variables.

3) Write difference between String and String Buffer Class.

String String Buffer


String class creates string of fixed StringBuffer class creates strings of
length. variable length.
We can't insert substring in middle of We can insert substring in middle of
string using string methods. string using StringBuffer methods.

Contents of object cannot be modified. Contents of object can be modified.

Methods of String class: Methods of StringBufferClass:

toLowerCase() setcharAt()
toUppercase() setLength()
equals() reverse()
equalsIgnoreCase() append()
substring() insert()
indexOf()
concat()
Syntax: Syntax:
String str=new String(); StringBuffer str=new StringBuffer();
The StringBuffer class is mutable.
The String class is immutable.
StringBuffer uses Heap memory
String class uses String constant pool.
4) Define error. List types of error.

Defination:
Error is an illegal operation performed by the user which results in the abnormal working of the program.
Types:
1. Syntax Error/compile time error
2. Run Time Error
3. Logical Error.
5) Define: i) Method Overriding ii) abstract method.
Method Overriding:
To define method in sub class with same method name, same parameter and same return type is called as
Method Overriding .i.e. sub class method is invoked and executed instead of super class method.

Abstract Method:
The method declaration ending with semicolon without method body in Base class is called as Abstract
method.

6) Describe use of throw and throws.


throw:
throw is used to throw an exception explicitly within a method.
user can throw own exception by using throw keyword.

throws:
throws is used in the method signature to declare that a method might throw one or more exceptions.
The throws keyword indicates what exception type may be thrown by a method

7) Define Thread. List two ways to create thread

Defination:

Threads are lightweight subprocesses, the smallest unit of execution with separate paths.

Two ways to create thread:


1) extending thread class itself.
2) implementing Runnable interface

8) Draw and explain life cycle of Thread.


Fig.Life Cycle of thread
Life cycle of thread includes following states :
1.Newborn
2. Runnable
3. Running
4. Blocked
5. Dead
New – A new thread begins its life cycle in the new state. It is also referred to as a born thread. This is the
state where a thread has been created, but it has not yet been started. A thread is started by calling its start()
method.
Runnable – The thread is in the runnable state after the invocation of the start() method, but the scheduler
has not selected it to be the running thread. It is in the Ready-to-run state by calling the start method and
waiting for its turn.
Running – When the thread starts executing, then the state is changed to a “running” state. The method
invoked is run|().
Blocked–This is the state when the thread is still alive but is currently not eligible to run. It is also called
suspended state. By suspend(),wait()and sleep(time in ms) method is called then the thread enters the
suspend or blocked state where it becomes idle and resides till resume(),notify(),or notyAll() are not called.
Dead – This is the state when the thread is terminated. The thread is in a running state and as soon as it is
completed its execution , it is in a “dead state”.it enters this state with the call stop(). Once a thread is in this
state, the thread cannot even run again.

Write Java Program to Define a class employee having data members as emp_id, name and salary
9) .Accept and display data for five employees.
import java.util.Scanner;
class Employee
{
int emp_id;
String name;
int salary;

// Method to set data for the Employee


void SetData() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Emp ID: ");
emp_id = scanner.nextInt();
System.out.println("Enter Emp Name: ");
name = scanner.next();
System.out.println("Enter Emp salary: ");
salary = scanner.nextInt();

// Method to display Employee data


void DisplayData() {
System.out.println("Emp ID: " + emp_id);
System.out.println("Emp Name: " + name);
System.out.println("Emp Salary: " + salary);
}

public static void main(String[] args) {


// Create an array to store 5 Employee objects
Employee[] e = new Employee[5];

// Accept and display data for five Employee


for (int i = 0; i < 5; i++) {
e[i] = new Employee(); // Create a new Employee object
System.out.println("\nEnter data for Employee " + (i + 1));
e[i].SetData(); // Set data for the Employee
}

// Display data for five Employee


System.out.println("\nDisplaying Employee data:");
for (int i = 0; i < 5; i++) {
System.out.println("\nEmployee " + (i + 1) + ":");
e[i].DisplayData(); // Display data for the Employee
}
}
}

10) Demonstrate interface in java with example.

interface Area
{
float pi=3.14f;
int radius=5;
public void calculateArea();
}
class Circle implements Area
{
public void calculateArea()
{
System.out.println("circle area="+pi*radius*radius);
}
}
public class InterfaceTest1 {

public static void main(String args[]) {


Circle c=new Circle();
c.calculateArea();

11) Describe type casting in java with example.

Type Casting: Converting one type of information into another type is called type casting.

Types of casting as follows:

Implicit casting(Widening):

Converting lower data type information into higher data type information is called as implicit casting.
It is also called as widening casting. In this type of casting memory size is goes on increasing.

Explicit Casting(Narrowing):
Converting higher data type information into lower data type information is called as explicit casting.
It is also called as narrow casting. In this type of casting memory size is goes on decreasing.
12) Explain the types of constructors in Java with suitable example.

“A constructor in Java is a special method having same name as class name that is used to initialize objects.”

types of constructors:
1. Default Constructor:
2. Parameterized Constructor:

Default Constructor:
Definition: Constructor without parameters\arguments is called as default constructor.
class Rectangle
{
int length,width;
Rectangle() //default constructor
{
length=10;
width=20;
System.out.println("length="+length+" width="+width);
}
void rectArea()
{
int area=length*width;
System.out.println("area="+area);
}
public static void main(String args[]) {

Rectangle r=new Rectangle();//calling default constructor


r.rectArea();

Parameterized Constructor:

Defination: The constructor with parameters/arguments is called as parameterized constructor.


Example:
class Rectangle1
{
int length,width;
Rectangle1(int l,int w) //parameterized constructor
{
length=l;
width=w;
System.out.println("length="+length+"\twidth= "+width);
}
void rectArea()
{
int area=length*width;
System.out.println("area="+area);
}

public static void main(String args[])


{

Rectangle1 r1=new Rectangle1(10,20);


r1.rectArea();

13) Explain single and multilevel inheritance with proper example.

“Inheritance is nothing but one class acquires the properties of another.”

Single Inheritance
“When there is only one base class and one derived class the inheritance is called as single inheritance.”
i.e. here one sub class is derived from only one base class.
Example:1 SingleInheritance.java OR Example2:single inheritance
class A package inheritance;
{
void set() class Student {
{ int roll_no;
System.out.println("this is method String name;
set() of class A"); Student(int rno,String sname)
} {
} roll_no=rno;
class B extends A name=sname;
{ }
void get() void display()
{ {
System.out.println("this is method get() of class
B"); System.out.println("roll_no="+roll_n
} o);
} System.out.println("name="+name);
public class SingleInheritance }
{ }
class Library extends Student
public static void main(String args[]) {
{ int member_no;
Library(int r,String n,int m)
B b=new B(); {
b.set(); super(r,n);
b.get(); member_no=m;
}
}
void display1()
}
{
display();

System.out.println("member_no="+member_no)
;
}
}
class SingleMain
{

public static void main(String[] args)


{
Library l=new Library(1,"gita",111);
l.display1();

Multilevel Inheritance:

“When a subclass derived from a derived class then this is called as multilevel inheritance”.

In multilevel inheritance there are super class, intermediate super classes and subclasses, in any number of levels.
Example1: Multi Level Inheritance OR Example 2:Multi level inheritance
class C class StudentClass
{ {
void set() int roll_no;
{ String name;
System.out.println("this is method set() of class C"); StudentClass(int rno,String sname)
} {
} roll_no=rno;
class D extends C name=sname;
{ }
void get() void display()
{ {
System.out.println("this is method get() of class D"); System.out.println("roll_no="+roll_no);
} System.out.println("name="+name);
} }
class E extends D }
{ class LibraryClass extends StudentClass
void check() {
{ int member_no;
System.out.println("this is method check() of class E"); LibraryClass(int r,String n,int m)
} {
} super(r,n);
member_no=m;
public class MultiLevelInheritance {
}
public static void main(String args[]) { void display1()
{
E e=new E();////using class E object can display();
call to methods of C,D and E also System.out.println("member_no="+member_no);
e.set(); }
e.get(); }
e.check(); class Result extends LibraryClass
{
} int marks;
Result(int r,String n,int m,int mk)
} {
super(r,n,m);
marks=mk;
}
void display2()
{
display1();
System.out.println("mearks="+marks);
}
}
class MultiMain
{

public static void main(String[] args)


{
Result l=new Result(1,"gita",111,90);
l.display2();

}
14) Explain How to create user defined package in java with suitable example.
To create package following steps can be taken:
1) Create a folder which is same as package name and make sure that class filee/interface files of
package are present inside the package.
2) Start the code by keyword “package”followed by package name.
Syntax: package packagename;
Example : package mypackage;
3) Add completed code required class files/interface files inside the package with appropriate access
modifiers.
MyClass.java
package myPackage;
public class MyClass
{
public void getNames(String s)
{
System.out.println(s);
}
}

4) Compile the code with “javac” to get .class file.


Example: myPackage\MyClass.java
4) To import that package inside any other program: (i.e make implementation class /class file in outside
of package and import whole package(or specific class) in that class file/implemented class files.)
Make use of import statement to include package in your program. It can be used with “*” to gain full
access to all classes within package or just by giving class name if just one class access is required.
Example : import mypackage.myclass; or import mypackage.*;

e.g: import myPackage.MyClass;//MyClass is imported from myPackage in DemoTest class

public class DemoTest


{
public static void main(String args[])
{
String s = "welcome";

MyClass o = new MyClass();

o.getNames(s);
}
}

Compile : javac DemoTest.java


Execute: java DemoTest

You might also like