0% found this document useful (0 votes)
2 views19 pages

Java Assignment

The document provides an overview of Java programming concepts including platform independence, bytecode, and Java architecture. It covers key topics such as data types, access specifiers, constructors, inheritance, and the significance of static and final keywords. Additionally, it includes code examples demonstrating various features and functionalities of Java.

Uploaded by

Electronic Idea
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
2 views19 pages

Java Assignment

The document provides an overview of Java programming concepts including platform independence, bytecode, and Java architecture. It covers key topics such as data types, access specifiers, constructors, inheritance, and the significance of static and final keywords. Additionally, it includes code examples demonstrating various features and functionalities of Java.

Uploaded by

Electronic Idea
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 19

1. Why Java is a platform-independent language?

Java is platform-independent because of the Java Virtual Machine


(JVM). Java programs are compiled into bytecode, which can run on any
system with a compatible JVM, irrespective of the underlying operating
system.
2. Write about Byte-Code and Unicode?
 Byte-Code: Intermediate code generated by the Java compiler that
runs on the JVM. It ensures Java's platform independence.
 Unicode: A universal character encoding standard that allows Java
to support multiple languages and symbols.
3. Explain Java Architecture with a neat diagram.
Java architecture includes:
 Java Compiler: Converts Java code to bytecode.
 Class Loader: Loads bytecode into memory.
 JVM (Java Virtual Machine): Converts bytecode into machine-
specific code.
 Runtime Environment: Provides libraries and execution
environment.
(Diagram should be included showing interaction between Java code,
Compiler, Bytecode, JVM, and OS.)
4. Write about JDK, JVM, and JRE with a diagram.
 JDK (Java Development Kit): Includes compiler, JRE, and
development tools.
 JVM (Java Virtual Machine): Converts bytecode into machine code
and executes it.
 JRE (Java Runtime Environment): Includes JVM and libraries
needed to run Java applications.
(Diagram should be included showing how JDK contains JRE, and JRE
contains JVM.)
5. What is garbage collection?
Garbage collection is the automatic process of reclaiming memory by
removing unused objects to optimize memory usage in Java.
6. Write in detail about the different Data types available in Java.
Java provides the following data types:
 Primitive Data Types: byte, short, int, long, float, double, char,
boolean.
 Non-Primitive Data Types: Arrays, Strings, Classes, Interfaces.
7. Explain different types of statements in Java?
Java has three types of statements:
 Expression Statements: Assignments, method calls, object
creation.
 Control Flow Statements: if, for, while, switch, break, continue.
 Declaration Statements: Variable and method declarations.
8. Define System Class.
System class in Java provides access to system resources like standard
input, output, and error streams. It includes methods like
System.out.println(), System.exit(), and System.gc().
9. Name the super class of Java classes.
The Object class is the superclass of all Java classes.
10. What is an Abstract class?
An abstract class is a class that cannot be instantiated and can contain
abstract methods (methods without implementation) that must be
implemented by subclasses.
11. What is Type Casting?
Type casting is converting one data type into another.
 Implicit Casting: Automatically done (e.g., int to double).
 Explicit Casting: Requires manual conversion (e.g., double to int).
12. Different access specifiers in Java.
 public: Accessible everywhere.
 private: Accessible only within the class.
 protected: Accessible in the same package and subclasses.
 default: Accessible within the same package.
13. Comparison between
Java and C++

POP and OOPs


Class and interface

14. String manipulation methods in java and there examples

15. Program to multiply two arrays.


class MultiplyArrays {
public static void main(String[] args) {
int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{5, 6}, {7, 8}};
int[][] result = new int[2][2];
for(int i=0; i<2; i++) {
for(int j=0; j<2; j++) {
result[i][j] = a[i][j] * b[i][j];
}
}
for(int[] row : result) {
for(int val : row) {
System.out.print(val + " ");
}
System.out.println();
}
}
}

16. Define Class and Object and write a class of student


Class – It is a user-defined blueprint or prototype from which objects
are created.
Object – An object in Java is a basic unit of Object-Oriented
Programming and represents real-life entities. Objects are the instances
of a class that are created to use the attributes and methods of a class.
A typical Java program creates many objects, which as you know,
interact by invoking methods.

Code:
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
Student s = new Student("Tanishq", 20);
s.display();
}a
}

