0% found this document useful (0 votes)
27 views24 pages

SBLJava Lab Manual 24-25 Journal Theory

Uploaded by

Prince Kaswala
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)
27 views24 pages

SBLJava Lab Manual 24-25 Journal Theory

Uploaded by

Prince Kaswala
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/ 24

Experiment 1

Programs on Basic programming constructs like branching and looping

Theory:
Branching

Branching in programming refers to the ability of a program to alter its execution path based on
certain conditions. This is crucial for making decisions within the program. The primary branching
statements in Java are if, else if, else, and switch.

1. If-Else Statement

The if statement is used to execute a block of code if a specified condition is true. The else
statement can be used to execute an alternative block of code if the condition is false.

Syntax:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}

2. Switch Statement

The switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each case.

Syntax:
switch (variable) {
case value1:
// code to be executed if variable == value1
break;
case value2:
// code to be executed if variable == value2
break;
// more case statements
default:
// code to be executed if variable doesn't match any case
}
Looping

Looping is a fundamental concept in programming that allows a block of code to be executed


repeatedly based on a condition. There are different types of loops in Java: for, while, and
do-while.

1. For Loop

The for loop is typically used when the number of iterations is known before entering the loop. It
consists of three parts: initialization, condition, and increment/decrement.

Syntax:
for (initialization; condition; update) {
// code to be executed
}

2. While Loop

The while loop repeats a block of code as long as a specified condition is true. It checks the
condition before executing the block of code.

Syntax:
while (condition) {
// code to be executed
}

3. Do-While Loop

The do-while loop is similar to the while loop, but it checks the condition after executing the
block of code, ensuring that the code is executed at least once.

Syntax:
do {
// code to be executed
} while (condition);
Experiment 2

Programs on accepting user input

Theory:

Command-Line Arguments in Java


Command-line arguments are a way to pass information to a program when it starts. They are
typically used to provide input data, configuration options, or other parameters that the program
needs to execute. In Java, command-line arguments are passed to the main method as an array of
String objects.

How Command-Line Arguments Work


When a Java program is started from the command line, any additional tokens (separated by
spaces) provided after the program name are passed to the main method as an array of String
objects. Each element of the array represents one command-line argument.

Syntax:
public static void main(String[] args) {
// args is the array of command-line arguments
}

Accessing Command-Line Arguments

The args array can be used to access command-line arguments. For example, args[0] refers to the
first command-line argument, args[1] refers to the second, and so on. The length of the args
array can be checked using args.length to determine how many arguments were passed.

Scanner

The Scanner class in Java is a part of the java.util package and is widely used for parsing
primitive types and strings using regular expressions. It provides a simple and effective way to
read input from various sources like input streams, strings, or files.
The Scanner class provides various methods to read different types of input:
● nextInt(): Reads an integer.
● nextDouble(): Reads a double.
● nextLine(): Reads a line of text (until a newline character).
● next(): Reads the next token (until whitespace).
BufferedReader

The BufferedReader class in Java is part of the java.io package and is used for reading
text from an input stream, efficiently buffering characters to provide fast input operations. It is
commonly used when you need to read large amounts of data or lines of text from a file or the
console. Here, we will cover the theory on using the BufferedReader class for accepting user
input in Java.

The BufferedReader class provides the readLine() method to read a line of text. It returns
a String containing the contents of the line, excluding any line-termination characters
Experiment 3

Program on 2D array, strings functions

Theory:

2D Arrays in Java

A 2D array in Java is essentially an array of arrays, allowing data to be stored in a tabular form
with rows and columns. Each element in a 2D array is accessed using two indices: the first for the
row and the second for the column. This structure is particularly useful for representing matrices,
grids, and other multi-dimensional data structures. For example, a 2D array can be used to
represent a chessboard, a spreadsheet, or a table of data. In Java, 2D arrays are declared and
initialized using syntax such as int[][] arrayName = new int[rows][columns];.

Strings in Java

Strings in Java are objects of the String class, which represents a sequence of characters. Unlike
primitive data types, strings are immutable, meaning once a String object is created, its value
cannot be changed. The String class provides numerous methods for string manipulation,
including concatenation (concat or + operator), length (length), substring extraction
(substring), character replacement (replace), case conversion (toUpperCase,
toLowerCase), and searching (indexOf, contains). Strings are widely used for text
processing, storing user input, and communication between different parts of a program.
Experiment 4

Program on StringBuffer and Vectors

Theory:
StringBuffer Class:

The StringBuffer class in Java is used to create mutable (modifiable) strings. Unlike
String, which is immutable, StringBuffer can be changed after it is created. This makes
StringBuffer more efficient for performing multiple string modifications, such as appending,
inserting, or reversing characters.

Key Features:

● Mutable Strings: StringBuffer objects can be modified after creation, which makes them
suitable for scenarios where strings need to be altered frequently.
● Thread-Safe: Methods of StringBuffer are synchronized, which makes it thread-safe.
Multiple threads can access a StringBuffer object without causing data inconsistency.
● Performance: While StringBuffer is thread-safe, it may be slower than
StringBuilder (which is not synchronized) due to the overhead of synchronization.

Common Methods:

● append(String s): Appends the specified string to the end of the current
StringBuffer.
● insert(int offset, String s): Inserts the specified string at the specified position.
● reverse(): Reverses the sequence of characters in the StringBuffer.
● delete(int start, int end): Removes the characters in a substring of the
StringBuffer.
● replace(int start, int end, String str): Replaces the characters in a
substring with the specified string.
● capacity(): Returns the current capacity of the StringBuffer.

Vector Class:
The Vector class in Java is a part of the Java Collection Framework. It implements a growable
array of objects. Like an array, it contains components that can be accessed using an integer index.
However, the size of a Vector can grow or shrink as needed to accommodate adding and
removing items.

Key Features:

● Resizable Array: Vector can dynamically grow and shrink in size as elements are added
or removed.
● Thread-Safe: Methods of Vector are synchronized, which makes it thread-safe. Multiple
threads can safely access a Vector object.
● Legacy Class: Vector is considered a legacy class and is largely replaced by
ArrayList in modern applications due to performance reasons.
Common Methods:

● add(E e): Appends the specified element to the end of the Vector.
● add(int index, E element): Inserts the specified element at the specified position.
● remove(Object o): Removes the first occurrence of the specified element.
● remove(int index): Removes the element at the specified position.
● get(int index): Returns the element at the specified position.
● set(int index, E element): Replaces the element at the specified position with the
specified element.
● size(): Returns the number of elements in the Vector.
Experiment 5

Programs on class and objects

Theory:

Classes and Objects in Java

In Java, the concepts of classes and objects are fundamental to object-oriented programming
(OOP). They allow for the modeling of real-world entities and the structuring of complex software
systems.

Class

A class is a blueprint or template for creating objects. It defines the attributes (fields) and
behaviors (methods) that the objects created from the class can have. A class can include:

● Fields (Variables): These represent the data or state of the class.


● Methods: These represent the actions or behaviors that the objects of the class can perform.
● Constructors: These are special methods used to initialize objects of the class.

Object

An object is an instance of a class. It is a real-world entity that has state and behavior. Objects are
created from classes, and they interact with one another in a program to perform operations and
solve problems.

Creating an Object:
ClassName objectName = new ClassName(parameters);
Experiment 6

Program on method and constructor overloading

Theory:

Method and Constructor Overloading

Overloading is a feature in Java that allows a class to have more than one method or constructor
with the same name, as long as their parameter lists are different. It increases the readability of the
program by allowing the same operation to be performed with different types of inputs.

Method Overloading:

Method overloading in Java allows a class to have more than one method with the same name, as
long as their parameter lists are different. The methods can have different numbers of parameters,
different types of parameters, or both. Method overloading is a compile-time polymorphism
concept where the appropriate method is selected based on the method signature.

Key Points:

● Method Signature: Method overloading is based on the method signature, which includes the
method name and the parameter list.
● Return Type: Method overloading cannot be achieved by changing only the return type of the
method.
● Parameters: Overloaded methods must have different parameter lists (different types,
numbers, or both).
● Compile-Time Polymorphism: Method overloading is resolved at compile time, meaning the
method call is bound to the method body based on the argument list during compilation.

Constructor Overloading:

Constructor overloading in Java allows a class to have more than one constructor with different
parameter lists. Like method overloading, constructor overloading is also based on the number and
type of parameters. Overloaded constructors provide different ways to initialize an object.

Key Points:

● Different Parameter Lists: Overloaded constructors must have different parameter lists.
● No Return Type: Constructors do not have a return type, not even void.
● Initialization: Each overloaded constructor provides a different way to initialize an object of
the class.
● Constructor Chaining: Constructors can call each other using this() to avoid code
duplication and to maintain a single point of initialization.
Experiment 7

Program on single inheritance

Theory:
Single Inheritance:

Single inheritance in Java is a mechanism where a class (subclass or derived class) inherits fields
and methods from another class (superclass or base class). This allows the subclass to reuse code,
making it easier to maintain and extend. Java supports single inheritance, meaning a class can
inherit directly from only one superclass.

Key Concepts:

● Inheritance:

Definition: Inheritance is a fundamental principle of object-oriented programming (OOP)


that allows one class to inherit properties and methods from another class.

Syntax: The extends keyword is used to inherit from a superclass.

class Subclass extends Superclass {


// additional fields and methods
}

● Constructors in Inheritance:

Superclass Constructor: When an object of a subclass is created, the constructor of the


superclass is called first to initialize the inherited fields.

Calling Superclass Constructor: The super() keyword is used within the subclass
constructor to explicitly call the superclass constructor.

public Subclass(parameters) {
super(arguments); // calls the superclass constructor
// additional initialization
}

● Method Overriding:

Definition: Method overriding occurs when a subclass provides a specific implementation


for a method that is already defined in its superclass.

Rules:

● The method in the subclass must have the same name, return type, and parameters
as the method in the superclass.

Purpose: Method overriding allows for dynamic method dispatch, enabling polymorphism.
It ensures that the correct method is called based on the object's runtime type.
Experiment 8

Program on hierarchical inheritance

Theory:
Hierarchical Inheritance:

Hierarchical inheritance in Java is a type of inheritance where multiple subclasses inherit from a
single parent class. This means that a single class (parent class) serves as a base class for more
than one subclass. Each subclass inherits the properties and methods of the parent class, and can
also have its own unique properties and methods. Hierarchical inheritance is useful for creating a
clear and logical class hierarchy and reusing code efficiently.

Key Points:

1. Single Parent, Multiple Children:


In hierarchical inheritance, one parent class can have multiple child classes. Each child
class inherits the properties and methods of the parent class.

2. Code Reusability:
Hierarchical inheritance promotes code reusability by allowing subclasses to use the
common functionality defined in the parent class.

3. Class Hierarchy:
This type of inheritance helps to organize classes in a hierarchical structure, making the
code more manageable and easier to understand.

4. Method Overriding:
Subclasses can override the methods of the parent class to provide specific
implementations. This allows for polymorphism, where the same method can have
different behaviors in different subclasses.

5. Super Keyword:
The super keyword can be used in subclasses to call methods and constructors of the
parent class. This helps in accessing the inherited methods that have been overridden.

Example:
// Parent class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}

void sleep() {
System.out.println("This animal sleeps.");
}
}

// Subclass Dog
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
// Subclass Cat
class Cat extends Animal {
void meow() {
System.out.println("The cat meows.");
}
}

// Subclass Bird
class Bird extends Animal {
void fly() {
System.out.println("The bird flies.");
}
}
Experiment 9

Program on abstract class and abstract methods

Theory:
Abstract Classes:

An abstract class in Java is a class that cannot be instantiated on its own and is meant to be
subclassed. Abstract classes are used to provide a common base and to define methods that must
be implemented by subclasses. They can contain both abstract methods (methods without a body)
and concrete methods (methods with a body).

Key Points:

1. Cannot be Instantiated:
You cannot create an instance of an abstract class directly. They are meant to be extended
by other classes.

2. Can Contain Abstract and Concrete Methods:


Abstract classes can have methods that are fully implemented and methods that are
declared without an implementation (abstract methods).

3. Subclass Responsibility:
Subclasses of an abstract class are responsible for providing implementations for all the
abstract methods declared in the abstract class.

If a subclass does not implement all the abstract methods, it must also be declared abstract.

4. Use of abstract Keyword:


The abstract keyword is used to declare an abstract class and its abstract methods.

Abstract Methods:

Abstract methods are methods that are declared without an implementation (without a body) in an
abstract class. These methods must be implemented by subclasses of the abstract class.

Key Points:

1. No Implementation in Abstract Class:


Abstract methods do not have a body in the abstract class. The method signature is followed by
a semicolon instead of curly braces.

2. Must be Overridden:
Subclasses must override abstract methods and provide their own implementations. If they do
not, the subclass must also be declared abstract.

3. Cannot be static, final, or private:


Abstract methods cannot be declared as static, final, or private because they need to
be overridden in subclasses.
Experiment 10

Program using super and final keyword

Theory:
super Keyword:

The super keyword in Java is used to refer to the immediate parent class of an object. It provides
a way to access members (methods and variables) of the parent class that have been hidden or
overridden by the subclass. The super keyword can be used in three main contexts:

1. Calling the Superclass Constructor:


○ When a subclass is instantiated, its constructor can call the constructor of the parent class
using super(). This is useful for initializing inherited fields.
○ If a superclass constructor requires arguments, the super call must match its parameter
list.
○ The super() call must be the first statement in the subclass constructor.

2. Calling the Superclass Method:


○ The super keyword can be used to call a method from the superclass that has been
overridden in the subclass.

3. Accessing Superclass Fields:


○ If a subclass has a field with the same name as one in its superclass, super can be used to
access the superclass's field.

final Keyword:

The final keyword in Java is used to apply restrictions on classes, methods, and variables. The
final keyword ensures immutability and prevents modification.

1. Final Variables:
○ A final variable can only be initialized once, either when it is declared or in the constructor.
After initialization, its value cannot be changed.

2. Final Methods:
○ A final method cannot be overridden by subclasses. This is used to prevent altering the
intended behavior of the method.

3. Final Classes:
○ A final class cannot be subclassed. This is used to prevent inheritance and to ensure that the
class's behavior remains unchanged.
Experiment 11

Program on Packages

Theory:
Packages are used in Java in order to make searching/locating and usage of classes, interfaces,
enumerations easier, to prevent naming conflicts and to control access.

Some of the existing packages in Java are::


java.lang - bundles the fundamental classes
java.io - classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle groups of classes/interfaces etc. It is a good
practice to group related classes implemented by you so that programmers can easily determine
that the classes, interfaces, enumerations, annotations are related.

Creating a package:
When creating a package, you should choose a name for the package and put a package statement
with that name at the top of every source file that contains the classes, interfaces, enumerations,
and annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package
statement in each source file, and it applies to all types in the file.

Syntax:
package packageName;

The import Keyword:


If a class wants to use another class in the same package, the package name does not need to be
used. Classes in the same package find each other without any special syntax.

Syntax:
import packageName.*;

The class itself can be imported using the import keyword. For example:
import packageName.className;

Note: A class file can contain any number of import statements. The import statements must appear after
the package statement and before the class declaration.
Experiment 12

Program on array of objects

Theory:

Array of Objects

Arrays are capable of storing objects also. For example, we can create an array of Strings which is
a reference type variable. However, using a String as a reference type to illustrate the concept of
array of objects isn't too appropriate due to the immutability of String objects. Therefore, for this
purpose, we will use a class Student containing a single instance variable marks. Following is the
definition of this class.
class Student {
int marks;
}

