Unit-1
1. List the primitive data types available in Java and explain
data types specify the type of data that can be stored inside variables in Java.
Java is a statically-typed language. This means that all variables must be declared before they can
be used. int speed;
Here, speed is a variable, and the data type of the variable is int.
Data type Meaning Memory size Range Default Value
byte Whole numbers 1 byte -128 to +127 0
short Whole numbers 2 bytes -32768 to +32767 0
int Whole numbers 4 bytes -2,147,483,648 to +2,147,483,647 0
long Whole numbers 8 bytes 9,223,372,036,854,775,808 to 0L
+9,223,372,036,854,775,807
float Fractional 4 bytes - 0.0f
numbers
double Fractional 8 bytes - 0.0d
numbers
char Single character 2 bytes 0 to 65535 \u0000
boolean unsigned char 1 bit 0 or 1 0 (false)
Example:
public class NonPrimitiveDataTypes {
String str;
public static void main(String[] args) {
String name = "BTech Smart Class!";
String wish = "Hello, ";
NonPrimitiveDataTypes obj = new NonPrimitiveDataTypes();
System.out.println("str = " + obj.str);
//using addition method
System.out.println(wish.concat(name));
}
}
2. List and explain the Java buzzwords in detail.
Java is the most popular object-oriented programming language. Java has many advanced
features; a list of key features is known as Java Buzz Words. The java team has listed the
following terms as java buzz words.
Simple
Secure
Portable
Object-oriented
Robust
Architecture-neutral (or) Platform Independent
Multi-threaded
Interpreted
High performance
Distributed
Dynamic
Simple
Java programming language is very simple and easy to learn, understand, and code. Most of the
syntaxes in java follow basic programming language C and object-oriented programming
concepts are similar to C++. In a java programming language, many complicated features like
pointers, operator overloading, structures, unions, etc. have been removed. One of the most
useful features is the garbage collector it makes java more simple.
Secure
Java is said to be more secure programming language because it does not have pointers concept,
java provides a feature "applet" which can be embedded into a web application. The applet in
java does not allow access to other parts of the computer, which keeps away from harmful
programs like viruses and unauthorized access.
Portable
Portability is one of the core features of java which enables the java programs to run on any
computer or operating system. For example, an applet developed using java runs on a wide
variety of CPUs, operating systems, and browsers connected to the Internet.
Object-oriented
Java is said to be a pure object-oriented programming language. In java, everything is an object.
It supports all the features of the object-oriented programming paradigm. The primitive data
types java also implemented as objects using wrapper classes, but still, it allows primitive data
types to archive high-performance.
Robust
Java is more robust because the java code can be executed on a variety of environments, java
has a strong memory management mechanism (garbage collector), java is a strictly typed
language, it has a strong set of exception handling mechanism, and many more.
Architecture-neutral (or) Platform Independent
Java has invented to archive "write once; run anywhere, any time, forever". The java provides
JVM (Java Virtual Machine) to to archive architectural-neutral or platform-independent. The JVM
allows the java program created using one operating system can be executed on any other
operating system.
Multi-threaded
Java supports multi-threading programming, which allows us to write programs that do multiple
operations simultaneously.
Interpreted
Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java bytecode. The byte code is interpreted to any machine code so that it
runs on the native machine.
High performance
Java provides high performance with the help of features like JVM, interpretation, and its
simplicity.
Distributed
Java programming language supports TCP/IP protocols which enable the java to support the
distributed environment of the Internet. Java also supports Remote Method Invocation (RMI),
this feature enables a program to invoke methods across a network.
Dynamic
Java is said to be dynamic because the java byte code may be dynamically updated on a running
system and it has a dynamic memory allocation and deallocation (objects and garbage collector).
3. What is an array? How do you declare the array in java? Give examples
An array is a collection of similar data values with a single name. An array can also be defined as,
a special type of variable that holds multiple values of the same data type at a time.
In java, arrays are objects and they are created dynamically using new operator. Every array in
java is organized using index values. The index value of an array starts with '0' and ends with
'size-1'. We use the index value to access individual elements of an array.
In java, there are two types of arrays and they are as follows.
One Dimensional Array
Multi Dimensional Array
Creating an array
One Dimensional Array
In the java programming language, an array must be created using new operator and with a
specific size. The size must be an integer value but not a byte, short, or long. We use the
following syntax to create an array.
Syntax
data_type array_name[ ] = new data_type[size];
(or)
data_type[ ] array_name = new data_type[size];
Let's look at the following example program.
Example
public class ArrayExample {
public static void main(String[] args) {
int list[] = new int[5];
list[0] = 10;
System.out.println("Value at index 0 - " + list[0]);
System.out.println("Length of the array - " + list.length);
}
}
Multidimensional Array
In java, we can create an array with multiple dimensions. We can create 2-dimensional, 3-
dimensional, or any dimensional array.
In Java, multidimensional arrays are arrays of arrays. To create a multidimensional array variable,
specify each additional index using another set of square brackets. We use the following syntax
to create two-dimensional array.
Syntax
data_type array_name[ ][ ] = new data_type[rows][columns];
(or)
data_type[ ][ ] array_name = new data_type[rows][columns];
4. Write the significance of Java Virtual Machine(Diagram) and Byte Code.
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
The JVM performs following operation:
Loads code, Verifies code, Executes code,Provides runtime environment
JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).
5. What is inheritance ? Demonstrate various forms of inheritance with suitable program segments.
How to prevent a class from inheritance?
Inheritance
Inheritance is a fundamental concept in object-oriented programming that allows one
class (subclass or derived class) to inherit properties and behaviors (fields and methods)
from another class (superclass or base class).
Java supports inheritance, which enables you to create a hierarchy of classes, promoting
code reuse and extending the functionality of existing classes.
The subclass can add its own fields and methods or override the superclass's methods.
Syntax:
class Subclass extends Superclass
{
// Subclass members
}
A subclass constructor can call a superclass constructor using super(...).If the subclass
constructor doesn't explicitly call super(...), the default no-argument constructor of the
superclass is called automatically.
Subclasses can override (provide a new implementation for) methods inherited from the
superclass.
Public and protected members of the superclass are accessible in the subclass.
We can prevent a class from being inherited (i.e., make it "final") by declaring the class with
the final keyword. When a class is marked as final, it cannot be extended by any other class.
Syntax:
final public class FinalClassExample {
// Class members and methods go here
}
Types of Inheritance
Single Inheritance:
A subclass inherits from only one superclass. Java supports single inheritance directly.
Example:
class GrandParent
{
private String gname;
public void eat(String s)
{
gname=s;
System.out.println(gname);
System.out.println("eat method of Grandparent class executed");
}
}
class Child extends GrandParent
{
protected String cname="amar";
public void drink()
{
System.out.println("drink method of child class executed");
}
}
class InheritanceTypesEx
{
public static void main(String[] args)
{
Child men=new Child();
men.eat("ali");
men.drink();
System.out.println("Grandparent name:"+men.gname);
System.out.println("Child name:"+men.cname);
}
}
Multiple Inheritance (Through Interfaces):
Java does not support multiple inheritance directly, where a class inherits from multiple classes.
However, multiple inheritance-like behavior can be achieved through interfaces,
Multilevel Inheritance:
A class inherits from another class, which in turn inherits from another class. It creates a chain of
inheritance relationships.
Example:
class GrandParent
{
private String gname;
public void eat(String s)
{
gname=s;
System.out.println(gname);
System.out.println("eat method of Grandparent class executed");
}
}
class Child extends GrandParent
{
protected String cname="amar";
public void drink()
{
System.out.println("drink method of child class executed");
}
}
class GrandChild extends Child
{
String gcname="anthony";
public void sleep()
{
System.out.println("sleep method of Grandchild class executed");
}
}
class InheritanceTypesEx
{
public static void main(String[] args)
{
GrandChild men=new GrandChild();
men.eat("ali");
men.drink();
men.sleep();
//System.out.println("Grandparent name:"+men.gname);
System.out.println("Child name:"+men.cname);
System.out.println("GrandpChild name:"+men.gcname);
System.out.println("Main method");
}
}
Hierarchical Inheritance:
multiple classes inherit from a single superclass. This creates a branching hierarchy, with several
subclasses deriving from a common superclass.
class Parent
{
private String pname;
public void eat(String s)
{
pname=s;
System.out.println(pname);
System.out.println("eat method of parent class executed");
}
}
class Child1 extends Parent
{
protected String cname1="amar";
public void drink()
{
System.out.println("drink method of child class executed");
}
}
class Child2 extends Parent
{
String cname2="anthony";
public void sleep()
{
System.out.println("sleep method of Grandchild class executed");
}
}
class InheritanceTypesEx
{
public static void main(String[] args)
{
Child1 men1=new Child1();
men1.eat("ali");
men1.drink();
Child2 men2=new Child2();
men2.eat("ali");
men2.sleep();
System.out.println("parent name:"+men1.pname);
System.out.println("Child1 name:"+men1.cname1);
System.out.println("Child2 name:"+men2.cname2);
}
}
6. What is the purpose of constructor in Java programming? Explain constructor overloading in java
Constructor
Constructor is a special type of method that is used for initializing objects when they are
created.
Constructors have the same name as the class and do not have a return type, not even
void. They are called automatically when an object is created using the new keyword.
Constructors can take one or more parameters.
Constructors can have access modifiers.
If you don't define any constructors in your class, Java provides a default constructor
with no arguments.
You can define multiple constructors in a class, and one constructor can call another
using this(keyword).
Constructors of a subclass must call a constructor of the superclass either explicitly using
super(...) or implicitly.
Constructor Overloading in java
Constructor overloading means defining two or more constructors within the same class.
In this case the constructors are said to be overloaded and the process is called
constructor overloading.
Now the question arises how Java determines which constructor to call, It is done by
determining the type of arguments and the number of arguments in the constructor’s
definition.
Constructor overloading is similar to method overloading, but it involves constructors
instead.
ConstructorOverloadingExample
public class ConsOver
{
int age;
String name;
public ConsOver(int a, String n)
{
age = a;
name = n;
}
public ConsOver(String n)
{
name = n;
}
public static void main(String[] args)
{
ConsOver u1 = new ConsOver(20, "Ali");
System.out.println("Age:" + u1.age);
System.out.println("Name:" + u1.name);
ConsOver u2 = new ConsOver("Ahmed");
System.out.println("Age:" + u2.age);
System.out.println("Name:" + u2.name);
}
}
7. What is polymorphism? Explain various forms of polymorphism(compile time(method
overloading) and run time(method overriding))
Polymorphism means defining one entity with multiple behavior's
In java we have following 2 types of poly morphisms.
1. Compile time polymorphism
Method overloading allows a class to have multiple methods with the same name
but different parameter lists.
The appropriate method to be called is determined at compile-time based on the
number and types of arguments passed.
Note: By using the concept of method overloading we can achieve this compile time
poly morphism.
It is also called as static polymorphism or early binding
Method overloading
Method overloading(Ad hoc Polymorphism) means declaring multiple methods with
same method name but having different method signature.
In method overloading while writing the method signature we have to follow
following 3 Rules
Method name must be same for all methods
List of parameters must be different like different type of parameters, different
number of parameters, different order of parameters.
Return type is not considered in method overloading; it means we never decide
method overloading with return type.
public class MethodOverloadingExample {
// Method with no parameters
public void printMessage() {
System.out.println("Hello, World!");
}
// Method with one parameter of type int
public void printMessage(int num) {
System.out.println("The number is: " + num);
}
// Method with two parameters of type double
public void printMessage(double num1, double num2) {
System.out.println("Sum of two numbers is: " + (num1 + num2));
}
public static void main(String[] args) {
MethodOverloadingExample example = new MethodOverloadingExample();
// Call the overloaded methods
example.printMessage(); // Calls the first method with no parameters
example.printMessage(42); // Calls the second method with an int parameter
example.printMessage(3.5, 2.7); // Calls the third method with two double parameters
}
}
2. Runtime Polymorphism
Method overriding occurs when a subclass provides a specific implementation for a
method that is already defined in its superclass.
Note: By using the concept of method overriding we can achieve this runtime poly
morphism.
It is also called as Dynamic polymorphism or late binding.
Method overriding
If we want to achieve the run time polymorphism then we have to use method
overriding.
Method overriding means declaring 2 methods with same method signature in 2
different classes which are having IS-A relation.
While Method overriding and writing the method signature, we must follow
following rules.
• Method name must be same
• List of parameters must be same
• Return type must be same
• Private, final and static methods cannot be overridden.
• There must be an IS-A relationship between classes (inheritance).
MethodOverridingExample
class Shape
{
void display() {
System.out.println("This is a shape.");
}
}
class Circle extends Shape
{
@Override
void display() {
//super.display();
System.out.println("This is a circle.");
}
}
public class MethodOverridingExample {
public static void main(String[] args) {
Shape shape1 = new Circle();
shape1.display(); // Calls Circle's overridden method
}
}
class Animal
{
String name = "Animal";
void eat()
{
System.out.println(name + " is eating.");
}
}
8. With suitable program segments examine the usage of “super‟ “final” and “this” keywords.
Super keyword
The super keyword in Java is used to refer to the immediate parent class or superclass of
a derived (subclass) class.
It is primarily used to access members (fields and methods) of the superclass that may
be overridden or hidden by members in the subclass.
The super keyword is often used in scenarios where there is a need to differentiate
between the members of the subclass and the members of the superclass.
SuperKeywordExample
class Dog extends Animal
{
String name = "Dog";
@Override
void eat()
{
super.eat(); // Calls the eat() method of the superclass
System.out.println(name + " is eating bones.");
}
void displayNames()
{
System.out.println("Superclass name: " + super.name); // Accesses the superclass's name
System.out.println("Subclass name: " + name);
}
}
public class SuperKeywordExample
{
public static void main(String[] args)
{
Dog dog = new Dog();
dog.eat();
dog.displayNames();
}
}
Final keyword
final is a keyword or modifier which can be used at variables, methods & classes.
If we declare a variable as final then we can’t modify value of the variable. The variable
acts like a constant. Final field must be initialized when it is declared.
If we declare a method as final then we can't override that method
If we declare a class as final then we can't extend from that class. We cannot inherit final
class in Java.
public final class FinalDemo
{
final int a=10; //valid
//b=10; invalid
// final int c; invalid
final void m1()
{
System.out.println("a:"+a);
}
public static void main(String[] args)
{
FinalDemo d=new FinalDemo();
d.m1();
}
}
This keyword
The this keyword in Java is a reference to the current instance of the class in which it's
used.
It's used to differentiate between instance variables (fields) and parameters or local
variables with the same name.
The this keyword is commonly used in constructors and instance methods to access and
manipulate instance variables and methods.
ThisKeyword
public class ThisKeyword
{
private String name;
private int age;
public ThisKeyword(String name, int age) // Constructor with parameters
{
name = name; // not 'this' to refer to the instance variable
age = age;
}
public void displayInfo() // Method to display information about the person
{
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
public static void main(String[] args)
{
ThisKeyword p1 = new ThisKeyword("Alice", 25);
p1.displayInfo();
}
}
9. What is encapsulation and how is it achieved in java. Explain the significance of default,public,
protected and private access specifiers in inheritance.
The binding of data (attributes or fields) and methods into a single unit is called encapsulation.
In Java, encapsulation is achieved by using access modifiers to control the visibility of fields and
methods within a class.
There are four types of access modifiers in Java:
public: The member is accessible from any other class.
protected: The member is accessible within its own package and by subclasses.
default (no modifier): The member is accessible only within its own package.
private: The member is accessible only within its own class.
Encapsulation provides a mechanism for controlling access to data and methods, Data
Hiding, promoting code organization, reusability, maintainability, and security in your
object-oriented programming
EncapsulationExample
class Student
{
public String ename; // private field
private int eage; // private field
public void setInfo(String name, int age)
{
ename = name;
eage=age;
}
public void getInfo()
{
System.out.println("Name: " + ename);
System.out.println("Age: " + eage);
}
}
class EncapsulationEx
{
public static void main(String[] args)
{
Student s1 = new Student();
s1.setInfo("Arjun",20);
s1.getInfo();
//System.out.println(s1.ename);
//System.out.println(s1.eage);