[Go to site: main page, start]

0% found this document useful (0 votes)
8 views20 pages

Java Object-Oriented Programming Examples

The document provides a series of Java programming examples demonstrating various concepts such as classes, constructors, command line arguments, random number generation, vectors, string manipulation, inheritance, interfaces, exception handling, threading, packages, and applets. Each example includes source code, expected output, and explanations of the functionality. These examples serve as practical illustrations for understanding Object-Oriented Programming in Java.

Uploaded by

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

Java Object-Oriented Programming Examples

The document provides a series of Java programming examples demonstrating various concepts such as classes, constructors, command line arguments, random number generation, vectors, string manipulation, inheritance, interfaces, exception handling, threading, packages, and applets. Each example includes source code, expected output, and explanations of the functionality. These examples serve as practical illustrations for understanding Object-Oriented Programming in Java.

Uploaded by

anusuuyaam
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Objected Oriented Programming in Java

1) Program Using class and object

Source Code:
import [Link].*;
class lamp
{
boolean ison;
void turnon()
{
ison=true;
[Link]("Light on?"+ison);
}
void turnoff()
{
ison=false;
[Link]("Light on?"+ison);
}
public static void main(String[] args)
{
lamp led =new lamp();
lamp halogen =new lamp();
[Link]();
[Link]();
}
}

OUTPUT:

Light on?true
Light on?false
2)Program Using Constructor

Source Code:

import [Link].*;
class student
{
int rollno;
String name;
student(int rollno,String name)
{
[Link]=rollno;
[Link]=name;
}
public static void main(String[] args)
{
student st=new student(01,"Bhooshi");
[Link]("studentname="+[Link]+" student rollno"+[Link]);
}
}

OUTPUT:

studentname=Bhooshi student rollno1


3) Program Using Command Line Arguments

Source Code:

import [Link].*;
class command
{
public static void main(String[] args)
{
[Link]("command line Arguments");
[Link]("The given String are");
for(String str:args)
{
[Link](str);
}
}
}

OUTPUT:

Execute :java command args1 args2 args0

command line Arguments


The given String are
args1
args2
args0
4)Program Using Random Class

Source Code:

import [Link];
class generaterandom
{
public static void main(String[] agrs)
{
Random random=new Random();
[Link]("A random int:"+[Link]());
[Link]("A random int from 0 to 49:"+[Link](50));
[Link]("A random double:"+[Link]());
[Link]("A random float:"+[Link]());
[Link]("A random long:"+[Link]());
}
}

OUTPUT:

A random int:-575546384
A random int from 0 to 49:9
A random double:0.9877748287289448
A random float:0.26873827
A random long:3476157426425303757
5) Program using Vector

Source Code:
import [Link];
class v
{
public static void main(String[] args)
{
Vector<String> vec=new Vector<>();
[Link]("Tiger");
[Link]("Dog");
[Link]("Lion");
[Link]("Deer");
[Link]("Elepahant");
[Link]("Rat");
[Link]("Cat");
[Link]("Elements in the vector:"+vec);
[Link]("Size of vector:"+[Link]());
[Link]("Deer");
[Link]("Elements in the vector after deletion:"+vec);
}
}

OUTPUT:

Elements in the vector:[Tiger, Dog, Lion, Deer, Elepahant, Rat, Cat]


Size of vector:7
Elements in the vector after deletion:[Tiger, Dog, Lion, Elepahant, Rat, Cat]
6) Program using String Tokenizer

Source code:
import [Link];
public class TD1
{
public static void main(String[] args)
{
StringTokenizer obj = new StringTokenizer("Welcome to study tonight");
while([Link]())
{
[Link]([Link]());
}
}
}

OUTPUT:
Welcome
to
study
tonight
7) Program Using Single Inheritance

Source Code:
import [Link].*;
class personaldetails
{
void display()
{
[Link]("Student Name: Bhooshitha");
[Link]("Phone Number:9488614140");
[Link]("Place:Gobi");
}
}
class academydetails extends personaldetails
{
void display1()
{
[Link]("Collage:Gobi Arts and Science collage");
[Link]("Department:IoT");
[Link]("Seemester 1:90%");
[Link]("Semester 2:80%");
[Link]("Semester 3:85%");
[Link]("Semester 4:78%");
[Link]("Semester 5:90%");
[Link]("Semester 6:95%");
[Link]("******");
}
}
class student
{
public static void main(String[] args)
{
academydetails a=new academydetails();
[Link]();
a.display1();
}
}
OUTPUT:
Student Name: Bhooshitha
Phone Number:9488614140
Place:Gobi
Collage:Gobi Arts and Science collage
Department:IoT
Seemester 1:90%
Semester 2:80%
Semester 3:85%
Semester 4:78%
Semester 5:90%
Semester 6:95%
******
8) Program using Interface

