JAVA

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

JAVA TUTORIAL 1 SOLUTIONS

1. Bring out the differences between Object Oriented and Procedure Oriented
Programming
Sol:

2.Explain how “compile once, run anywhere” is implemented in java


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

• Java Programs run inside a virtual machine sandbox

• 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:

• The English mining of Robust is strong.


Java is robust because:

• It uses strong memory management.

• There is a lack of pointers that avoids security problems.

• 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 enables the creation of cross-platform programs by compiling into an intermediate


representation called Java bytecode. This code can be executed on any system that
implements the Java Virtual Machine.
• Most previous attempts at cross-platform solutions have done so at the expense of
performance. As explained earlier, the Java bytecode 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.
x) Distributed:

• 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;

Scanner in = new Scanner(System.in);


System.out.println("Enter the number of rows: "); row = in.nextInt( );
System.out.println("Enter the number columns: ");
col = in.nextInt( );

int mat1[ ][ ] = new int[row][col];


int mat2[ ][ ] = new int[row][col];
int res[ ][ ] = new int[row][col];
System.out.println("Enter the elements of matrix1:\n");
for ( i= 0 ; i < row ; i++ )

{
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++ )
{

for ( j= 0 ; j < col ;j++ )


mat2[i][j] = in.nextInt();
System.out.println();
}
for ( i= 0 ; i < row ; i++ )

for ( j= 0 ; j < col ;j++ )


res[i][j] = mat1[i][j] + mat2[i][j] ;
System.out.println("Sum of matrices:\n");
for ( i= 0 ; i < row ; i++ )

for ( j= 0 ; j < col ;j++ )


System.out.print(res[i][j]+"\t");

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.

6.Explain the following operations with examples. (i)<< (ii)>> (iii)>>>


Sol: 1. Left Shift Operator (<<)
• Operation: Shifts the bits of a number to the left by a specified number of positions,
filling the rightmost bits with zeros.

• Effect: For every left shift, the number is effectively multiplied by 2.


Example:
int x = 4; // 4 in binary is 0000 0100
int result = x << 2; // Shift left by 2 positions: 0001 0000 (which is 16 in decimal)
System.out.println(result); // Output: 16

2. Right Shift Operator (>>)


• Operation: Shifts the bits of a number to the right by a specified number of positions,
preserving the sign (the leftmost bit, which indicates the sign, is filled with the
original sign bit).

• 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.

• Effect: This is useful for dealing with unsigned numbers in binary.


Example:
int x = -16; // -16 in binary is 1111 0000 (in two's complement)
int result = x >>> 2; // Shift right by 2 positions: 0011 1100 (in unsigned mode, it's
1073741820 in decimal)
System.out.println(result); // Output: 1073741820.

7.Write a Java program to sort the elements using a for loop.

Sol: import java.util.Scanner;

public class SortArray {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input: Number of elements in the array

System.out.print("Enter the number of elements: ");

int n = scanner.nextInt();

// Declare the array

int[] arr = new int[n];

// Input: Array elements

System.out.println("Enter the elements of the array:");

for (int i = 0; i < n; i++) {

arr[i] = scanner.nextInt();

// Sort the array using a for loop (Bubble Sort)


for (int i = 0; i < n - 1; i++) {

for (int j = 0; j < n - 1 - i; j++) {

if (arr[j] > arr[j + 1]) {

// Swap arr[j] and arr[j+1]

int temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

// Output: Sorted array

System.out.println("Sorted array:");

for (int i = 0; i < n; i++) {

System.out.print(arr[i] + " ");

scanner.close();

8. Explain different types of if statements in JAVA

Sol: The different conditional statements are,

i) if ii) if-else iii) else-if ladder iv) nested-if v) switch.


i) if:

• 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:

• This is 2-way selection statement.


• This is used to check 2 conditions at a time.
• if expression is true, it will execute some set of statements else, it will execute other
set of statements.
• Syntax: if(expression)
{statements;}

Else

{statements;}

• Example:
int a=4,b=6;

if(a>b)

System.out.println(“a is big: ” +a);

Else

System.out.println(“b is big: ” +b);

else if ladder:

• This is a Multiway selection statement.


• That is more than one condition we can check at a time.

• 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)

{statements;} ............... ............... else {statements;}

Example:

int a=4,b=6,c=8;

if(a>b && a>c)

System.out.println(“a is big: ” +a);

else if(b>a && b>c)

System.out.println(“b is big: ” +b);

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.

