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

short ans oop

The document provides an overview of Java programming concepts, including type casting, operators, control statements, variable scope, constructors, garbage collection, and exception handling. It explains various Java features such as inheritance, polymorphism, interfaces, and packages, along with examples for clarity. Additionally, it discusses the significance of keywords like 'super' and 'this', and outlines the thread life cycle and exception handling mechanisms.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

short ans oop

The document provides an overview of Java programming concepts, including type casting, operators, control statements, variable scope, constructors, garbage collection, and exception handling. It explains various Java features such as inheritance, polymorphism, interfaces, and packages, along with examples for clarity. Additionally, it discusses the significance of keywords like 'super' and 'this', and outlines the thread life cycle and exception handling mechanisms.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

objects.

Example:
3. What is type casting
java
Definition: Converting one data type into Copy code
class Demo {
another. static int z = 30; // Static variable
Types: }

1. Implicit Casting (Widening): Automatic


conversion of a smaller data type to a 4. What are the different types of
larger type. operators in Java?
largerType = smallerType;
Arithmetic Operators: Perform basic math
java operations (+, -, *, /, %). Example:
Copy code Relational Operators: Compare two values
int num = 10; (==,
double result = num; // int to double Logical Operators: Combine multiple
conditions
2. Explicit Casting (Narrowing): Manual Assignment Operators: Assign values to
conversion of a larger data type to a variables
smaller type. 7. Explain control statements in Java.
smallerType = (smallerType) largerType;
5. What are the types of loops available in
java
Java?
Copy code
double num = 10.5; for Loop: Repeats code for a fixed number of
int result = (int) num; // double to int
iterations. Example:
4) State & explain scope of variable with java
an example. Copy code
for (int i = 0; i < 5; i++) System.out.println(i);
Definition: The portion of the program where a while Loop: Executes as long as the condition
variable is accessible. is true. Example:
java
Copy code
Types of Scope: int i = 0;
while (i < 5) {
1. Local Scope: Variable declared inside a System.out.println(i);
method, accessible only within the i++;
method. }
Example: do-while Loop: Executes
at least once before
checking the condition. Example:
java java
Copy code Copy code
void method() { int i = 0;
int x = 10; // Local variable do {
System.out.println(x); System.out.println(i);
} i++;
} while (i < 5);

2. Instance Scope: Variable declared inside


a class but outside any method, accessible 9. Explain any two relational operators in
via objects. Java with example.
Example:
1. Equality (==): Checks if two values are
java
Copy code
equal. Example:
class Demo {
int y = 20; // Instance variable java
} Copy code
int x = 10, y = 20;
System.out.println(x == y); // false
3. Class/Static Scope: Variable declared as
static inside a class, shared among all
2. Greater Than (>): Checks if the left
operand is greater. Example:
java Syntax:
Copy code
System.out.println(x > y); // false java
Copy code
dataType[] arrayName = new dataType[size];
arrayName[index] = value; // Initialization

Example:
10. Why java became platform independent
language? Explain. java
Copy code
Bytecode: Java programs compile into int[] arr = {1, 2, 3, 4, 5}; // Declaration and initialization
System.out.println(arr[0]); // Output: 1
intermediate bytecode.
JVM: Each platform has its own JVM that
interprets the bytecode into machine code. 17. What is the difference between a single-
Example: Write on Windows, run on Linux without dimensional array and a multi-dimensional
changes. array?

13. What is the difference between == 18. Enlist types of constructor. Explain any
operator and .equals () method in Java? two with example.
14. Define a class and object. Write syntax to Default Constructor: No parameters.
create class and object with an Example. Example:
java
Copy code
• Class: Blueprint for objects; defines class Demo {
properties and behavior. Demo() {
• Object: Instance of a class. System.out.println("Default Constructor");
}
class ClassName { }
// Fields Parameterized Constructor: Accepts
// Methods parameters.
} Example:
java
Copy code
ClassName obj = new ClassName(); // Object creation
class Demo {
class Car {
Demo(String msg) {
String model;
System.out.println("Message: " + msg);
int year;
}
}
void display() {
System.out.println("Model: " + model + ", Year: " + 20. State three uses of final keyword.
year);
} Final Variable: Prevents modification of a
} variable.
java
public class Main { Copy code
public static void main(String[] args) { final int x = 10;
Car car = new Car(); // Create object // x = 20; // Error
car.model = "Tesla"; Final Method: Prevents method overriding.
car.year = 2022; java
car.display(); Copy code
} final void display() { }
} Final Class: Prevents inheritance.
java
Copy code
15. What is the difference between a default final class A { }
constructor and a parameterized constructor?

