JAVA
JAVA
JAVA
1. Bring out the differences between Object Oriented and Procedure Oriented
Programming
Sol:
• One of the major problems facing programmers is that no guarantee exists that if you
write a program today, it will run tomorrow even on the same machine.
• Operating system upgrades, processor upgrades and changes in core system resources
can all combine to make a program malfunction.
• Java virtual language machine, goal is that - write once; run anywhere, anytime,
forever. Java enables the creation of cross platform programs by compiling into an
intermediate representation called Java Byte code.
• Byte code is a highly optimized set of instructions designed to be executed by the
java run time system.
• Translating a java program into byte code makes it much easier to run a program in a
wide variety of environment because JVM needs to be implemented for each
platform. Execution of byte code by the JVM is the easiest way to create truly
portable programs.
• The java byte code was carefully designed so that it would be easy to translate
directly into native machine code for very high performance by using a just-in-time
compiler.
• Java run time systems that provide this feature lose none of the benefits of the
platform- independent code. This enables us to implement ―compile once, run
anywhere” in java in the distributed environment without bothering about
architectures of the systems and their configuration.
3.List and explain the java buzzwords
Sol: i) Simple ii) Secure iii) Portable iv) Object-oriented v) Platform Independent vi) Robust vii)
Multithreaded viii) Architecture-neutral ix) Interpreted and High performance x) Distributed xi)
Dynamic.
1.Simple:
• Java was designed to be easy for the professional programmer to learn and use effectively.
• If you already understand the basic concepts of object-oriented programming, learning Java
will be even easier. Because Java inherits the C/C++ syntax
ii) Secure:
• Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:
• No explicit pointer
• Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which
is used to load Java classes into the Java Virtual Machine dynamically
• Security Manager: It determines what resources a class can access such as reading and
writing to the local disk.
iii) Portable:
•
Java is portable because it facilitates you to carry the Java bytecode to any platform.
It doesn't require any implementation.
iv) Object-oriented:
•
Java is an object-oriented programming language. Everything in Java is an object.
Object- oriented means we organize our software as a combination of different types
of objects that incorporate both data and behavior.
• Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.
v) Platform Independent:
• Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run anywhere
language.
• A platform is the hardware or software environment in which a program runs.
• Java provides a software-based platform.
• Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere.
vi) Robust:
• Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of
objects which are not being used by a Java application anymore.
• There are exception handling and the type checking mechanism in Java.
vii) Multithreaded:
• Java was designed to meet the real-world requirement of creating interactive, networked
programs. To accomplish this, Java supports multithreaded programming, which allows you
to write programs that do many things simultaneously.
viii) Architecture-neutral / Machine Independent:
• Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
• In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32
and 64- bit architectures in Java.
ix) Interpreted and High Performance:
• Java is designed for the distributed environment of the Internet because it handles TCP/IP
protocols.
• In fact, accessing a resource using a URL is not much different from accessing a file. Java
also supports Remote Method Invocation (RMI). This feature enables a program to invoke
methods across a network.
xi) Dynamic:
• Java is a dynamic language. It supports the dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.
• Java supports dynamic compilation and automatic memory management (garbage collection).
5.Define Array. Write a Java program to implement the addition of two matrixes.
Sol: An array is a data structure that stores a fixed-size collection of elements of the same
type in a contiguous block of memory.
import java.util.Scanner;
class Sample
{
public static void main (String args[ ])
{
int row, col,i,j;
{
for ( j= 0 ; j < col ;j++ );
mat1[i][j] = in.nextInt();
System.out.println();
}
System.out.println("Enter the elements of matrix2:\n");
for ( i= 0 ; i < row ; i++ )
{
System.out.println();
}
}
}
Output:
Enter the number of rows:
2
Enter the number columns:
3
Enter the elements of matrix1: 1 2 3 3 2 1
Enter the elements of matrix2: 4 5 6 6 5 4
Sum of matrices: 5 7 9 9 7 5.
• Effect: For every right shift, the number is effectively divided by 2, rounding down.
Example:
int x = 16; // 16 in binary is 0001 0000
int result = x >> 2; // Shift right by 2 positions: 0000 0100 (which is 4 in decimal)
System.out.println(result); // Output: 4
3. Unsigned Right Shift Operator (>>>)
• Operation: Shifts the bits of a number to the right by a specified number of positions,
filling the leftmost bits with zeros regardless of the sign.
int n = scanner.nextInt();
arr[i] = scanner.nextInt();
arr[j + 1] = temp;
System.out.println("Sorted array:");
scanner.close();
• keyword is if.
• This is used to check only one condition at a time. So, it is called as one way selection
statement.
• Syntax: if expression is true then it will execute set of statements if(expression)
{statements;}
• Example: int a=5,b=3; if(a>b) System.out.println(“a is Big: ” +a);
• //output: a is Big: 5
ii) if else:
Else
{statements;}
• Example:
int a=4,b=6;
if(a>b)
Else
else if ladder:
• The if statements are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is executed, and the rest
of the ladder is bypassed.
• If none of the conditions is true, then the final else statement will be executed. The
final else acts as a default condition: i.e ,if all other conditional tests fail, then the last
else statement is performed.
• If there is no final else and all other conditions are false, then no action will take place.
Syntax:
if(expression1)
{statements;}
else if(expression2)
{statements;}
else if(expression3)
Example:
int a=4,b=6,c=8;
else
System.out.println(“c is big: ” +c);
9. What are constructors? Explain two types of constructors with an example program.
Sol: A constructor is a special method that is invoked automatically when an object of the class
is created.
i)No-Argument constructor
ii)Parameterized constructor
i) No-Argument Constructor:
• It can be tedious to initialize all of the variables in a class each time an instance is
created. Even when you add convenience functions like setDim( ), it would be
simpler and more concise to have all of the setup done at the time the object is first
created.
• Because the requirement for initialization is so common, Java allows objects to
initialize themselves when they are created.
• This automatic initialization is performed through the use of a constructor. A
constructor initializes an object immediately upon creation.
• It has the same name as the class in which it resides and is syntactically similar to a
method.
• Once defined, the constructor is automatically called immediately after the object is
created, before the new operator completes.
• Constructors look a little strange because they have no return type, not even void.
This is because the implicit return type of a class constructor is the class type itself.
• It is the constructor’s job to initialize the internal state of an object so that the code
creating an instance will have a fully initialized, usable object immediately.
• Ex:
class Box {
double width;
double height;
double depth;
Box( ) { System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
double volume( ) {
}
}
class BoxDemo6 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
When this program is run, it generates the following results:
Constructing Box
Constructing
Box Volume is 1000.0
Volume is 1000.0
10. Define recursion. Write a recursive program to find nth Fibonacci number.
Sol: Recursion is a programming technique where a function calls itself in order to solve a
smaller instance of the same problem.
import java.util.Scanner;
public class FibonacciRecursion {
if (n == 0) {
} else if (n == 1) {
} else {
int n = scanner.nextInt();
scanner.close();
Access specifiers help to restrict the scope of a class, constructor, variable, method, or data
member.
• It provides security, accessibility etc… to the user, depending upon the access
specifier used with the element.
• There are four types of access specifiers in Java.
• They are,
Default – No keyword required. ii) Private iii) Protected iv) Public
i) Default:
• When no access specifier is specified for a class, method, or data member, it is said to be
• The data members, classes, or methods that are not declared using any access specifiers
i.e. having default access modifiers are accessible only within the same package.
class A {
void display() {
System.out.println("Hello World!");
Private:
• Sol: Call-by-value:
• When a parameter is pass-by-value, the caller and the callee method operate on two
different variables which are copies of each other.
• Any changes to one variable don’t modify the other.
• It means that while calling a method, parameters passed to the callee method will be
clones of original parameters.
• Any modification done in callee method will have no effect on the original parameters
in caller method.
Pass/call-by-Reference:
• When a parameter is pass-by-reference, the caller and the callee operate on the same
object.
• It means that when a variable is pass-by-reference, the unique identifier of the object
is sent to the method.
• Any changes to the parameter’s instance members will result in that change being
made to the original value.
13.Write a program to perform Stack operations using proper class and Methods
Sol: // This class defines an integer stack that can hold 10 values.
class Stack
int top
// Initialize top-of-stack
Stack()
top=-1;
if(top==9)
System.out.println("Stack underflow.");
return 0;
Class StackDemo
for(int i=0;i<=10;i++)
ob.push(i); ob.pop();
output:
10
0123456789
Sol:
• The most common use of “this” keyword is to eliminate the confusion between class
attributes and parameters with the same name (because a class attribute is shadowed
by a method or constructor parameter).
• this can also be used to:
• Invoke current class constructor
• Invoke current class method
• Return the current class object
• Pass an argument in the method call
• Pass an argument in the constructor call
Example:
int x;
public Main(int x) {
this.x = x;
}
the static keyword in Java is used for memory management and signifies that a particular
member (field, method, or block) belongs to the class rather than to instances (objects) of
the class. This means static members can be accessed directly using the class name without
creating an object of the class.
o Only one copy of a static variable exists, regardless of the number of objects
created.
2. Static Methods:
A method declared as static belongs to the class and can be called without
creating an instance of the class.
o Static methods can only access static variables and call other static methods.
o These methods cannot refer to this or super because they are not tied to an
object instance.
3. Static Blocks:
o It runs once, when the class is first loaded into memory, and is used to
initialize static variables or perform other class-level tasks.
4. Static Classes:
class StaticExample {
// Instance variable
int id;
StaticExample() {
// Static method
}
// Non-static method
void displayID() {
• Since objects are dynamically allocated by using the new operator, you might be
wondering how such objects are destroyed and their memory released for later reallocation.
• Java takes a different approach; it handles deallocation for you automatically.
• It works like this: when no references to an object exist, that object is assumed to be no
longer needed, and the memory occupied by the object can be reclaimed.
• Garbage collection only occurs sporadically (if at all) during the execution of your program.
• It will not occur simply because one or more objects exist that are no longer used.
• After this fragment executes, b1 and b2 will both refer to the same object.
• The assignment of b1 to b2 did not allocate any memory or copy any part of the original
object.
• Thus, any changes made to the object through b2 will affect the object to which b1 is
referring, since they are the same object.
• Although b1 and b2 both refer to the same object, they are not linked in any other way.
Box b1 = new Box(); Box b2 = b1;
// ...
b1 = null;
Here, b1 has been set to null, but b2 still points to the original object.
• In method overloading, methods of the same class share the same name but each
method must have different number of parameters or parameters having different
types and order.
• Method overloading means more than one method share the same name in the class
but having different signature.
• It is used to add or extend more to method’s behaviour.
• It is a compile time polymorphism
• It may or may not need inheritance. It always requires inheritance.
• The methods must have different signature.
• The methods must have same signature.
• A relationship exists between the methods of same class. A relationship exists
between the methods of super-class and sub-class.
• In method overloading, methods have same name different signatures but in the same
class. In method overriding, methods have same name and same signature but in
different class.
• It does not require more than one class for overloading.
Ex:
class Add
return a + b;
int sum(int a)
return a + 10;
}
}
class overloadingDemo
int res1=a.sum(10,20);
System.out.println("Sum="+res1);
int res2=a.sum(10);
System.out.println("Sum="+res2);
Output:
Sum=30
Sum=20
17.Write a program to find the biggest of three numbers using ternary Operator.
int largest = (num1 > num2) ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 :
num3);
scanner.close();
Output:
Sol:
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: