[Go to site: main page, start]

0% found this document useful (0 votes)
122 views14 pages

Java Lab: String Operations and OOP

The document discusses Java programming concepts including string operations, classes and objects, method overloading and overriding, abstract classes, and exception handling. It provides code examples for each concept: 1. A string operations program demonstrates various string methods like charAt, compareTo, concat, etc. 2. A student class program stores details of 5 students using arrays and displays the total marks. 3. Method overloading and overriding programs illustrate defining multiple methods with the same name but different parameters and overriding a parent class method. 4. An abstract animal class program shows abstract and concrete methods, with dog and lion subclasses implementing the abstract methods. 5. An exception handling program demonstrates throwing and catching exceptions.

Uploaded by

Srinu Shahu
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)
122 views14 pages

Java Lab: String Operations and OOP

The document discusses Java programming concepts including string operations, classes and objects, method overloading and overriding, abstract classes, and exception handling. It provides code examples for each concept: 1. A string operations program demonstrates various string methods like charAt, compareTo, concat, etc. 2. A student class program stores details of 5 students using arrays and displays the total marks. 3. Method overloading and overriding programs illustrate defining multiple methods with the same name but different parameters and overriding a parent class method. 4. An abstract animal class program shows abstract and concrete methods, with dog and lion subclasses implementing the abstract methods. 5. An exception handling program demonstrates throwing and catching exceptions.

Uploaded by

Srinu Shahu
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
  • Lab 1: String Operations
  • Lab 2: Class and Object
  • Method Overloading and Method Overriding
  • Abstract Classes
  • Exception Handling
  • Packages
  • Interfaces
  • Threads
  • Priorities to Thread

OBJECT ORIENTED PROGRAMMING USING

JAVA LAB
Lab 1: String Operations
Aim:
To write a program to perform various String Operations
Description:
String: A string is the sequence of characters enclosed within double quotes.
Strings are very useful because most of the data on internet will be in the form
of strings only.
For example: name, vehicle number, address, credit card number etc. will
come under strings.
The following methods are uses to solve various string method classes and
various string buffer classes.

 charAt(index)
Give the charcater at the specified index.
 compareTo(str2)
Compare two strings and returns integer.( case sensitive)
 compareToIgnoreCase(str2)
Compare two strings and returns integer.( not case sensitive)
 equals(str2)
returns true if two strings are equal( case sensitive)
 equalsIgnoreCase(str2)
returns true if two strings are equal( not case sensitive)
 concat(str3)
combines string1 and string2
 toLowerCase()
Convert the given string to lower case.
 toUpperCase()
Convert the given string to lower case.
 length()
returns actual number of characters in the string buffer.
 trim()
remove the space from right and left side of a string.
 substring(start inex, end index)
Returns a substring from the starting index till the cahracter before the
end index.
 replace(character1,character2)
replace the character1 by character 2.
[Link] for various string operations

import [Link].*;
public class AllStringFuctionExample
{
public static void main(String[] args)
{
String str = "GM INFORMATICS ";
String str1= "LATEST JOB NEWS";
String str2= "latest job news";
String str3= "UG and PG Previous papers";
String tempstr = " String trimming example ";
[Link]("Character at the index 6 is :" + [Link](6));
[Link]("Compare b/w two strings :" + [Link](str2));
[Link]("Compare b/w two strings:" +
[Link](str2));
[Link]("Difference b/w two strings :" + [Link](str2));
[Link]("Difference b/w two strings :" +
[Link](str2));
[Link]("Concatenation of two strings :" + [Link](str3));
String Lowercase = [Link]();
[Link]("Lower case String :" + Lowercase);
String Uppercase = [Link]();
[Link]("Upper case String : " + Uppercase);
[Link]("Length of the given string :" + [Link]());
[Link]("String before trimming : " + tempstr);
[Link]("String after trimming : " + [Link]());
[Link]("String between index 3 to 9 is :"+ [Link](3, 9));
[Link]("Difference between two strings:" +
[Link]('J','M'));
[Link]("String after replacement :"+ [Link]("GM", "DM"));
}
}
Lab 2. Class and Object
Aim:
Write a program on class and object in java.
Description:
To write a java program to display total marks of 5 students using student class. Use the
following attributes HTNO, Name , Marks in 3 subjects Maths, Statistics/Physics, Computers
and Total.

2. Program for student Marks list