16. How do you declare and initialize an array


in Java?
21. What is garbage collection in Java?
Explain finalize method in Java.
24. Explain how interface is used to achieve
Garbage Collection: An automated process multiple Inheritances in Java.
in Java to free memory by destroying objects that
are no longer referenced. Java doesn’t support multiple inheritance through
Purpose: Prevents memory leaks and classes but allows it using interfaces.
optimizes application performance.
finalize() Method: A method in the Object class, Example:
called by the garbage collector before an object is
destroyed. java
Copy code
22. Describe access control specifiers with interface A {
void methodA();
example. }

interface B {
void methodB();
}

class C implements A, B {
public void methodA() {
System.out.println("From Interface A");
}
public void methodB() {
System.out.println("From Interface B");
}
23. Define a class and object. Write syntax to }
create class and object with an public class Main {
example.Which are public static void main(String[] args) {
C obj = new C();
the restrictions present for static declared obj.methodA();
methods? obj.methodB();
}
}
• Class: Blueprint for objects, containing
fields and methods.
• Object: Instance of a class. 25. What is abstraction in Java? How do you
implement it?
Syntax:
• Definition: Hiding implementation details
java
and showing only essential features.
Copy code
class ClassName { • Implementation: Achieved using abstract
int x; // Field classes or interfaces.
void method() { } // Method
} Example (Abstract Class):
ClassName obj = new ClassName(); // Object
java
Restrictions of static Methods: Copy code
abstract class Shape {
1. Cannot use non-static fields or methods abstract void draw();
}
directly.
2. Cannot use this or super. class Circle extends Shape {
void draw() {
Example: System.out.println("Drawing Circle");
}
java }
Copy code
class Demo {
static void display() {
System.out.println("Static Method");
// Cannot access non-static methods or variables 26. What is the significance of the ‘super’
} keyword in Java?
}
• Refers to the parent class’s members. Example:

1. Access the parent class’s field: java


Copy code
java // File: package1/MyClass.java
Copy code package package1;
super.fieldName;
public class MyClass {
public void display() {
2. Call the parent class’s method: System.out.println("Hello from Package1");
}
java }
Copy code
super.methodName(); // File: package2/Main.java
package package2;
3. Invoke the parent class constructor:
import package1.MyClass;
java public class Main {
Copy code public static void main(String[] args) {
super(arguments); MyClass obj = new MyClass();
obj.display();
}
27. Explain the concept of constructors in }
Java. Discuss the different types of
constructors with
30. How to add new class to a package?
examples. Explain with an example.
Constructor: Special method to initialize
• Steps:
objects when a class is instantiated.
1. Create the package.
Types:
2. Add the new class using the package
keyword.
1. Default Constructor: No parameters.
2. Parameterized Constructor: Accepts
Example:
parameters.
3. Copy Constructor: Creates a copy of java
another object (achieved manually). Copy code
// Create Package: mypackage/MyClass.java
package mypackage;

28. What is constructor overloading in Java? public class MyClass {


public void show() {
Definition: Defining multiple constructors with System.out.println("New Class in Package");
the same name but different parameter lists }
}
within a class.
Purpose: To initialize an object in different // Access the Class: Main.java
ways. import mypackage.MyClass;

29. Which are the ways to access package public class Main {
from another package? Explain with example. public static void main(String[] args) {
MyClass obj = new MyClass();
obj.show();
1. mport the Package: }
}
java
Copy code
import packageName.ClassName;

2. Use Fully Qualified Name:

