0% found this document useful (0 votes)
2 views19 pages

Java OOP Sampe Programs

The document contains a series of Java programs demonstrating various programming concepts including increment/decrement operators, binary operators, conditional statements (if-else, switch), loops (for, while, do-while), and object-oriented programming principles like method overloading and static members. Each program is accompanied by a brief description and expected output. The examples serve as practical illustrations for learning Java programming.

Uploaded by

rekikabebaw8
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)
2 views19 pages

Java OOP Sampe Programs

The document contains a series of Java programs demonstrating various programming concepts including increment/decrement operators, binary operators, conditional statements (if-else, switch), loops (for, while, do-while), and object-oriented programming principles like method overloading and static members. Each program is accompanied by a brief description and expected output. The examples serve as practical illustrations for learning Java programming.

Uploaded by

rekikabebaw8
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

Program 1: A simple Java program illustrating the increment and decrement operators.

public class IncrementDecrement [Link](“ y=”+y);


{ [Link](“ --x=”+(--x));
public static void main(String args [ ]) [Link](“ y--=”+(y--));
{ [Link](“ x=”+x);
int x=10, y=20; [Link](“ y=”+y);
[Link](“ x=”+x); }
[Link](“ y=”+y); }
[Link](“ ++x=”+(++x)); Output of the program:
[Link](“ ++y=”+(++y)); ?
[Link](“ x=”+x);
Program 2: A Java program to illustrate the five basic binary operators.

public class BasicBinaryOperators [Link](“x-y=”+(x-y));


{ [Link](“x*y=”+(x*y));
public static void main(String args[ ]) [Link](“x/y=”+(x/y));
{ [Link](“x%y=”+(x%y));
int x=9, y=5; }
[Link](“x=”+x); }
[Link](“y=”+y); Output of the program:
[Link](“x+y=”+(x+y)); ?

Program 3: Boolean Logical Operators.

Public class boolean logical operator [Link] ( “” +b);


public static void main (String args []) else
{ [Link] ( “” +a);
int a = 5; }
int b = 7; Output of the program:
if ((a>b)&&((b=19)>10)) ?

1|Page
G2 OOP Sample Programs
Programs 4: Demonstrates if ... else ... else if statement

public class IfElse grade = “Third” ;


{ else
public static void main (String args [ ] ) grade = “ Sorry I can’t give you grade, better
{ appear
int marks = 52; next time” ;
String grade; [Link] ( “ Grade of the student is
if( marks >= 60) : “ +grade);
grade = “First” ; }}
else if (marks >= 50) Output of the program:
grade = “Second” ; ?
else if( marks >= 35)

Programs 5: Cascading a series of if ... else statements

public class IfElseCascade if(ch==’x’)


{ i=10;
public static void main(String args[ ]) elseif(ch==’z’)
{ i=30;
int i; else
char ch=(char)-1; i=40;
[Link](“Enter a character:”);
[Link](“number:”+i);
try
}
{
}
ch=(char)[Link]();
Output of the program:
}
catch(Exception e) ?
{}

2|Page
G2 OOP Sample Programs
Program 6: Demonstrates switch

public class SwitchDemo break;


{ case 5: [Link](“Thursday”);
public static void main(String args [ ]) break;
{ case 6: [Link](“Friday”); break;
int day = 4; case 7: [Link](“Saturday”)break;
switch (week) default: [Link](“ Day doesn’t
{ exist”);
case 1: [Link](“Sunday”); break; }
case 2: [Link](“Monday”); }
break; }
case 3: [Link](“Tuesday”); Output of the program:
break; ?
case 4: [Link](“Wednesday”);

Program 7: Demonstrates switch case constant

public class SwitchCaseConstruct {


{ case ‘x’ : i=10
public static void main(String args []) break;
{ case ‘y’ : i=20
int i; break;
char ch=(char)-1; case ‘z’ : i=30
[Link](“Enter a character:”); break;
try default ; i=40;
}
{
[Link](“number :”+i);
ch=(char)[Link]();
}
}
}
catch(Exception e)
Output of the program:
{}
?
switch(ch)

3|Page
G2 OOP Sample Programs
Program 8: Demonstrates the for loop

public class ForLoop [Link](“number :”+i);