import [Link].*;
class Student
{
int HTNO,TOTAL;
String NAME;
int marks[]=new int[3];
void getDetails()
{
Scanner sc =new Scanner([Link]);
[Link]("Enter the Hall ticket Number");
HTNO=[Link]();
[Link]("Enter the name");
NAME=[Link]();
[Link]("Enter Marks in Maths");
marks[0]=[Link]();
[Link]("Enter marks Stat/Physics: ");
marks[1]=[Link]();
[Link]("Enter Marks in Computer science");
marks[2]=[Link]();
TOTAL=marks[0]+marks[1]+marks[2];
}
void display()
{
[Link](HTNO +"\t"+NAME + "\t" + marks[0] +"\t"
+marks[1]+ "\t"+marks[2]+"\t"+TOTAL);
}
}
class Marks
{
public static void main(String[] args)
{
Student s[]=new Student[5];
for(int i=0;i<5;i++)
{
s[i]=new Student();
s[i].getDetails();
}
[Link]("\t\t\t Marks List");
[Link]("****************************************");

[Link]("HTNO\tNAME\tMaths\tStat\tComputers\tTotal");
for(int i=0;i<5;i++)
s[i].display();
}
}

3. Method Overloading and Method Overriding


Aim:
Write a program to illustrate Function Overloading & Function Overriding methods in Java
Description:
Method: A function written in a class is called a method. In java we have only methods.
Method Overloading: Having the same name of method with different parameters is method
overloading. If we define multiple methods with the same name with different signatures in a
class, such concept is known as method overloading. The difference may be number of
parameters order of parameters and type of parameters. We implement polymorphism in java
using this concept.

Method Overriding: Having same type of methods same signature in the parent and child is
nothing but overriding.

Changing the definition of the class method in the sub class is known as method overriding.
Method overriding happens when classes are inheritance [Link] class method and sub
class method signatures should be the [Link] return type should be the same.
Program for Method overloading
class Areas
{
int l,b;
void setSides(int x)
{
l=b=x;
}
void setSides(int x,int y)
{
l=x;
b=y;
}
int getArea()
{
return l*b;
}
}
class ExMethodOverLoading
{
public static void main(String args[])
{
Areas sc1=new Areas();
[Link](3);
Areas sc2=new Areas();
[Link](4,5);
[Link]("Areas of the square"+[Link]());
[Link]("Areas of the rectangle"+[Link]());
}
}

Program for Method overriding


class RBI
{
public double getROI(){
return 10.5;
}
}
class SBI extends RBI
{
public double getROI()
{
return [Link]()-0.5;
}
public double calculateInterest(double p,double t)
{
return(p*t*getROI())/100;
}
public static void main(String args[])
{
SBI sbi=new SBI();
[Link]("SBI: "+[Link]());
}
}

4. Abstract classes
Aim:
Write a program to illustrate the implementation of abstract class
Description:
Abstract classes:
• These classes are used to provide abstraction in java.
• An abstract class should start with a keyword “abstract”.
• The abstract classes can contain both abstract methods and concrete
methods(implemented / non- implemented method)

Program for abstract class


abstract class Animal
{
public abstract String sound();
public abstract String nature();
public String walksWith()
{
return "By legs";
}
}
class Lion extends Animal
{
public String sound()
{
return "Roar Roar";
}
public String nature()
{
return "Wild Animal";
}
}
class Dog extends Animal
{
public String sound()
{
return "Bow Bow";
}
public String nature()
{
return "Domestic Animal";
}
}
public class AnimalTest
{
public static void main(String[] args)
{
//Animal a=new Animal();
//walksWith();
Dog d=new Dog();
Lion l=new Lion();
[Link]("=======Dog behaviour======");
[Link]("sounds like "+[Link]());
[Link]("Nature "+[Link]());
[Link]("Walks with "+[Link]());
[Link]("=========Lion behaviour=====");
[Link]("sounds like "+ [Link]());
[Link]("Nature "+[Link]());
[Link]("Walks with "+[Link]());
}
}
[Link] Hndling
Aim:
Write a program to implement Exception handling
Description:

Program for exception handling

import [Link].*;
class ExException
{
int i;
String fun()throws Exception
{
try
{
Scanner s1=new Scanner([Link]);
[Link]("Enter Amount:");
i=[Link]();
if(i<1000)
throw new Exception();
}
catch(Exception ee)
{
[Link]("catch block");
return "insufficient balance";
}
finally
{
[Link]("State Bank Of India");
}
return "sufficient balance";
}
public static void main(String args[])
{
try
{
ExException obj=new ExException();
[Link]([Link]());
}
catch(Exception ee)
{
[Link]("in main catch");
}
}
}

Program For Packages

/*Book detail class in Package Book*/