Source Code:
import [Link].*;
class vehicle
{
void display()
{
[Link]("This is a vehicle");
}
}
interface car
{
void carInfo();
}
interface Bike
{
void bikeInfo();
}
class Twowheeler implements Bike
{
public void bikeInfo()
{
[Link]("This is a two wheeler bike");
}
}
class Fourwheeler implements car
{
public void carInfo()
{
[Link]("This is a four wheeler car");
}
}
public class interface1
{
public static void main(String[] args)
{
vehicle veh = new vehicle();
[Link]();
Twowheeler twowheeler = new Twowheeler();
[Link]();
Fourwheeler fourwheeler = new Fourwheeler();
[Link]();
}
}
OUTPUT:
This is a vehicle
This is a twowheeler bike
This is a fourwheeler car
9)Program using String Class

Source Code:
import [Link].*;
public class StringExample1
{
public static void main(String[] args)
{
String str1="Hello";
String str2=",Java!";
String combinedstr=str1+str2;
[Link]("Combined String:"+combinedstr);
int length=[Link]();
[Link]("length of the string:"+length);
Boolean containsjava = [Link]("Java");
[Link]("contains 'java':"+containsjava);
String UpperCaseStr = [Link]();
String LowerCaseStr = [Link]();
[Link]("Uppercase:"+UpperCaseStr);
[Link]("Lowercase:"+LowerCaseStr);
String substr1=[Link](0,5);
String substr2=[Link](6);
[Link]("substring1:"+substr1);
[Link]("substring2:"+substr2);
Boolean startsWithHello=[Link]("Hello");
Boolean endsWithJava=[Link]("Java");
[Link]("Starts With 'Hello':"+startsWithHello);
[Link]("Ends With 'Java':"+endsWithJava);
String[] words=[Link](",");

for(String word:words)
{
[Link](word);
}
}
}
Output:
Combined String:Hello,Java!
length of the string:11
contains 'java':true
Uppercase:HELLO,JAVA!
Lowercase:hello,java!
substring1:Hello
substring2:Java!
Starts With 'Hello':true
Ends With 'Java':false
Hello
Java!
10) Program Using String Buffer Class

Source Code:

import [Link].*;
public class stringbufferexample
{
public static void main(String[] args)
{
StringBuffer stringBuffer=new StringBuffer("Hello");
[Link](",");
[Link]("Java!");
[Link]("Appended string:"+stringBuffer);
[Link]("Inserted string:"+stringBuffer);
[Link](5,"Awesome");
[Link]();
[Link]("ReversedString:"+stringBuffer);
[Link](5,13);
[Link]("DeletedString:"+stringBuffer);
[Link]("Updated string:"+stringBuffer);
}
}

OUTPUT:
Appended string:Hello,Java!
Inserted string:Hello,Java!
ReversedString:!avaJ,emosewAolleH
DeletedString:!avaJolleH
Updated string:!avaJolleH
11)Program Using Exception Handling

Source Code:

import [Link].*;
class Ex
{
public static void main(String[] args)
{
try
{
int result =divide(10,0);
[Link]("Result"+result);
}
catch(ArithmeticException e)
{
[Link]("An error occured:"+[Link]());
}
finally
{
[Link]("end of program");
}
}
public static int divide(int divident,int diviser)
{
return divident/diviser;
}
}
}
}

OUTPUT:
An error occured:/ by zero
end of program
12)Thread Based Application

Source Code:

import [Link].*;
class myThread extends Thread
{
private String threadName;
public myThread(String name)
{
[Link]=name;
}
public void run()
{
for(int i=1;i<=5;i++)
{
[Link](threadName + " -count:"+i);
try
{
[Link](1000);
}
catch(InterruptedException e)
{
[Link]();
}
}
}
}
public class threadexample
{
public static void main(String[] agrs)
{
myThread thread1 = new myThread("Thread1");
myThread thread2 = new myThread("Thread2");
[Link]();
[Link]();
try
{
[Link]();
[Link]();
}
catch(InterruptedException e)
{
[Link]();
}
[Link]("Main thread finished");
}
}

OUTPUT:

Thread1 -count:1
Thread2 -count:1
Thread1 -count:2
Thread2 -count:2
Thread1 -count:3
Thread2 -count:3
Thread1 -count:4
Thread2 -count:4
Thread1 -count:5
Thread2 -count:5
Main thread finished
13)Program Using Package

Source Code:

person/[Link]

package person;
public class student
{
int age = 20;
String gender="F";
String name = "Bhooshi";
int E = 90;
int T = 80;
int M = 85;
int J = 96;
int A = 80;
public void display()
{
[Link]("Student Details");
[Link]("Age"+age);
[Link]("Name"+name);
[Link]("English:"+E);
[Link]("Tamil:"+T);
[Link]("Maths:"+M);
[Link]("Java programming"+J);
[Link]("Analog and Electronics"+A);
}
}