An array of objects is created just like an array of primitive type data items in the following way.
Student[] studentArray = new Student[7];

The above statement creates the array which can hold references to seven Student objects.
It doesn't create the Student objects themselves. They have to be created separately using the
constructor of the Student class. The studentArray contains seven memory spaces in which the
address of seven Student objects may be stored. If we try to access the Student objects even before
creating them, run time errors would occur. For instance, the following statement throws a
NullPointerException during runtime which indicates that studentArray[0] isn't yet pointing to a
Student object.
studentArray[0].marks = 100;

The Student objects have to be instantiated using the constructor of the Student class and their
references should be assigned to the array elements in the following way.
studentArray[0] = new Student();

In this way, we create the other Student objects also. If each of the Student objects have to be
created using a different constructor, we use a statement similar to the above several times.
However, in this particular case, we may use a for loop since all Student objects are created with
the same default constructor.
for ( int i=0; i<studentArray.length; i++) {
studentArray[i]=new Student();
}

The above for loop creates seven Student objects and assigns their reference to the array elements.
Now, a statement like the following would be valid.
studentArray[0].marks=100;

Enhanced for loops find a better application here as we not only get the Student object but also we
are capable of modifying it. This is because of the fact that Student is a reference type. Therefore
the variable in the header of the enhanced for loop would be storing a reference to the Student
object and not a copy of the Student object which was the case when primitive type variables like
int were used as array elements.
for ( Student x : studentArray ) {
x.marks = s.nextInt(); // s is a Scanner object
}

Recall that we were not able to assign to the array elements in a similar way when the array was of
type int.

Moreover, in the case of an array of objects, when we pass an array element to a method, the
object is susceptible to changes. This is because the element being passed is also a reference type
item.
Experiment 13
Program on Exception handling

Theory:

What are Exceptions?

An exception in Java is an event that disrupts the normal flow of the program's instructions. It is an
object that wraps an error event which can be thrown and caught by the program. Exceptions are
used to handle errors and other exceptional events in a controlled manner.

Exception Handling Mechanisms


Java provides several keywords to handle exceptions:

1. try-catch:
○ The try block contains the code that might throw an exception.
○ The catch block contains the code that handles the exception.
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}

2. finally:
○ The finally block contains the code that is always executed after the try block, regardless of
whether an exception was thrown or not. It is typically used to release resources.
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that is always executed
}

3. throw:
○ The throw keyword is used to explicitly throw an exception.
throw new ExceptionType("Error message");

4. throws:
○ The throws keyword is used in the method signature to declare that a method might throw
exceptions.
public void methodName() throws ExceptionType {
// Method code
}
User-Defined Exceptions
In addition to the predefined exceptions, Java allows you to create your own exceptions. This is
useful when you want to handle specific error conditions in your application.

Creating a User-Defined Exception

1. Define the Exception Class:


○ Create a class that extends the Exception class (or any subclass of it).

class InvalidAgeException extends Exception {


public InvalidAgeException(String message) {
super(message);
}
}

2. Throw the User-Defined Exception:


○ Use the throw keyword to throw the exception when a specific condition is met.

public class UserDefinedExceptionExample {


public static void validateAge(int age) throws
InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age is less than 18.
Access denied.");
}
}
}

3. Handle the User-Defined Exception:


○ Use a try-catch block to catch and handle the user-defined exception.

public class Main {


public static void main(String[] args) {
try {
UserDefinedExceptionExample.validateAge(15);
} catch (InvalidAgeException e) {
System.out.println("Caught the exception: " +
e.getMessage());
}
}
}
Experiment 14

Program on Multithreading

Theory:

Threads

Java provides built-in support for multithreaded programming. A multithreaded program contains
two or more parts that can run concurrently. Each part of such a program is called a thread, and
each thread defines a separate path of execution. A multithreading is a specialized form of
multitasking. Multithreading requires less overhead than multitasking processing. I need to define
another term related to threads: process: A process consists of the memory space allocated by the
operating system that can contain one or more threads. A thread cannot exist on its own; it must be
a part of a process. A process remains running until all of the non-daemon threads are done
executing. Multithreading enables you to write very efficient programs that make maximum use of
the CPU, because idle time can be kept to a minimum.