// javac -d . [Link]
package book;
public class BookDetails
{
String name,author;
float price;
int year;
public BookDetails(String n,String a,float p, int y)
{
name=n;
author=a;
price=p;
year=y;
}
public void display( )
{
[Link]("Book Name : "+name);
[Link]("Book Author : " +author);
[Link]("Book Price : " +price);
[Link]("Year of publishing : " +year);
}
}

/* Class that imports book package*/


import [Link];
class BookDemo
{
public static void main(String[] args)
{
BookDetails b=new BookDetails("java programming",
"Bala",190.00f,2007);
[Link]();
}
}

Program for Interface

interface AquaticAnimal
{
//String LivesIn="water";
String oceanName();
String eats();
boolean isLays();
}
class BlueWhale implements AquaticAnimal
{
public String oceanName()
{
return "Pacific";
}
public String eats()
{
return "Fishes and small creatures";
}
public boolean isLays()
{
return false;
}
}
class StarTortoise implements AquaticAnimal
{
public String oceanName()
{
return "Bay of bengal";
}
public String eats()
{
return "small creatures and under water plants";
}
public boolean isLays()
{
return true;
}
}
public class AquaticTest
{
public static void main(String[] args)
{
BlueWhale whale =new BlueWhale();
StarTortoise tot=new StarTortoise();
[Link]("Bluewhale behaviour");
[Link]("eats "+[Link]());
[Link]("Lays eggs "+[Link]());
[Link]("available in"+[Link]());
[Link]("=====================");

[Link]("Tortoise behaviour");
[Link]("eats "+[Link]());
[Link]("Lays eggs "+[Link]());
[Link]("available in"+[Link]());
[Link]("=====================");
}
}

Program for multiple Threads

class MyThreadOne extends Thread


{
public void run( )
{
for(int i=1;i<=20;i++)
[Link]("Hello");
}
}
class MyThreadTwo extends Thread
{
public void run( )
{
for(int i=1;i<=20;i++)
[Link]("Hai");
}
}
class MultiThreadingExample
{
public static void main(String[] args)
{
MyThreadOne t1=new MyThreadOne( );
MyThreadTwo t2= new MyThreadTwo( );
[Link]();
[Link]();
[Link]("This is Mahesh");
}
}

Program for Multiple Inheritance


abstract class Animal
{
public abstract String sound();
public abstract String nature();
public void walksWith()
{
[Link]("By legs");
}
}
interface AquaticAnimal
{
String LivesIn="water";
String oceanName();
String eats();
boolean isLays();
}

class BlueWhale extends Animal implements AquaticAnimal


{
public String oceanName(){
return "Pacific";
}
public String eats(){
return "Fishes and small creatures";
}
public boolean isLays(){
return false;
}
public String sound()
{
return "Queek Queek";
}
public String nature()
{
return "Wild nature";
}
}
class ExMultipleInheritance
{
public static void main(String[] args)
{
BlueWhale whale =new BlueWhale();
StarTortoise tot=new StarTortoise();
[Link]("Bluewhale behaviour");
[Link]("eats "+[Link]());
[Link]("Lays eggs "+[Link]());
[Link]("available in"+[Link]());
[Link]("Sounds like"+[Link]());
[Link]("Nature"+[Link]());
[Link]("Lives in "+[Link]);
[Link]("=====================");

}
}
Program for Priorities to thread