[Link]

import [Link];
class package1
{
public static void main(String agrs[])
{
student s=new student();
[Link]();
}
}
OUTPUT:
Student Details
Age20
NameBhooshi
English:90
Tamil:80
Maths:85
Java programming96
Analog and Electronics80
14) Working with colors and fonts in Applet

Source Code:

[Link]

<html>
<body>
here is a output of fan applet program
<applet code="[Link]"width=600 height=600></applet>
</body>
</html>

[Link]

import [Link].*;
import [Link];
public class fan extends Applet
{
public void paint(Graphics g)
{
setBackground([Link]);
{
Font f1,f2;
f1=new Font("Arrival",[Link],18);
f2=new Font("Elephant",[Link],28);
[Link](f1);
[Link]([Link]);
[Link]("Bhooshi",50,50);
[Link](f2);
[Link]([Link]);
[Link]("Java Applet",30,90);
}
}
}
OUTPUT:

Common questions

Powered by AI

Inheritance in Java is implemented by using the 'extends' keyword, allowing a new class to inherit features (methods and fields) from an existing class. In this example, the 'academydetails' class inherits from 'personaldetails', which allows it to use the 'display' method directly, alongside its own 'display1' method. This provides advantages like code reuse, increased modularity, and improved maintenance by creating hierarchical class structures .

The String class in Java offers extensive functionality for string manipulations. In the StringExample1 class, operations include concatenation using the '+' operator to form 'Hello,Java!', calculating length of the string, checking substring presence, changing case (toUpperCase, toLowerCase), extracting substrings, checking start and end substrings, and splitting the string based on delimiters. These features enable comprehensive manipulation of strings, useful in various scenarios from basic formatting to complex data parsing .

Command-line arguments allow users to pass arguments to the main method when executing a Java program. In the command class example, the main method receives these inputs through the 'args' parameter. The program iterates over 'args' and prints each argument, demonstrating how user input can be processed to change program execution without modifying the code itself .

StringTokenizer in Java is used for breaking a string into tokens or parts, which is useful for parsing data. In the TD1 class example, the StringTokenizer is initialized with the string "Welcome to study tonight". It uses 'hasMoreTokens' and 'nextToken' methods to iterate and print each word separately ('Welcome', 'to', 'study', 'tonight'), allowing efficient manipulation of string data by skipping delimiters like spaces .

Constructors in Java differ from other member methods as they are invoked only once at the time of object creation and are used to initialize variables. In the student class example, the constructor initializes the 'rollno' and 'name' attributes when a new instance of student is created, as shown by 'student st=new student(01,"Bhooshi")'. Regular methods, unlike constructors, can be called multiple times and do not initialize an object’s state .

Exception handling in Java involves planning for errors that could disrupt program execution. In the class Ex, a division by zero is handled using a try-catch block, where ArithmeticException is caught and handled gracefully with a pre-defined message, ensuring the program continues to execute. Considerations include identifying potential error conditions, implementing specific exception classes to handle them, using finally blocks for code that should always execute, and designing logic to recover or inform the user meaningfully after an exception occurs .

StringBuffer in Java is used for creating mutable string objects, allowing modifications without creating new objects, unlike String which is immutable. In the stringbufferexample class, methods like 'append', 'insert', 'delete', and 'reverse' demonstrate how the content of a StringBuffer can be modified. This is beneficial for high-performance applications where frequent string modifications are needed without the overhead of creating new string objects, enhancing efficiency over regular String operations .

Interfaces in Java provide a mechanism to achieve abstraction and multiple inheritance. The interface1 class program demonstrates how classes can implement multiple interfaces (i.e., 'Bike' and 'Car'), which is not possible with classes alone due to the single inheritance constraint. This allows a class like 'Twowheeler' to define specific behavior for 'Bike' and 'Fourwheeler' for 'Car'. The flexibility to implement multiple interfaces allows separation of method signatures from implementation and provides a way to define contracts for other classes to fulfill .

The Vector class in Java is different from a traditional array because it is dynamic in size; it grows or shrinks as elements are added or removed. In the example, elements like 'Dog' and 'Lion' are added seamlessly, and the removal of 'Deer' causes the Vector to adjust without manual resizing. Unlike arrays, Vectors also provide built-in methods for managing the list structure, making them more flexible for use cases requiring dynamic resizing .

The purpose of using classes and objects in Java programming is to model real-world entities and manage them efficiently. In the lamp example, a class 'lamp' is defined with a field 'ison' that represents whether the lamp is on or off. Methods 'turnon' and 'turnoff' are used to change the state of the lamp. By creating objects 'led' and 'halogen', each representing a lamp, we can control the lamps independently. This encapsulation and separation of concerns highlight the benefits of object-oriented programming, allowing modularity and reuse .

You might also like