There are two types,

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( ) {

return width * height * depth;

}
}
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 {

// Recursive function to find the nth Fibonacci number

public static int fibonacci(int n) {

if (n == 0) {

return 0; // Base case: Fibonacci(0) = 0

} else if (n == 1) {

return 1; // Base case: Fibonacci(1) = 1

} else {

return fibonacci(n - 1) + fibonacci(n - 2); // Recursive case

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input: nth number for Fibonacci sequence

System.out.print("Enter the position of the Fibonacci number to find: ");

int n = scanner.nextInt();

// Output: nth Fibonacci number

int result = fibonacci(n);


System.out.println("The Fibonacci number at position " + n + " is: " + result);

scanner.close();

11. Explain the various access specifiers in Java.

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

having the default access specifier by default.

• 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.

• Ex: package p1;

class A {

void display() {

System.out.println("Hello World!");

Private:

• The private access specifier is specified using the keyword private.


• The methods or data members declared as private are accessible only within the
class in which they are declared.
• Any class with the same package will not be able to access these members.
• Ex: package p1;
class A {
private void display() {
System.out.println(“SJCIT”);
}
}
class B {
public static void main(string args[ ]) {
A obj = new A( );
obj.display( ); //error…!!!
}
}
ii) Protected:
• The protected access specifier is specified using the keyword protected.
• The methods or data members declared as protected are accessible within the same
package or sub-classes in different packages.
• Ex: package p1;
public class A {
protected void display() {
System.out.println("SJCIT");
}
}
package p2;
import p1.*;
class B extends A
{ public static void main (string args[ ]) {
B obj = new B( );
obj.display( );
}
}
iii) Public:
• The public access specifier is specified using the keyword public.
• The public access specifier has the widest scope among all other access specifiers.
• The methods or data members declared as public are accessible from everywhere in
the program.
• Ex: package p1;
public class A {
public void display( ) {
System.out.println("SJCIT");
}
}
package p2;
import p1.*;
class B {
public static void main (string args[ ]) {
A obj = new A( );
obj.display( );
}
}
12. Explain call by value and call by reference with an example program

• 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 stck[] = new int[10];

int top

// Initialize top-of-stack

Stack()

top=-1;

// Push an item onto the stack

void push(int item)


{

if(top==9)

System.out.println("Stack underflow.");

return 0;

else return stck[top--];

Class StackDemo

Public static void main(String args[])

Stack ob=new stack(10);

for(int i=0;i<=10;i++)

ob.push(i); ob.pop();

output:

Enter the stack size

10

Enter the elements for stack

0123456789

Stack elements are:


0

14.Explain the role of “ this” and “static” keyword ?

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:

public class Main {

int x;

public Main(int x) {

this.x = x;
}

public static void main(String[] args) {

Main myObj = new Main(5);

System.out.println("Value of x = " + myObj.x);

Output: Value of x =5.

static Keyword in Java:

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.

Roles of static keyword:

1. Static Variables (Class Variables):

o When a variable is declared as static, it is shared among all instances of the


class.

o Only one copy of a static variable exists, regardless of the number of objects
created.

o It is initialized only once, at the start of the program execution.

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 A static block is used for static initialization of a class.

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:

o A nested class can be declared as static. In that case, it can be accessed


without creating an instance of the outer class.

class StaticExample {

// Static variable (class variable)

static int count = 0;

// Instance variable

int id;

// Constructor to increment count and assign id

StaticExample() {

count++; // Increment static variable

id = count; // Assign unique id to each object

// Static method

static void displayCount() {

System.out.println("Total Objects Created: " + count);

}
// Non-static method

void displayID() {

System.out.println("Object ID: " + id);

public class TestStatic {

public static void main(String[] args) {

StaticExample obj1 = new StaticExample();

StaticExample obj2 = new StaticExample();

StaticExample obj3 = new StaticExample();

// Accessing static method directly using class name

StaticExample.displayCount(); // Output: Total Objects Created: 3

// Accessing instance method through objects

obj1.displayID(); // Output: Object ID: 1

obj2.displayID(); // Output: Object ID: 2

obj3.displayID(); // Output: Object ID: 3

15.Write a note on: a. Garbage Collection. b. Object Reference variable.


Sol: a) Garbage Collection:

• 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.

• The technique that accomplishes this is called garbage collection.

• 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.

• There is no explicit need to destroy objects as in C++.

• 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.

b) Object Reference Variable:

• Object reference variables act differently when an assignment takes place.

Box b1 = new Box(); Box b2 = b1;

• 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.

• It simply makes b2 refer to the same object as does b1.

• 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.

16.What is method overloading? Illustrate with a suitable program.


Sol: Method Overloading

• 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

int sum(int a, int b)

return a + b;

int sum(int a)

return a + 10;

}
}

class overloadingDemo

public static void main(String args[ ])

Add a=new Add( );

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.

Sol: import java.util.Scanner;

public class LargestNumber {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input three numbers


System.out.print("Enter first number: ");

int num1 = scanner.nextInt();

System.out.print("Enter second number: ");

int num2 = scanner.nextInt();

System.out.print("Enter third number: ");

int num3 = scanner.nextInt();

// Use ternary operator to find the largest number

int largest = (num1 > num2) ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 :
num3);

// Output the largest number

System.out.println("The largest number is: " + largest);

scanner.close();

Output:

Enter first number: 15

Enter second number: 42

Enter third number: 33

The largest number is: 42


18. Write a program to perform Stack operation using proper class and methods

Sol:

REPEATED QUESTION SAME ANSWER OF 13

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