Life Cycle of a Thread:

A thread goes through various stages in its life cycle. For example, a thread is born, started, runs,
and then dies. Following diagram shows the complete life cycle of a thread.

Above mentioned stages are explained here:


● New : When an instance of thread is created using the new operator it is in the new state,
but the start() method has not been invoked on the thread yet, so the thread is not eligible to
run yet. Thread object is created but the thread is not alive yet.

● Runnable : When the start() method is called on a thread it enters the runnable state.
As soon as Thread enters the runnable state it is eligible to run, but not running. (Thread
scheduler has not scheduled the Thread execution yet, Thread has not entered in the
run() method yet). A thread first enters the runnable state when the start() method is
invoked, but a thread can also return to the runnable state after either running or coming
back from a blocked, waiting, or sleeping state. Thread is considered alive in runnable
state.

● Running : Thread scheduler selects thread to go from runnable to running state. In the
running state Thread starts executing by entering run() method. Thread scheduler selects
a thread from the runnable pool on the basis of priority, if priorities of two threads are
same, threads are scheduled in unpredictable manner. Thread scheduler behaviour is
completely unpredictable.

● Waiting/blocked/sleeping : In this state a thread is not eligible to run. Thread is still alive,
but currently it’s not eligible to run. Thread also may go from running to waiting state if it
is waiting for some I/O operation to take place. Once input is available, the thread may
return to the runnable state.

Creating a Thread:
Java defines two ways in which this can be accomplished:
● You can implement the Runnable interface.
● You can extend the Thread class, itself.

What is Thread Synchronization?

Thread synchronization in Java is a mechanism to control the access of multiple threads to shared
resources. Synchronization helps prevent thread interference and memory consistency errors,
ensuring that the shared resource is accessed by only one thread at a time.

Why is Synchronization Needed?

When multiple threads access shared resources concurrently, it can lead to inconsistent data or
unexpected behavior. This is often referred to as a race condition. Synchronization is needed to
ensure that only one thread accesses the critical section of code (the part of the program that
accesses shared resources) at a time, preventing race conditions.

Types of Synchronization

1. Mutual Exclusion (Mutex): Ensures that only one thread executes a critical section at a
time.
2. Cooperation (Coordination): Ensures that threads cooperate or coordinate their actions,
especially useful in producer-consumer scenarios.
Experiment 15

Program to create GUI application

Theory:

Applets in Java

An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java
application because it has the entire Java API at its disposal. There are some important differences
between an applet and a standalone Java application, including the following:

● An applet is a Java class that extends the java.applet.Applet class.


● A main() method is not invoked on an applet, and an applet class will not define main().
● Applets are designed to be embedded within an HTML page.
● When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
● A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser
or a separate runtime environment.
● The JVM on the user's machine creates an instance of the applet class and invokes various
methods during the applet's lifetime.
● Applets have strict security rules that are enforced by the Web browser. The security of an
applet is often referred to as sandbox security, comparing the applet to a child playing in a
sandbox with various rules that must be followed.
● Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.

Life Cycle of an Applet:


Initialization (init method):

● This method is called once when the applet is first loaded. It is used for initial setup, such as
initializing variables, loading resources, etc.
● public void init()

Starting (start method):

● This method is called after init and every time the applet is restarted. It is typically used to start or
resume applet execution, such as starting animations or threads.
● public void start()

Stopping (stop method):

● This method is called when the applet is stopped. It is used to suspend any ongoing activity, such
as stopping animations or threads.
● public void stop()

Destruction (destroy method):

● This method is called once when the applet is being destroyed. It is used to clean up resources,
such as closing files or network connections.
● public void destroy()

Painting (paint method):

● This method is called whenever the applet needs to repaint its output. It is used for drawing
graphics on the applet's window.
● public void paint(Graphics g)

You might also like