0% found this document useful (0 votes)
4 views17 pages

JAVA sem 4

Uploaded by

Manishkumar Rai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views17 pages

JAVA sem 4

Uploaded by

Manishkumar Rai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

JAVA:- James Gosling is the person who designed the language in 1991 along with his team at Sun

Microsystems. Initially, the team was developing language to program processor-controlled home
appliances. Controllers were wide in variety and so language was developed with a feature of ‘not
controller specific’. Home appliances like a set-top box, washing machines, fridge, microwave and
many more. The first version of Java was used to write these controller programs.

During 1994, Gosling realized the need to use the language for network programming. In 1995 it was
introduced as a network programming language and the Netscape was the first browser to run java
programs.

Features Of JAVA:-Though java was developed as a general-purpose programming language to be


used for home appliances, after 1995 it was modified and was introduced with new features to make
it compatible to be used on World Wide Web (WWW). During those days WWW was new and was
being adapted for data transmission. These new features made java an extraordinary and all-purpose
programming language. Points below discuss various features of java.

1)Object Oriented Programming Language:-Java is considered to be pure Object Oriented Language,


as everything in java is an Object. Objective of Object Oriented Programming paradigm is to provide
security to data from unintended processes. Object is a basic entity in OOP which encapsulates data
and processes together.

As an OOP language, it also supports all basic concepts of OOP. Applications developed using Java
can be easily extended or upgraded since it is based on the Object model. This feature makes java
applications more durable.

2)Platform independent and interpretered Language:-Java is more popular because it is platform-


independent. Here platform used to execute an application or service includes hardware and
software, hardware includes a processor, RAM, etc, while software includes an operating system and
other supporting software. Java programs have a feature that makes them platform-independent.

The compilation process for Java is different than other programming languages. When compiler
translates the High-Level Langage code to machine level language it adds some feature to code from
platform on which it has been compiled. Hence the compiled code now requires a platform with the
same configuration on which it has been compiled. Hence the compiled version of application
becomes platform dependent though the language is featured with 'platform-independent'. For
example, an application written and compiled using ‘c’ language on windows operating system, can
be executed on Windows operating system only, and cannot be executed on machines with Linux or
Ubuntu operating system.

3)Secure:-Java is considered to be a more secure development tool as it enables the developmentof


virus-free, tamper-free systems. Authentication techniques are based on public-key encryption.

4)Simple:-Syntaxes used in Java are simple and easy to remember. Moreover, java maintains
uniformity for the implementation of basic OOP concepts. Once formats used in OOP language are
clearly understood it becomes very easy to write programs.

Java programmers follow programming conventions that should be followed while writing java
programs which helps new programmers to be master of programming. But if anyone follows these
conventions it becomes very easy for him to read and understand programs written in java. These
conventions are given in upcoming sections.
5)Robust:-Java makes an effort to eliminate error-prone situations by emphasizing mainly on
compile-time error checking and runtime checking. While compiling java program all possible future
run time errors are estimated and accordingly program is compiled. It also provides a well defined
‘Exception Handling’ technique for handling run time errors. This helps to handle future errors.

In addition to the full proof compilation process, the Java compiler does not allow the programmer
to have any direct access to memory. The memory management process is taken care of by JVM
while executing the program. The feature is known as ‘Garbage Collection’.

6)Multithreaded:-With Java's multithreaded feature it is possible to write programs that can perform
many tasks simultaneously. This design feature allows the developers to construct interactive
applications that can run smoothly.

Inheritance?Single Inheritance ?:-Inheritance is the mechanism which allows a class to use properties
(attributes) and behaviour (methods) from its parent class. The feature helps to define a new system
based on the existing system. With the help of inheritance properties predefined with previously
defined class can be used by newly defined class. Here previously defined class is known as ‘parent
class’ or ‘super class’ while newly defined class is known as ‘child class’ or ‘sub class’. The sub class
derives members from super class hence it is also known as ‘derived class’.

1)Single Inheritance:-When sub class is derived from a single super-class then the type of inheritance
is known as simple or single inheritance.

Diagrammatically it is represented as –

Fig 3.3: Simple Inheritance

In the above diagram two classes are represented, class A and class B. Arrow is pointing towards A
which is the super-class and B is a sub-class. B as sub- class derives members from A whose access
modifiers are protected and public.