17. Explain different access specifier and what is the use of default
access specifier in java
 public: Accessible everywhere.
 private: Accessible only within the class.
 protected: Accessible in the same package and subclasses.
 default: Accessible within the same package.
The default access specifier (also called package-private access) is used
when no explicit access modifier (public, private, or protected) is
specified for a class, variable, or method.
18. Define constructor and its type. Why constructor use in class and
when this constructor is invoked?
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 the
constructor, memory for the object is allocated in the memory. It is a
special type of method that is used to initialize the object. Every time
an object is created using the new() keyword, at least one constructor
is called.
Types:
 Default Constructor
 Parameterized Constructor
 Copy Constructor
Constructors are used to assign values to the class variables at the time
of object creation, either explicitly done by the programmer or by Java
itself (default constructor).
Each time an object is created using a new() keyword, at least one
constructor (it could be the default constructor) is invoked to assign
initial values to the data members of the same class.
19. Write a difference between array and vector and write a program
to sort the array element.

20. Write a program to show the significance of the static variable in


java
21. What is the significance of final in Java? Write a java code to show
the significance of final keyword.
In Java, the final keyword is used to apply restrictions on variables,
methods, and classes. Its significance depends on where it is used:

 Final Variable

public class keyword {

public static void main(String[] args) {

final int num = 100;

System.out.println(num);

num = 200; // Error: Cannot assign a value to final variable

num

 Final method

class student {
final void display() {
System.out.println("This is a student
class");
}
}
class teacher extends student {
void display() { // cannot override a final
method
System.out.println("This is a teacher
class");
}
}

 Final class

final class student {


final void display() {
System.out.println("This is a student
class");
}
}

// error: cannot inherit from final student


class teacher extends student {
public void display1() {
System.out.println("This is a teacher
class");
}
}

22. Define constructor with its different type. Why constructor are
used in a class and when these constructor are invoked?
A constructor in Java is a special method that is used to initialize
objects. It has the same name as the class and does not have a return
type (not even void). A constructor is automatically invoked when an
object of the class is created.

Types of constructor:
 Default Constructor
A constructor that has no parameters is known as default
constructor. A default constructor is invisible. And if we write a
constructor with no arguments, the compiler does not create a
default constructor.
 Parameterized Constructor
A constructor that has parameters is known as parameterized
constructor. If we want to initialize fields of the class with our own
values, then use a parameterized constructor.
 Copy Constructor
Unlike other constructors copy constructor is passed with another
object which copies the data available from the passed object to
the newly created object.
Constructor are used:
 To initialize objects when they are created.
 To avoid manually setting default values for every object.
 To enforce certain properties in an object when it is instantiated.
 To support object copying through copy constructors.
Constructor are invoked:

 Automatically when an object is created using new keyword.


 Each time an object is instantiated, a constructor runs before any
other method.
 If no constructor is defined, Java provides a default constructor
implicitly.

23. What’s the purpose of static methods and static variables? Show
with help of program.
The static keyword in Java is mainly used for memory management.
The static keyword in Java is used to share the same variable or method
of a given class. The users can apply static keywords with variables,
methods, blocks, and nested classes. The static keyword belongs to the
class rather than an instance of the class. The static keyword is used for
a constant variable or a method that is the same for every instance of a
class.
Static variables
When a variable is declared as static, then a single copy of the variable
is created and shared among all objects at the class level. Static
variables are, essentially, global variables. All instances of the class
share the same static variable.
Static methods
When a method is declared with the static keyword, it is known as the
static method. The most common example of a static method is
the main( ) method. As discussed above, Any static member can be
accessed before any objects of its class are created, and without
reference to any object. Methods declared as static have several
restrictions:
 They can only directly call other static methods.
 They can only directly access static data.
 They cannot refer to this or super in any way.
class Example {
// Static variable (shared among all instances)
static int count = 0;

// Constructor to increment count when a new object is


created
Example() {
count++; // Increments the shared variable
}

// Static method to display the count


static void displayCount() {
System.out.println("Number of objects created: " +
count);
}
}

public class static_key {


public static void main(String[] args) {
// Creating objects
Example obj1 = new Example();
Example obj2 = new Example();
Example obj3 = new Example();

// Calling static method without creating an object


Example.displayCount();
}
}

24. Define Wrapper class and why it is required. Write a program of it.
A Wrapper class in Java is one 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.
Need of Wrapper Classes:
There are certain needs for using the Wrapper class in Java as
mentioned below:
1. They convert primitive data types into objects. Objects are needed
if we wish to modify the arguments passed into a method
(because primitive types are passed by value).
2. The classes in java.util package handle only objects and hence
wrapper classes help in this case.
3. Data structures in the Collection framework, such
as ArrayList and Vector, store only objects (reference types) and
not primitive types.
4. An object is needed to support synchronization in multithreading.
public class WrapperExample {
public static void main(String[] args) {
// Autoboxing: Converting primitive to wrapper object
Integer num = 10;
Double price = 99.99;

// Unboxing: Converting wrapper object to primitive


int newNum = num;
double newPrice = price;

// Displaying values
System.out.println("Integer object: " + num);
System.out.println("Converted to primitive int: " + newNum);
System.out.println("Double object: " + price);
System.out.println("Converted to primitive double: " +
newPrice);
}
}

25. Define vector. Write a java code to show advantage of vector over
array.
A Vector in Java is a dynamic array that can grow and shrink in size. It is
part of the java.util package and implements the List interface.
Key Features of Vector:
 It automatically resizes when elements are added or removed
(unlike arrays, which have fixed size).
 It is synchronized, making it thread-safe.
 It allows duplicate elements and maintains insertion order.
import java.util.Vector;

public class VectorExample {


public static void main(String[] args) {
// Using an array (fixed size)
int[] arr = new int[3];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
// arr[3] = 40; // X This will cause an
ArrayIndexOutOfBoundsException

// Using a Vector (dynamic size)


Vector<Integer> vec = new Vector<>();
vec.add(10);
vec.add(20);
vec.add(30);
vec.add(40); // ✅ No issue, Vector expands
dynamically

// Displaying array elements


System.out.println("Array Elements:");
for (int num : arr) {
System.out.print(num + " ");
}

System.out.println("\n\nVector Elements:");
for (int num : vec) {
System.out.print(num + " ");
}

// Demonstrating dynamic resizing


System.out.println("\n\nAdding more elements to
Vector...");
vec.add(50);
vec.add(60);

System.out.println("Updated Vector: " + vec);


}
}

26. Why to use inheritance in java and explain it types. Write a code
to show how multilevel inheritance is possible in java.
Inheritance is a mechanism in Java where a child class acquires
properties and behaviors (methods) from a parent class. This allows
code reusability, reduces redundancy, and enables method overriding
and polymorphism.
Key Benefits of Inheritance:
1. Code Reusability – You don't have to write the same code again in
multiple classes.
2. Method Overriding – A child class can provide its own
implementation of a method defined in the parent class.
3. Improved Maintainability – Changes made in the parent class
automatically reflect in the child classes.
4. Extensibility – You can add new features without modifying
existing code.
Types of Inheritance in Java
1️. Single Inheritance
 A child class inherits from a single parent class.
 Example: A Dog class inherits from an Animal class.
 Advantage: The child class can use existing methods from the
parent.
2️. Multilevel Inheritance
 A class inherits from another class, which itself is a child of
another class (like a chain).
 Example: Puppy → Dog → Animal
 Advantage: The properties are passed down multiple levels.
3️. Hierarchical Inheritance
 Multiple child classes inherit from a single parent class.
 Example: Dog and Cat both inherit from Animal.
 Advantage: Different child classes can use the common properties
of the parent.
4️. Multiple Inheritance (Not Supported Directly in Java)
 Java does not allow multiple inheritance with classes to avoid
ambiguity.
 Solution: Java achieves multiple inheritance using interfaces.
 Example: A class can implement two interfaces and inherit
behaviors from both.
class Animal {
void eat() {
System.out.println("Animals can
eat");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Dogs can bark");
}
}
class Puppy extends Dog {
void weep() {
System.out.println("Puppies weep");
}
}

public class MultilevelInheritance {


public static void main(String[] args) {
Puppy myPuppy = new Puppy();

myPuppy.eat();
myPuppy.bark();
myPuppy.weep();
}
}

27. Differentiate between method overloading and method overriding


with a suitable code.
Method
overloading

Method
overriding

You might also like