java
Copy code 31. What is single level inheritance? Explain
packageName.ClassName obj = new
packageName.ClassName(); with suitable example.
• Definition: A child class inherits from a
single parent class.
• Purpose: Promotes code reuse. 34. Explain inheritance and polymorphism
features of Java.
Example:
Inheritance: A child class inherits properties
java and methods of a parent class. Example:
Copy code
class Parent { java
void display() { Copy code
System.out.println("Parent Class"); class Parent {
} void show() {
} System.out.println("Parent");
}
class Child extends Parent { }
void show() {
System.out.println("Child Class"); class Child extends Parent { }
}
}
Polymorphism: The ability to perform a single
public class Main { action in multiple ways. Example:
public static void main(String[] args) {
Child obj = new Child(); java
obj.display(); // Parent Class Copy code
obj.show(); // Child Class class Demo {
} void show() {
} System.out.println("Base Class");
}
}
32. What is package? State how to create and
class Derived extends Demo {
access user defined package in Java.
void show() {
System.out.println("Derived Class");
• Package: A namespace for organizing }
classes and interfaces. }
• Creation: Use the package keyword.
• Access: Use import or fully qualified name.
35. What is the multiple inheritance? Write a
java program to implement multiple
inheritance.
33. What is meant by interface? State its need
and write syntax and features of interface. • Definition: A class inherits from multiple
parent classes/interfaces.
• Definition: A contract that defines a set of • Java: Achieves multiple inheritance using
methods that implementing classes must interfaces.
provide.
• Need: Example:
o Supports multiple inheritance.
o Achieves abstraction. java
Copy code
interface A {
Syntax: void methodA();
}
java
Copy code interface B {
interface InterfaceName { void methodB();
void method(); }
}
class C implements A, B {
Features: public void methodA() {
System.out.println("From Interface A");
}
1. Methods are public and abstract by default. public void methodB() {
2. Can include static and default methods. System.out.println("From Interface B");
3. Variables are public, static, and final. }
}
obj.show(); // Overridden Method
}
36. What is package? How do we create it? }
Give the example to create and to access 38. What is importance of super and this
package. keyword in inheritance ? Illustrate with
suitable
Definition: A collection of related classes and Example
interfaces.
• super: Refers to the parent class. Used to
Example:
call parent methods, variables, or
java
constructors.
Copy code • this: Refers to the current object. Used to
// File: mypackage/Hello.java call current class methods, variables, or
package mypackage; constructors.
public class Hello {
public void greet() {
Example:
System.out.println("Hello from Package");
} java
} Copy code
class Parent {
// Access: void display() { System.out.println("Parent Method"); }
import mypackage.Hello; }
class Child extends Parent {
public class Main { void display() { System.out.println("Child Method"); }
public static void main(String[] args) { void show() {
Hello obj = new Hello(); this.display(); // Current class
obj.greet(); super.display(); // Parent class
} }
} }

37. Explain method overriding with suitable 39. What is thread ? Draw thread life cycle
example diagram in Java.
Thread: A small part of a process that runs
• Definition: A subclass provides a specific independently.
implementation of a method already Thread Life Cycle:
defined in the parent class.
• Rules: 1. New → start()
o Method must have the same name,
2. Runnable → Waiting for CPU.
return type, and parameters. 3. Running → Executing.
o Subclass method cannot have
4. Blocked/Waiting → Temporarily paused.
stricter access. 5. Terminated → Finished execution.
Example: 40. What is thread priority ? Write default
java
priority values and methods to change
Copy code them.What is
class Parent {
void show() { exception ?Thread Priority: Sets execution
System.out.println("Parent Method"); importance.
}
}
o Default Priority: 5
class Child extends Parent { o Range: 1 (Low) to 10
@Override (High).Methods:
void show() {
System.out.println("Overridden Method"); • setPriority(int)
} • getPriority()
}