{ }
public static void main (String args[ ] ) }
{ }
{ Output of the program:
for(int i=0;i<10;i++) ?

Program 9: Demonstrates a continue statement in for loop

public class ForLoopContinue { }


public static void main (String args[ ] ) { [Link] (“End of the for loop”);
{ }
for(int i=0;i<5;i++) }
{ Output of the program:
if(i==2) continue; ?
[Link](“number :”+i);
Program 10: Demonstrates a break statement in for loop

public class ForLoopBreak [Link](“number :”+i);


{ }
public static void main (String args[ ] ) [Link] (“End of the for loop”);
{ }
{ }
for(int i=0;i<5;i++) Output of the program:
{ ?
if(i==2) break;

4|Page
G2 OOP Sample Programs
Program 11: A simple Java program to illustrate nested for loops:

public class ForLoopNested [Link](“(“+i+”,”+j+”)”);


{ }
public static void main (String args[ ] ) [Link]();
{ }
for(int i=1;i<=3;i++) Output of the program:
{
?
for(int j=1; j<=3; j++)
{
Program 12: A Java program to illustrate the usage of continue label statement
in a nested for loop is as follows:

public class ForLoopContinueLoopLabel }


{ [Link](“(“+i+”,”+j+”)”);
public static void main (String argv[]) }
{ [Link]();
label: }
for(int i=1 ; i<=3;i++) [Link](“End of the loop”);
{ }
for(int j=1;j<=3; j++) }
{ Output of the program:
if((i= = 2)&&(j= =2)
?
{
[Link]();
continue label;

5|Page
G2 OOP Sample Programs
Program 13: Print 0 to 10 numbers using while loop

public class WhileLoop i++;


{ }
public static void main (String args[ ] ) [Link](“End of the while loop”);
{ }
int i = 0; }
while (i <10) { Output of the program:
[Link](“number :”+i); ?

Program 14: A Java program to illustrate the usage of continue statement in a


while loop.

public class WhileLoopContinue i++;


{ continue;
public static void main(String argv [ ]) }
{ [Link](“number :”+i);
int i=0; }
while(i<5) }
{ Output of the program:
if(i= =2) ?
{

6|Page
G2 OOP Sample Programs
Program 15: A Java program to show the usage of break statement in a while
loop.

public class WhileLoopBreak break;


{ [Link]. println(“End of the while
public static void main(String args[ ]) loop”);
{ }
int i=0; }
while(i<5)
Output of the program:
{
?
if(i= =2)
Program 16: A Java program with nested while loop.

public class }
WhileLoopContinueLoopNested [Link]( );
{ j=1;
public static void main (String argv[]) i++;
{ }
int i=1, j=1; [Link](“End of the loop”);
while(i<=3) }
{ }
while(j<=3) Output of the program:
{
?
[Link](“(“+i+”,”+j+”)”);
j++;

7|Page
G2 OOP Sample Programs
Program 17: A Java program to illustrate the use of continue label statement in
a nested while loop.

public class WhileLoopContinueLoopLabel }


{ [Link](“(“+i+”,”+j+”)”);
public static void main (String args[]) j++;
{ }
int i=1, j=1; [Link]();
j=1;
label:while(i<=3)
i++;
{
}
while(j<=3)
[Link](“End of the loop”);
{
}
if((i= = 2)&&(j= =2)
}
{
Output of the program:
i++;
j=1; ?
[Link]();
continue label;
Program 18: A Java program to illustrate the use of continue label statement in
a nested while loop.

public class WhileLoopbreakLoopLabel break label;


{ }
public static void main (String args[]) [Link](“(“+i+”,”+j+”)”);
{ j++;
int i=1, j=1; }
label: [Link]();
while(i<=3) j=1;
{ i++;
while(j<=3) }
{ [Link](“End of the loop”);
if((i= = 2)&&(j= =2) }
{ }
Output of the program:
i++;
j=1; ?
[Link]();

8|Page
G2 OOP Sample Programs
Program 19: Demonstrates do ... while loop

public class DoWhileLoop i++;


{ } while (i <10)
public static void main (String args[ ] ) [Link](“End of the while loop”);
{ }
int i = 0; }

do Output of the program:


{ ?
[Link](“number :”+i);
Program 20: A Java program to illustrate the usage of continue statement in a do
... while loop:

public class DoWhileLoopContinue }


{ [Link](“number :”+i);
public static void main (String argv[]) i++;
{ }
int i=0; while(i<5);
do [Link](“End of the loop”);
{ }
if(i= =2) }
{
Output of the program:
i++;
?
continue;

9|Page
G2 OOP Sample Programs
Program 21: A Java program to illustrate the usage of break statement in a do ...
while loop.

public class DoWhileLoopBreak break;


{ }
public static void main (String args[]) [Link](“number :”+i);
{ i++;
int i=0; }while(i<5)
do [Link](“End of the loop”);
{ }
if(i= =2) }
{ Output of the program:
i++; ?
Program 22: A Java program to illustrate the break statement

class Break [Link](“number :” +i);


{ }
public static void main(String args[]) [Link](“End of the for loop”);
{ }
for( int i= 0;i<5;i++) }
{ Output of the program:
if(i==2) break; ?

Program 23: A Java program to illustrate the continue statement

class Continue [Link] (“number:” +i);


{ }
public static void main(String args[]) [Link](“End of the for loop”);
{ }
for( int i= 0;i<5;i++) }
{ Output of the program:
if(i= =2) continue; ?

10 | P a g e
G2 OOP Sample Programs
Program 24: A program to demonstrate the accessing of members of a class.

class Cuboid [Link]=60;


{ [Link]=20;
int length; [Link]=40;
int width; int vol=[Link]();
int height;
//accessing variables
int volume() //method definition
{ //calling method
return(length*width*height);
[Link](“The volume of the
}
cuboid is: “
}
+vol);
class ClassDemo
}
{
}
public static void main(String args[])
{ Output of the program:
?
Cuboid cobj=new //object creation
Cuboid();
Program 25: A program to demonstrate the call by value mechanism

class FirstCall int w=20;


{ int h=15;
void vol(int i, int j, int k) [Link](“Length, Width, Height
{ before call
i+=5; is :” +l+ “ “ +w+ “ “ +h);
j+=5; [Link](l, w, h); //passing values as arguments
k+=5; [Link](“Length, Breadth, Height
} after call
} is :” +l+ “ “ +w+ “ “ +h);
class CallByValue }
{ }
public static void main(String args[])
Output of the program:
{
?
FirstCall fc =new FirstCall();
int l=10;

11 | P a g e
G2 OOP Sample Programs
Program 26: A program to demonstrate the call by reference mechanism.

class SecondCall [Link]=30;


{ [Link](“The values of Length,
int length, breadth, height; //variables Breadth and Height
declaration before method call: “ +[Link] + “ “
void vol(SecondCall s) //method definition +[Link] + “ “
{ +[Link]);
[Link]+=5; [Link](sc); //passing object as method
[Link]+=5; argument
[Link]+=5; [Link](“The values of Length,
}} Breadth and Height
class CallByRefernce after method call: “ +[Link] + “ “
{ +[Link] + “ “
public static void main(String args[]) +[Link]);
{ }}
SecondCall sc=new SecondCall();
Output of the program:
[Link]=10;
?
[Link]=20;
Program 27: A program to demonstrate the concept of a constructor.

class Cuboid }
{ class Constructor
int length; {
int width; public static void main(String args[])
int height; {
Cuboid() //constructor definition without Cuboid c1=new Cuboid();
parameters Cuboid c2=new Cuboid();
{ int a=[Link]();
length=20; int b=[Link]();
width=10; [Link](“The volume of first
height=15; cuboid is “ +a);
} [Link](“The volume of second
int volume() cuboid is “ +b);
}
{
}
return (length*width*height);
Output of the program:
}
?

12 | P a g e
G2 OOP Sample Programs
Program 28: A program to demonstrate the concept of method overloading.

class Shapes [Link](“The perimeter of the


{ rectangle is
void perimeter(int a)//method with int type “+2*(a+b));
parameter }
{ }
[Link](“The perimeter of the class MethodOverloading
square is “+(4*a)); {
} public static void main(String args[])
void perimeter(double a)//method with {
double type parameter Shapes s=new Shapes();
{ [Link](5.5);
[Link](“The circumference of
[Link](10);
the circle is
[Link](15,10);
“+(2*a*(22/7)));
}
}
}
void perimeter(int a, int b) //method with
Output of the program:
two parameters
?
{
Program 29: A program to demonstrate the use of static members of a class.

class StaticMembers public static void main(String args[])


{ {
static int i=10; //static variable
[Link](30,40); //calling static method
static void add(int x, int y) //static method
int i= StaticMembers.i; //accessing static
{
[Link](“Sum of two numbers is: //variable
“+(x+y)); [Link](“Value of i is: “+i);
} }
} }
class StaticExample Output of the program:
{ ?

13 | P a g e
G2 OOP Sample Programs
Program 30: A program to demonstrate the name space collision between the instance
variables of a class and variables declared inside a method.

class SecondConstructor variable j:”+j);


{ }
int i, j; }
SecondConstructor(int i, int j) class ConstructorsCall
{ {
//accessing variables of a constructor public static void main(String args[])
i=i; {
j=j; SecondConstructor sc=new
} SecondConstructor(10, 20);
void display() [Link]();
{ }
[Link](“Value of instance }
variable i:”+i); Output of the program:
[Link](“Value of instance ?

Program 31: A Java program shows the usage of inheritance:

class SuperBazar “+
{ (sales + tax_to_pay));
int sales; }
public SuperBazar( ) { } / / default }
constructor public class SalesTax extends SuperBazar
public SuperBazar(int bill) {
{ public SalesTax(int amount)
sales = bill; {
} sales = amount;
public void tax( ) }
{ public static void main(String args[ ])
double tax_to_pay = sales * 8.33 /100; {
[Link](“Customer sales amount SalesTax apgst = new SalesTax(5000);
is Birr. “ + [Link]( );
sales); }}
[Link](“Tax to pay is Birr. “ + Output of the program:
tax_to_pay); ?
[Link](“Total Bill amount is Rs.

14 | P a g e
G2 OOP Sample Programs
Program 32: A Java program using super Keyword:

class Number1 }
{ public static void main(String args[ ])
int num = 10; {
public void display( ) Number1 number1 = new Number1( );
{ Number2 number2 = new Number2( );
[Link](“From Number 1 : num =
[Link]( );
“ + num);
its own class method
}
[Link]( ); / / superclass
}
superclass method object calling
public class Number2 extends Number1
[Link]( );
{
own class method
Super (num);
int num = 20; / /subclass object
public void show( ) calling
{
/ / subclass object
[Link](“From Number 2 without
calling its
super num =
“ + num); }
[Link](“From Number 2 with }
super num = Output of the program:
“ + num); ?

15 | P a g e
G2 OOP Sample Programs
Program 33: A Java program shows the use of multilevel hierarchy.

class Worker Supervisor gmoffice=new


{ supervisor(5700,459.25f.1876);
int salary; Supervisor
float overtime; planningdept=newsupervisor(6780.145.85f,256
double total; 7);
Worker( ) { } double d;
publicWorker(int x, float y) d=[Link]( );
{ [Link](“Total Salary of shopfloor
salary = x; worker is Birr.”
overtime = y; +d);
} [Link] println(“Total Salary of frontoffice
public double totalSalary( ) worker is
{ Birr”+ [Link]( ));
return total = salary + overtime;
d=[Link] Salary( );
}
[Link] println (“Total Salary of GM office
public double netSalary( )
supervisor
{
is Birr” + d);
return totalSalary( ) – totalSalary( ) * 30 / 100;
[Link](“Total Salary of Planning
}
department
}
supervisor is Birr.” + planning [Link](
public class Supervisor extends Worker
));
int supervisory_allowance;
System. out. println(“Supervisory allowance of
public Supervisor(int x, float y, int z)
gmoffice is
{
Birr.” +gmoffice. supervisory _ allowance );
salary=x;
[Link] (“Supervisory allowance of
overtime=y;
planningdept
supervisory_allowance = z;
is Birr.” +
}
planningdept.supervisory_allowance);
public static void main (String args[ ] )
}
{
Output of the program:
Worker shopfloor =new worker (2500,376.5f);
?
Worker frontoffice=new worker(2200,85.00f);

16 | P a g e
G2 OOP Sample Programs
Program 34: A Java program for overriding

class area public void area(int r)


{ {
public void area(int r) [Link](“ Perimeter of circle: “ +
{ [Link] ( 2 * [Link] * r ));
[Link](“ Area of circle: “ + }
[Link] ( public static void main(String args[ ] )
[Link] * r *r)); {
} Area a = newArea( );
public void area(int l, int b) Periemter p = new Perimeter ( );
{ [Link] (22);
[Link](“ Area of rectangle: “ + 2 [Link] (22);
* (l + b)); [Link] (22, 33);
} }}
} Output of the program:
public class Perimeter extends Area ?
{

17 | P a g e
G2 OOP Sample Programs
Program 34: Write a Java program to create a class called Person with private instance variables
name, age. and country. Provide public getter and setter methods to access and modify these
variables.

// [Link]

// Person Class

class Person { public int getAge() {

// Private field to store the name of the return age;


person
}
private String name;
// Public method to set the age of the
// Private field to store the age of the person
person
public void setAge(int age) {
private int age;
[Link] = age;
// Private field to store the country of the
}
person
// Public method to get the country of the
private String country;
person
// Public method to get the name of the
public String getCountry() {
person
return country;
public String getName() {
}
return name;
// Public method to set the country of the
}
person
// Public method to set the name of the
public void setCountry(String country) {
person
[Link] = country;
public void setName(String name) {
}
[Link] = name;
}
}

// Public method to get the age of the


person

18 | P a g e
G2 OOP Sample Programs
// [Link]

// Main Class

public class Main { String name = [Link]();

public static void main(String[] args) { int age = [Link]();


// Create an instance of Person String country = [Link]();

Person person = new Person();

// Print the values

// Set values using setter methods [Link]("Name: " + name);

[Link]("Ayele Kebede"); [Link]("Age: " + age);

[Link](25); [Link]("Country: " +


country);
[Link]("Ethiopia");
}

}
// Get values using getter methods

19 | P a g e
G2 OOP Sample Programs

You might also like