class TestMultiPriority extends Thread{

public void run(){

[Link]("running thread name


is:"+[Link]().getName());

[Link]("running thread priority


is:"+[Link]().getPriority());

public static void main(String args[]){

TestMultiPriority m1=new TestMultiPriority();

TestMultiPriority m2=new TestMultiPriority();

[Link](Thread.MIN_PRIORITY);

[Link](Thread.MAX_PRIORITY);

[Link]();

[Link]();

Common questions

Powered by AI

Interfaces and abstract classes both provide ways to achieve abstraction in Java, but they differ significantly. Interfaces declare methods that must be implemented by classes but cannot hold implementation details themselves, making them suitable for defining capabilities or contracts across unrelated classes. Abstract classes, conversely, can hold both abstract and concrete methods, allowing for more flexible design with shared code implementation. Interfaces are ideal when different classes need to implement similar functionalities in diverse class hierarchies, while abstract classes are preferable when creating a common base across closely related classes with shared behavior .

Abstraction in object-oriented programming involves simplifying complex systems by modeling classes based on essential characteristics while hiding unnecessary details. It allows developers to focus on higher-level operations by defining clear interfaces through methods and abstract classes. This reduces complexity and enhances code manageability by emphasizing what objects do rather than how they do it, leading to systems that are easier to extend, maintain, and use efficiently, ultimately increasing development productivity .

Java packages allow developers to group related classes and interfaces into namespaces, which helps organize files within a project hierarchically. This organization facilitates the modular development of applications, making code easier to manage, navigate, and understand. Packages help avoid name conflicts by providing namespace management and allow controlled access to classes with tools for scope and encapsulation, contributing to cleaner, more maintainable, and scalable codebases .

Exception handling in Java is essential for managing runtime errors, ensuring that a program executes smoothly without unexpected termination. By catching and managing exceptions, Java programs can handle errors gracefully, providing informative messages or alternative actions instead of crashing. This enhances program reliability by maintaining control flow even when unforeseen issues arise, such as user input errors or resource access problems, thus improving user experience and system robustness .

Method overriding in Java enables a subclass to provide a specific implementation of a method that is already defined in its superclass. This demonstrates runtime polymorphism, allowing the Java runtime to invoke the correct overridden method based on the object's actual type rather than its reference type. The primary benefit in an inheritance hierarchy is flexibility; it allows subclass objects to interact with superclass references using their specialized methods, resulting in reusable code while allowing individual customization .

In Java, the 'compareTo' method is used to lexicographically compare two strings and returns an integer indicating their order, which is useful for sorting or ordering strings. It is case-sensitive, distinguishing between uppercase and lowercase. On the other hand, the 'equals' method checks for literal equality between two strings, returning a boolean value. Unlike 'compareTo', 'equals' is intended to determine if two strings have identical characters in the same sequence and can also be used in a case-insensitive manner using 'equalsIgnoreCase'. Each method serves distinct purposes within string manipulation: 'compareTo' for ordering operations and 'equals' for equality checks .

Java's multithreading capabilities enable concurrent execution of two or more parts of a program, which can significantly improve performance and responsiveness. By allowing multiple threads to run simultaneously, applications can perform long-running operations like data processing or network communication while remaining responsive to user interactions, enhancing user experience. Multithreading also maximizes CPU utilization by keeping threads busy with tasks, thereby reducing idle time and increasing the efficiency of resource allocation .

Method overloading in Java allows multiple methods to have the same name with different parameters within a class. This promotes polymorphism, enabling the same method to perform different functions based on the input parameters' types and numbers. The benefits of method overloading include improved code readability and organization, as multiple operations that serve similar purposes can be grouped under a single method name. Additionally, it simplifies the interface of a class for users, allowing them to interact with methods using a uniform approach .

Abstract classes in Java serve as a blueprint for other classes. They cannot be instantiated on their own and must be subclassed. Abstract classes allow the definition of abstract methods, which must be implemented in derived classes, thereby enforcing a contract for subclasses. This enables polymorphism, as objects can be treated as instances of their abstract superclass, allowing for the abstraction of implementation details and facilitating the flexibility and scalability of code through a uniform interface .

Java's multithreading provides concurrency by allowing multiple threads to execute simultaneously, which lets applications handle multiple tasks in parallel, such as processing user interactions while running background processes. This concurrency enhances application responsiveness and performance. However, it also introduces challenges such as thread synchronization, which is necessary to prevent data inconsistency and race conditions when multiple threads access shared resources. Developers must carefully manage thread life cycles and resource allocation to avoid deadlocks and ensure safe thread interactions, making it an advanced and careful task .

OBJECT ORIENTED PROGRAMMING USING 
JAVA LAB 
Lab 1: String Operations 
Aim:  
To write a program to perform various String Op
1.Program for various string operations 
import java.util.*; 
public class AllStringFuctionExample  
 
{ 
 
 
public static v
Lab 2. Class and Object 
 
Aim:  
Write a program on class and object in java. 
Description: 
To write a java program to disp
public static void main(String[] args)  
 
{ 
 
 
Student s[]=new Student[5]; 
 
 
for(int i=0;i<5;i++) 
 
 
{ 
 
 
 
s[i]=
Program for Method overloading 
class Areas 
{ 
 
int l,b; 
 
void setSides(int x) 
 
{ 
 
 
l=b=x; 
 
} 
 
void setSides(int
}  
 
public double calculateInterest(double p,double t) 
 
{ 
 
 
return(p*t*getROI())/100; 
 
} 
 
public static void m
{ 
 
 
 
return "Wild Animal"; 
 
 
} 
 
} 
 
class  Dog extends Animal 
 
{ 
 
 
public String sound() 
 
 
{ 
 
 
 
ret
5.Exception Hndling 
Aim:  
Write a program to implement Exception handling  
Description:  
 
 
 
 
 
Program for exception
ExException obj=new ExException(); 
          System.out.println(obj.fun()); 
          } 
           catch(Excepti
{ 
 
public static void main(String[] args)  
 
{ 
             BookDetails b=new BookDetails("java programming", 
"Bala",190

You might also like