When an object defined on class A memory will be allocated for all members from class A like an
object on a normal class. While object defined on class B will have protected & public members from
class A and all members (private + protected + public) from class B. It is explained with the help of
following program –

/Program demonstrates Simple Inheritance/

/Here ‘A’ is a super class while ‘B’ is sub class/ class A

{protected int a,b;

public void setDataA(int i, int j)

a=i;b=j;

public void displayA()

System.out.println("\nObject OF class A: \nClass A: a= "+a+"\nb= "+b);

}
}

class B extends A

private int c;

public void setDataB(int i,int j, int k)

super.setDataA(i,j);

c=k;

public void displayB()

System.out.println("\nObject

OF class A: a="+a+"\nb= "+b+"\nClass B: c= "+c);

class SimpleInheritance

public static void main(String arg[])

A obA=new A(); B obB=new B(); obA.setDataA(4,5); obA.displayA(); obB.setDataB(40,50,60);


obB.displayB();

In the above program three classes are defined one is class ‘A’, second is class ‘B’, which are user
defined classes, and third is class ‘SimpleInheritance’ which is the class for implementation. Class ‘A’
and class ‘B’ are related with each other by the relation of ‘inheritance’.

Here class ‘A’ defines two attributes namely ‘a’ and ‘b’ of type integer and access modifier as
protected while two methods namely ‘setDataA()’ and ‘displayA() which are public. While class ‘B’
defines one attribute namely ‘c’ with access modifier ‘private’ and two methods setDataB() and
displayB() whose access modifier is public.

Class ‘SimpleInheritance’ defines objects for both classes. For ‘obA’, when gets allocated, occupies
memory to store two integers and two methods. On the other hand for ‘obB’ memory is allocated for
its own members that is ‘c’, ‘setDataB()’ and ‘displayB()’ as well as for its derived members from
super class ‘A’, namely ‘a’, ‘b’, ‘setDataA()’ and ‘displayA()’. So though class ‘B’ defines only one
variable its object can store data for three variable, one for its own and other two from its super
class.

Write a program to define a class employce having members with empno, (12) name, basic salary, DA
is 5% of Basic Salary, HRA is 10% of Basic Salary.

Professional tax is Rs. 200 and calculate Gross Salary for an employce. Write all necessary methods
accordingly.

Ans:-

public class Employee {

private int empno;

private String name;

private double basicSalary;

private double da;

private double hra;

private final double PROFESSIONAL_TAX = 200;

// Constructor

public Employee(int empno, String name, double basicSalary) {

this.empno = empno;

this.name = name;

this.basicSalary = basicSalary;

this.da = 0.05 * basicSalary;

this.hra = 0.1 * basicSalary;

// Getter and Setter methods

public int getEmpno() {

return empno;

public void setEmpno(int empno) {

this.empno = empno;

}
public String getName() {

return name;

public void setName(String name) {

this.name = name;

public double getBasicSalary() {

return basicSalary;

public void setBasicSalary(double basicSalary) {

this.basicSalary = basicSalary;

this.da = 0.05 * basicSalary;

this.hra = 0.1 * basicSalary;

public double getDa() {

return da;

public double getHra() {

return hra;

public double getProfessionalTax() {

return PROFESSIONAL_TAX;

// Calculate gross salary method

public double calculateGrossSalary() {

return basicSalary + da + hra - PROFESSIONAL_TAX;

In this implementation, we define the Employee class with private member variables for empno,
name, basicSalary, da, hra, and PROFESSIONAL_TAX. The da and hra variables are calculated as 5%
and 10% of the basicSalary, respectively. The PROFESSIONAL_TAX is a constant value of Rs. 200.
We also define a constructor that takes in the empno, name, and basicSalary as arguments and sets
the corresponding member variables accordingly. We also initialize the da and hra variables based on
the basicSalary in the constructor.

We also define getter and setter methods for each member variable to provide access to the private
variables. The setBasicSalary() method updates the da and hra variables based on the new
basicSalary.

Finally, we define a method calculateGrossSalary() that calculates the gross salary for an employee by
adding the basicSalary, da, and hra variables and subtracting the PROFESSIONAL_TAX.

AWT components:-As stated in introduction package’awt’ provides wide variety of classes

helping to develop GUI for an application and these classes are arranged hierarchically. The hierarchy
of classes in ‘awt’ package is represented with the help of following diagram shown

The classes in ‘awt’ acting as controls are derived from a super class ‘Component’. These controls are
divided under three categories –

• Container classes – As the name suggests objects created on container classes can store references
to other control objects, and hence create group of controls. The class ‘Container’ defines two sub
classes – ‘Window’ and ‘Panel’. Sub classes from class ‘Window’, ‘Frame’ and ‘Dialogue’, are used for
a desktop applications while the ‘Panel’ is used for development of ‘Applets’. Responsibility of
container objects is to refer its controls collectively.

• Input controls – ‘TextField’, ‘TextArea’, ‘CheckBox’ etc. are input controls which helps user to accept
input from user. These are individual controls and can be used as a part of a container.

• Output controls – ‘Label’ is a output control helps to give corresponding messages for input.

• Processing Controls – the controls which are responsible for carrying out process are the processing
controls. ‘Button’ is a processing control.

•Navigation controls-Menu’ is acting as a navigation control which helps to change control among
different forms.

What is Synchronization? Why it is necessary? Explain with example.

Synchronization refers to the coordination or orderly arrangement of events or actions in a system. It


is necessary to ensure that multiple processes or threads in a system operate in a controlled and
consistent manner to avoid errors, data corruption, or resource conflicts.

Synchronization is essential in multi-threaded programming where multiple threads share common


resources such as memory, files, or network connections. Without proper synchronization, different
threads may access and modify shared resources concurrently, leading to race conditions, deadlocks,
and other synchronization-related problems.

For example, consider a banking system that processes transactions from multiple users
concurrently. If two transactions try to withdraw money from the same account simultaneously,
without proper synchronization, it is possible that both transactions read the same account balance,
resulting in an incorrect balance after both transactions complete. To avoid such issues, the system
must synchronize access to the account balance so that only one transaction can withdraw money at
a time.

In summary, synchronization is necessary to ensure consistency, correctness, and efficiency in


concurrent systems by coordinating access to shared resources and managing interactions between
concurrent threads or processes.

Looping?describe for loop and while loop ?

Looping is a programming construct that allows a section of code to be executed repeatedly. It is


often used when we need to perform a task multiple times or when we need to iterate over a set of
data. In Java, there are two main types of loops: the for loop and the while loop.

The for loop in Java is used to iterate over a set of values. It has a specific syntax that includes a
variable declaration, a condition, and an increment or decrement statement. Here is an example of a
for loop in Java:

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

System.out.println("The value of i is: " + i);

In this example, the loop will iterate 10 times. The variable i is initialized to 0, and the loop will
continue as long as i is less than 10. After each iteration, the value of i is incremented by 1.

The while loop in Java is used to repeat a block of code as long as a certain condition is true. Here is
an example of a while loop in Java:

int i = 0;

while (i < 10) {

System.out.println("The value of i is: " + i);

i++;

In this example, the loop will iterate 10 times. The variable i is initialized to 0, and the loop will
continue as long as i is less than 10. After each iteration, the value of i is incremented by 1.

Both the for loop and the while loop can be used to achieve the same result, but they are often used
in different situations. The for loop is often used when we know how many times we want to iterate,
while the while loop is often used when we are iterating over a set of data and we don't know how
many times we need to iterate.
Write a Java program to print sum of digits of a given number?y

import java.util.Scanner;

public class SumOfDigits {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

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

int num = input.nextInt();

int sum = 0;

while (num != 0) {

int digit = num % 10;

sum += digit;

num /= 10;

System.out.println("The sum of digits is: " + sum);

}
Method Overloading:-The concept of function overloading helps developers to use same name for
different function blocks. The ambiguity while execution can be avoided by differentiating every
definition either by –

• Number of arguments passed OR

• Type of arguments passed to function.

Need of Function Overloading:-

In different situations we can prefer function overloading.

The one situation where there is need of writing function blocks where either process block is similar
but data type of arguments go on changing then we can use function overloading. For example
programmer need to write a program to add two

numbers where user need to add either two integers or float or double values depending on his
requirement. In case process is same for all function blocks, while only data type goes on changing.
In language like ‘c’, one need to write functions as sumInt(int a, int b), sumFloat(float a, float b),
sumDouble(double a, double b) for adding integer, float and double respectively. But in java by using
concept of function overloading functions can be written as sum(int a, int b), sum(float a, float b),
sum(double a, double b). In case of function overloading user of function need to remember only
name of the function as ‘sum’ instead of using different names for functions. It is shown in the
following program –

/Function overloading for different datatypes/ class FunOverload

public static int sum(int a,int b)

System.out.println("Function for Integers - "); int c=a+b; return(c);

public static float sum(float a,float b)

{System.out.println("Function for Floats - "); float c=a+b; return(c);

}public static double sum(double a,double b)

{System.out.println("Function for Doubles - "); double c=a+b; return(c);

}public static void main(String arg[])

{int s1=sum(5,3);

System.out.println("Sum of Integers : "+s1); float s2=sum(5.6F,8.9F); System.out.println("Sum of


Floats : "+s2); double s3=sum(5.67,8.93); System.out.println("Sum of Doubles : "+s3);

Output for the above program is shown in the command window given below. Here function ‘sum’
has three definitions with different data types. In
command window below we can observe how different functions get executed.

What is an interface? How to implement the concept of multiple inheritance?:-

In programming, an interface is a set of methods or properties that describe the behavior of an


object, without providing the implementation details. Interfaces are used to define a contract that a
class must adhere to if it wants to implement that interface. This allows for polymorphism, where
objects of different classes can be treated as if they belong to a common type.

To implement the concept of multiple inheritance using interfaces, you can define multiple
interfaces, each with a different set of methods and properties, and then have a class implement
multiple interfaces. This allows the class to inherit behavior from all of the interfaces it implements.

For example, consider the following interfaces:

interface IShape {

double calculateArea();

interface IColor {

String getColor();

These interfaces define behavior for shapes and colors. Now, let's say we have a class called
Rectangle that we want to inherit from both IShape and IColor. We can do this as follows:

class Rectangle implements IShape, IColor {

private double length;

private double width;

private String color;

public Rectangle(double length, double width, String color) {

this.length = length;

this.width = width;

this.color = color;

public double calculateArea() {

return length * width;

}
public String getColor() {

return color;

Here, Rectangle implements both IShape and IColor. It provides implementations for the
calculateArea and getColor methods defined in each interface, allowing it to inherit behavior from
both interfaces.

By implementing multiple interfaces, a class can inherit behavior from multiple sources, allowing for
greater flexibility and code reuse.
What is Constructor? Explain its special properties and types in detail?:-

In object-oriented programming, a constructor is a special method or function that is automatically


called when an object of a class is created. The purpose of the constructor is to initialize the object's
state or data members.

The main properties of a constructor are:

Name: The name of the constructor is always the same as the name of the class.

Access Modifiers: Constructors can have public, private, or protected access modifiers, just like other
methods in a class.

Return Type: Constructors do not have a return type, not even void, because they are called implicitly
when an object is created.

Parameters: Constructors can have parameters, which are used to initialize the object's data
members.

Overloading: Like other methods, constructors can also be overloaded, meaning that a class can have
multiple constructors with different parameter lists.

There are two types of constructors:

Default Constructor: A default constructor is a constructor that is automatically generated by the


compiler if a class does not have any explicit constructors defined. It does not take any parameters
and its body is empty, meaning that it does not perform any initialization. If a class has any data
members that need to be initialized, they will be initialized with default values (e.g. 0 for integers,
false for booleans, and null for object references).

Parameterized Constructor: A parameterized constructor is a constructor that takes one or more


parameters, which are used to initialize the object's data members. The advantage of a
parameterized constructor is that it allows you to create objects with different initial values, rather
than relying on default values. Parameterized constructors can be overloaded to provide different
ways of initializing objects.
Write a Java Program to check whether the given number is prime or not?

import java.util.Scanner;

public class PrimeChecker {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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

int num = scanner.nextInt();

boolean isPrime = true;

if (num <= 1) {

isPrime = false;

} else {

for (int i = 2; i <= Math.sqrt(num); i++) {

if (num % i == 0) {

isPrime = false;

break;

if (isPrime) {

System.out.println(num + " is a prime number.");

} else {

System.out.println(num + " is not a prime number.");

}
Design a class to represent a bank account. Create appropriate data members (12) and write
methods to perform following tasks:

a) Assign initial value to all data members using constructor.

b) Deposit an amount.

c) Withdraw an amount after checking balance.

d) Display the name and balance

Ans:-

public class BankAccount {

private String name;

private double balance;

// Constructor to initialize the name and balance

public BankAccount(String name, double balance) {

this.name = name;

this.balance = balance;

// Method to deposit an amount

public void deposit(double amount) {

balance += amount;

// Method to withdraw an amount after checking balance

public void withdraw(double amount) {

if (balance >= amount) {

balance -= amount;

} else {

System.out.println("Insufficient balance!");

// Method to display the name and balance

public void display() {

System.out.println("Name: " + name);


System.out.println("Balance: $" + balance);

Here's an example usage of this class:

BankAccount account = new BankAccount("John Doe", 1000.0);

account.deposit(500.0);

account.withdraw(200.0);

account.display();

This will output:

Name: John Doe

Balance: $1300.0

Exception Handling:-Exception handling is a mechanism in Java that allows developers to deal with
runtime errors and exceptional situations that may occur during program execution. It helps in
preventing the program from crashing and makes it more robust.

In Java, exceptions are objects that represent different types of runtime errors such as divide-by-zero,
null pointer, array out of bounds, etc. The try-catch block is used to handle exceptions in Java. The try
block contains the code that may cause an exception, while the catch block contains the code that
handles the exception.

Here is an example of exception handling in Java:

public class ExceptionExample {

public static void main(String[] args) {

try {

int a = 5 / 0; // division by zero

} catch (ArithmeticException e) {

System.out.println("Error: " + e.getMessage()); // handling the exception

}
Applet Lifecycle:-We have already discussed every applet application is derived from class Applet’
and it overrides methods defined in class ‘Applet’. These methods help developer to define state
specific behavior to applet application as well as to control applet execution. In this section we are
going to discuss about methods which define different life cycle events of an applet. These methods
help the browser or applet viewer interfaces to the applet and controls its execution. Four of these
methods are —

• init( ) – Here ‘init’ stands for initialization. It is the method from which applet execution starts. The
method is executed when applet is executed for the first time. Generally it is defined to initialize all
data members as it is executed only one time.

• start( ) – The method is executed right after execution of ‘init’ is completed as well as when the
control enter the applet. In multitasking systems when a control from one application returns to the
applet, the method is executed. Generally the method defines process to start or resume with an
application. Mostly the method defines process to start with animation.

• stop( ) – As opposite to ‘start’ the method is executed when the control changes to other
application from the applet application. It is executed to stop the thread of animation.

• destroy( ) – The method as opposite to ‘init’ and is executed when user closes the applet
application.

• paint( ) – The paint( ) method defined in AWT, is called each time your applet’s output must be
redrawn. This situation can occur for several reasons. For example, the window in which the applet is
running may be overwritten by another window and then uncovered. Or the applet window may be
minimized and then restored. paint( ) is also called when the applet begins execution. Whatever the
cause, whenever the applet must redraw its output, paint( ) is called. The paint( ) method has one
parameter of type Graphics. This parameter will contain the graphics context, which describes the
graphics environment in which the applet is running. This context is used whenever output to the
applet is required.
What is an array? Explain one dimensional array with example?

In computer programming, an array is a data structure that allows you to store multiple values of the
same data type in a single variable. Each value in the array is accessed by its index, which is an
integer value that represents the position of the element in the array.

A one-dimensional array is an array with only one level or one index. It is also called a single-
dimensional array. In Java, you can declare and initialize a one-dimensional array using the following
syntax:

datatype[] arrayName = new datatype[size];

Here, datatype is the type of data that the array will store, arrayName is the name of the array, and
size is the number of elements that the array can hold. For example, to declare and initialize an array
of integers with 5 elements, you can use the following code:

int[] numbers = new int[5];

This creates an array called numbers that can hold 5 integers. You can also initialize the array with
specific values using the following syntax:

datatype[] arrayName = {value1, value2, ..., valueN};

For example, to create an array of strings with 3 elements, you can use the following code:

String[] names = {"John", "Mary", "Bob"};

Here, the array called names contains three elements, each of which is a string value. The first
element is "John", the second is "Mary", and the third is "Bob". To access an element in the array,
you use the index of the element, like this:

int firstNumber = numbers[0];

String secondName = names[1];

In this example, firstNumber will be assigned the value of the first element in the numbers array
(which has an index of 0), and secondName will be assigned the value of the second element in the
names array (which also has an index of 1).

You might also like