public class Main { Exception: Error disrupting program flow.


public static void main(String[] args) {
Parent obj = new Child();
41. What is the use of try catch and finally 44. Explain following clause w.r.t. exception
statement give example. handling :
(i) try (ii) catch (iii) throw (iv) finally
• try: Contains risky code.
• catch: Handles exceptions. try:
• finally: Runs after try or catch.
• Contains code that might throw an
Example: exception.
• Syntax: try { // code }
java
Copy code
try { catch:
int a = 5 / 0;
} catch (Exception e) { • Catches and handles exceptions thrown in
System.out.println("Error: " + e); the try block.
} finally {
• Syntax: catch (ExceptionType e) { // code }
System.out.println("Always runs");
}
throw:

42. What is Exception Handling in Java? • Used to explicitly throw an exception in


Discuss the use of try, catch, finally, throw, code.
and throws • Syntax: throw new Exception("Message");
in exception handling, providing code finally:
examples for each. Define throws &amp;
finally statements • Executes code regardless of whether an
exception was thrown or not.
with its syntax and example.
• Syntax: finally { // code }
• try: Test code for exceptions.
• catch: Handle exceptions.
• finally: Runs always. 45. Explain following terms :
• throw: Used to throw an exception.
• throws: Declares possible exceptions. (i) Thread Priority (ii) Types of Exception

(i) Thread Priority:

43. With syntax and example explain try • Determines the importance of a thread.
&amp; catch statement. Higher priority threads are executed before
lower priority ones.
Syntax: • Priority range: 1 (lowest) to 10 (highest).
Default priority is 5.
java
Copy code (ii) Types of Exception:
try {
// Risky code
} catch (ExceptionType e) { • Checked Exception: Exceptions that are
// Handle exception checked at compile-time (e.g., IOException,
} SQLException).
• Unchecked Exception: Exceptions that
Example: are checked at runtime (e.g.,
NullPointerException, ArithmeticException).
java
Copy code
try {
int[] arr = new int[5];
arr[10] = 50;
} catch (Exception e) {
System.out.println("Error: " + e);
}
46. Write any four methods of file class with
their use.
exists(): Reader:

• Checks if a file or directory exists. • Handles character data.


• Syntax: file.exists() • Suitable for reading text files.
• Example: FileReader.
length():

• Returns the size of the file in bytes.


• Syntax: file.length() 49. Explain fileinputstream class to read the
content of a file.
delete():
• FileInputStream is used for reading byte-
• Deletes the file or directory. oriented data from files. It is useful when
• Syntax: file.delete() working with binary data.
• Example:
isDirectory():
java
Copy code
• Checks if the file is a directory. import java.io.FileInputStream;
• Syntax: file.isDirectory() import java.io.IOException;

public class Main {


public static void main(String[] args) {
47. Write any four methods of File Input try {
FileInputStream fis = new FileInputStream("file.txt");
stream class give their syntax. int data;
while ((data = fis.read()) != -1) {
read():
System.out.print((char) data);
}
• Reads a single byte of data. fis.close();
• Syntax: fileInputStream.read() } catch (IOException e) {
System.out.println("Error: " + e);
}
read(byte[] b): }
}
• Reads data into an array of bytes.
• Syntax: fileInputStream.read(b)
50. Write any two methods of file and file input
available(): stream class each.

• Returns the number of bytes that can be File Class:


read without blocking.
• Syntax: fileInputStream.available() 1. createNewFile(): Creates a new empty file if
it doesn't exist.
close(): Syntax: file.createNewFile()
2. getName(): Returns the name of the file.
• Closes the stream and releases system Syntax: file.getName()
resources.
• Syntax: fileInputStream.close() FileInputStream Class:

1. skip(long n): Skips over n bytes of data.


Syntax: fileInputStream.skip(n)
48. Differentiate between Input stream class 2. mark(int readlimit): Marks the current
and Reader class position in the input stream.
Syntax: fileInputStream.mark(readlimit)
InputStream:

• Handles byte data.


• Suitable for reading binary files like 51. Explain Stream Classes
images, videos, etc.
• Example: FileInputStream.
• Stream Classes in Java are used to read }54. What is the difference between checked
and write data. Streams can be and unchecked exceptions?
categorized into two types:
o Byte Streams: Handle I/O of raw • Checked Exceptions:
binary data (e.g., FileInputStream, o Exceptions that are checked at
FileOutputStream). compile-time.
o Character Streams: Handle I/O of o The programmer is forced to handle
character data (e.g., FileReader, or declare them using try-catch or
FileWriter). throws.
o Examples: IOException, SQLException.
Streams support reading, writing, and other • Unchecked Exceptions:
operations like buffering, and can be chained for o Exceptions that occur during
efficient processing. runtime.
o The programmer is not required to
handle them, but they can be
caught if needed.
52. Explain OutputStreamClass.
o Examples: NullPointerException,
OutputStream is an abstract class that is the ArrayIndexOutOfBoundsException.
superclass of all classes representing an output
stream of bytes. Key Difference:

• Write operations: Allows writing bytes to a • Checked: Must be handled or declared.


destination (file, memory, network). • Unchecked: Not mandatory to handle.
• Common subclasses:
o FileOutputStream: Writes data to a
file.
o BufferedOutputStream: Provides
buffering for faster I/O operations.
o ObjectOutputStream: Writes objects
to an output stream

53. Write program to handle primitive data


types.
public class PrimitiveDataTypes {
public static void main(String[] args) {
// Declare and initialize primitive data types
int num = 5;
double price = 19.99;
char grade = 'A';
boolean isActive = true;

// Display values
System.out.println("Integer: " + num);
System.out.println("Double: " + price);
System.out.println("Character: " + grade);
System.out.println("Boolean: " + isActive);
}

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