Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Java Programs

The document contains multiple Java programming examples demonstrating various concepts such as object initialization, method overloading, access modifiers, inheritance, encapsulation, abstraction, and generics. Each example includes code snippets along with expected output, illustrating how to implement these concepts in Java. The document serves as a comprehensive guide for understanding fundamental Java programming principles.

Uploaded by

tharungoudthanda
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Java Programs

The document contains multiple Java programming examples demonstrating various concepts such as object initialization, method overloading, access modifiers, inheritance, encapsulation, abstraction, and generics. Each example includes code snippets along with expected output, illustrating how to implement these concepts in Java. The document serves as a comprehensive guide for understanding fundamental Java programming principles.

Uploaded by

tharungoudthanda
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

1.

Write a Java Program to Initializing a Java Object


// Java Program to Demonstrate the
// use of a class with instance variable
// Class Declaration
public class Dog
{
// Instance Variables
String name;
String breed;
int age;
String color;
// Constructor Declaration of Class
public Dog(String name, String breed, int age, String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}
// method 1
public String getName()
{
return name;
}
// method 2
public String getBreed()
{
return breed;
}
// method 3
public int getAge()
{
return age;
}
// method 4
public String getColor()
{
return color;
}
@Override public String toString()
{
return ("Name is: " + this.getName() + "\nBreed, age, and color are: " +
this.getBreed() + "," + this.getAge() + "," + this.getColor());
}
public static void main(String[] args)
{
Dog tuffy= new Dog("tuffy", "papillon", 5, "white");
System.out.println(tuffy.toString());
}
}
Output -
Name is: tuffy
Breed, age, and color are: papillon,5,white

2. Write a Java program to Initialize Object by using Method/Function


// Java Program to initialize Java Object
// by using method/function
public class Geeks
{
static String name;
static float price;
static void set(String n, float p)
{
name = n;
price = p;
}

static void get()


{
System.out.println("Software name is: " + name);
System.out.println("Software price is: " + price);
}

public static void main(String args[])


{
Geeks.set("Visual studio", 0.0f);
Geeks.get();
}
}

Output -
Software name is: Visual studio
Software price is: 0.0

3. Write a Java program to demonstrate Variable’s local scope with


initialization
public class Test {
public void pupAge() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}

public static void main(String args[]) {


Test test = new Test();
test.pupAge();
}
}
Java
Output -
Puppy age is: 7
Java

4. Write a Java Program to demonstrate Java Instance Variables


public String name;

// salary variable is visible in Employee class only.


private double salary;

// The name variable is assigned in the constructor.


public Employee (String empName) {
name = empName;
}

// The salary variable is assigned a value.


public void setSalary(double empSal) {
salary = empSal;
}

// This method prints the employee details.


public void printEmp() {
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}

public static void main(String args[]) {


Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}
Output -
name : Ransika
salary :1000.0
Java

5. Write a Java program to demonstrate Java Class/Static Variables


import java.io.*;

public class Employee {

// salary variable is a private static variable


private static double salary;

// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";

public static void main(String args[]) {


salary = 1000;
System.out.println(DEPARTMENT + "average salary:" + salary);
}
}
Output -
Development average salary:1000

6. Write a Java Program to create and call a default constructor


(Example 1)
class Bike1
{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");
}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output -
Bike is created

7. Write a Java Program to create and call a default constructor


(Example 2)
class Student3
{
int id;
String name;
//method to display the value of id and name
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}
}
Output -
0 null

8. Write a
Java Program to demonstrate the use of the parameterized cons
tructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Output -
111 Karan
222 Aryan

9. Write a Java program to overload constructors


class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output -
111 Karan 0
222 Aryan 25

10. Write a Java program to demonstrate destructor


public class DestructorExample
{
public static void main(String[] args)
{
DestructorExample de = new DestructorExample ();
de.finalize();
de = null;
System.gc();
System.out.println("Inside the main() method");
}
protected void finalize()
{
System.out.println("Object is destroyed by the Garbage Collector");
}
}
Output -
Object is destroyed by the Garbage Collector
Inside the main() method
Object is destroyed by the Garbage Collector

11. Write a Java program to demonstrate access modifiers


i) Default access modifier –
// default access modifier
package p1;
// Class Geek is having
// Default access modifier
class Geek
{
void display()
{
System.out.println("Hello World!");
}
}

ii) Protected access modifier – (Example 1)


// protected access modifier
package p1;
// Class A
public class A {
protected void display() {
System.out.println("GeeksforGeeks");
}
}

Example 2 -
// protected modifier
package p2;

// importing all classes


// in package p1
import p1.*;

// Class B is subclass of A
class B extends A {
public static void main(String args[]) {
B obj = new B();
obj.display();
}
}

i) Public access modifier – (Example 1)

// public modifier
package p1;

public class A {
public void display() {
System.out.println("GeeksforGeeks");
}
}

Example 2 -
// public access modifier
package p2;

import p1.*;

class B {
public static void main(String args[]) {

A obj = new A();


obj.display();
}

12. Write a // Java Program to Implement Method Overloading


import java.io.*;

class MethodOverloadingEx
{

static int add(int a, int b)


{
return a + b;
}

static int add(int a, int b, int c)


{
return a + b + c;
}

// Main Function
public static void main(String args[])
{
System.out.println("add() with 2 parameters");
// Calling function with 2 parameters
System.out.println(add(4, 6));

System.out.println("add() with 3 parameters");


// Calling function with 3 Parameters
System.out.println(add(4, 6, 7));
}
}

Output -
add() with 2 parameters
10
add() with 3 parameters
17

13. Write a Java Program to implement Method Overriding:


import java.io.*;

// Base Class
class Animal
{
void eat()
{
System.out.println("eat() method of base class");
System.out.println("Animal is eating.");
}

// Derived Class
class Dog extends Animal
{
@Override
void eat()
{
System.out.println("eat() method of derived class");
System.out.println("Dog is eating.");
}

// Method to call the base class method


void eatAsAnimal()
{
super.eat();
}
}

// Driver Class
class MethodOverridingEx
{
// Main Function
public static void main(String args[])
{
Dog d1 = new Dog();
Animal a1 = new Animal();

// Calls the eat() method of Dog class


d1.eat();
// Calls the eat() method of Animal class
a1.eat();

// Polymorphism: Animal reference pointing to Dog object


Animal animal = new Dog();

// Calls the eat() method of Dog class


animal.eat();

// To call the base class method, you need to use a Dog reference
((Dog) animal).eatAsAnimal();
}
}

Output -
eat() method of derived class
Dog is eating.
eat() method of base class
Animal is eating.
eat() method of derived class
Dog is eating.
eat() method of base class
Animal is eating.

14. Write a Java program to show working of user defined


Generic classes

// We use < > to specify Parameter type


class Test<T>
{
// An object of type T is declared
T obj;
Test(T obj) { this.obj = obj; } // constructor
public T getObject() { return this.obj; }
}

// Driver class to test above


class Main {
public static void main(String[] args)
{
// instance of Integer type
Test<Integer> iObj = new Test<Integer>(15);
System.out.println(iObj.getObject());

// instance of String type


Test<String> sObj
= new Test<String>("GeeksForGeeks");
System.out.println(sObj.getObject());
}
}

Output -
15
GeeksForGeeks

15. Write a Java program to show multiple type parameters in


Java Generics

// We use < > to specify Parameter type


class Test<T, U>
{
T obj1; // An object of type T
U obj2; // An object of type U

// constructor
Test(T obj1, U obj2)
{
this.obj1 = obj1;
this.obj2 = obj2;
}

// To print objects of T and U


public void print()
{
System.out.println(obj1);
System.out.println(obj2);
}
}

// Driver class to test above


class Main
{
public static void main (String[] args)
{
Test <String, Integer> obj =
new Test<String, Integer>("GfG", 15);

obj.print();
}
}

Output -
GfG
15

16. Write a Java Program to demonstrate Abstraction


// Demonstrating Abstraction in Java
abstract class Geeks
{
abstract void turnOn();
abstract void urnoff();
}

// Concrete class implementing the abstract methods


class TVRemote extends Geeks
{
@Override
void turnOn()
{
System.out.println(“TV is turned ON.”);
}

@Override
void urnoff()
{
System.out.println(“TV is turned OFF.”);
}
}

// Main class to demonstrate abstraction


public class Main
{
public static void main(String[] args)
{
Geeks remote = new TVRemote();
remote.turnOn();
remote.turnOff(); }}

Output -
TV is turned ON.
TV is turned OFF.

17. Write a Java program to demonstrate the Encapsulation.


class Person {
// Encapsulating the name and age
// only approachable and used using
// methods defined
private String name;
private int age;

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public int getAge() { return age; }

public void setAge(int age) { this.age = age; }


}

// Driver Class
public class Geeks {
// main function
public static void main(String[] args)
{
// person object created
Person p = new Person();
p.setName("John");
p.setAge(30);
// Using methods to get the values from the variables
System.out.println("Name: " + p.getName());
System.out.println("Age: " + p.getAge());
}
}

Output -
Name: John
Age: 30

18. Write a Java program to illustrate the concept of single


inheritance
import java.io.*;
import java.lang.*;
import java.util.*;

// Parent class
class One
{
public void print_geek()
{
System.out.println("Geeks");
}
}

class Two extends One


{
public void print_for() { System.out.println("for");
}
}
// Driver class
public class Main
{
// Main function
public static void main(String[] args)
{
Two g = new Two();
g.print_geek();
g.print_for();
g.print_geek();
}
}

Output -
Geeks
for
Geeks

19. Write a Java program to illustrate the concept of multi-level


inheritance

import java.io.*;
import java.lang.*;
import java.util.*;

// Parent class One


class One
{
// Method to print "Geeks"
public void print_geek()
{
System.out.println("Geeks");
}
}

// Child class Two inherits from class One


class Two extends One
{
// Method to print "for"
public void print_for()
{
System.out.println("for");
}
}

// Child class Three inherits from class Two


class Three extends Two
{
// Method to print "Geeks"
public void print_lastgeek()
{
System.out.println("Geeks");
}
}

// Driver class
public class Main
{
public static void main(String[] args)
{
// Creating an object of class Three
Three g = new Three();

// Calling method from class One


g.print_geek();

// Calling method from class Two


g.print_for();
// Calling method from class Three
g.print_lastgeek();
}
}

Output -
Geeks
for
Geeks

20. Write a Java program to illustrate the concept of


Hierarchical inheritance

class A
{
public void print_A()
{
System.out.println("Class A");
}
}

class B extends A
{
public void print_B()
{ System.out.println("Class B");
}
}

class C extends A
{
public void print_C()
{
System.out.println("Class C");
}

class D extends A
{
public void print_D()
{
System.out.println("Class D");
}
}
// Driver Class
public class Test
{

public static void main(String[] args)


{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();
C obj_C = new C();
obj_C.print_A();
obj_C.print_C();
D obj_D = new D();
obj_D.print_A();
obj_D.print_D();
}
}

Output -
Class A
Class B
Class A
Class C
Class A
Class D

21. Write a Java program to illustrate the concept of Multiple


inheritance (Interfaces)
import java.io.*;
import java.lang.*;
import java.util.*;

interface One
{
public void print_geek();
}
interface Two
{
public void print_for();
}
interface Three extends One, Two
{
public void print_geek();
}
class Child implements Three {
@Override public void print_geek()
{
System.out.println("Geeks");
}

public void print_for() { System.out.println("for");


}
}

// Drived class
public class Main
{
public static void main(String[] args)
{
Child c = new Child();
c.print_geek();
c.print_for();
c.print_geek();
}
}

Output
Geeks
for
Geeks

22. Write a Java program to demonstrate Java IS-A type of


Relationship
class SolarSystem
{
}
class Earth extends SolarSystem
{
}
class Mars extends SolarSystem
{
}
public class Moon extends Earth
{
public static void main(String args[])
{
SolarSystem s = new SolarSystem();
Earth e = new Earth();
Mars m = new Mars();

System.out.println(s instanceof SolarSystem);


System.out.println(e instanceof Earth);
System.out.println(m instanceof SolarSystem);
}
}

Output
true
true
true

23. Write a Java program to demonstrate Inner class

class OuterClass {
int x = 10;

class InnerClass {
public int myInnerMethod() {
return x;
}
}
}

public class Main {


public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.myInnerMethod());
}
}

24. Write a Java program to demonstrate static variables and


blocks

class Test
{
// static variable
static int a = m1();

// static block
static {
System.out.println("Inside static block");
}

// static method
static int m1() {
System.out.println("from m1");
return 20;
}

// static method(main !!)


public static void main(String[] args)
{
System.out.println("Value of a : "+a);
System.out.println("from main");
}
}

Output
from m1
Inside static block
Value of a : 20
from main

25. Write a Java program to demonstrate static methods

class Student {
String name;
int rollNo;

// static variable
static String cllgName;

// static counter to set unique roll no


static int counter = 0;

public Student(String name)


{
this.name = name;

this.rollNo = setRollNo();
}

// getting unique rollNo


// through static variable(counter)
static int setRollNo()
{
counter++;
return counter;
}

// static method
static void setCllg(String name) { cllgName = name; }

// instance method
void getStudentInfo()
{
System.out.println("name : " + this.name);
System.out.println("rollNo : " + this.rollNo);

// accessing static variable


System.out.println("cllgName : " + cllgName);
}
}

// Driver class
public class StaticDemo {
public static void main(String[] args)
{
// calling static method
// without instantiating Student class
Student.setCllg("XYZ");
Student s1 = new Student("Alice");
Student s2 = new Student("Bob");

s1.getStudentInfo();
s2.getStudentInfo();
}
}

Output
name : Alice
rollNo : 1
cllgName : XYZ
name : Bob
rollNo : 2
cllgName : XYZ

26. Write a Java program to demonstrate static classes

public class ExampleClass {


public static int count = 0;
public int id;

public ExampleClass() {
count++;
id = count;
}

public static void printCount() {


System.out.println("Number of instances: " + count);
}

public void printId() {


System.out.println("Instance ID: " + id);
}

public static void main(String[] args) {


ExampleClass e1 = new ExampleClass();
ExampleClass e2 = new ExampleClass();
ExampleClass e3 = new ExampleClass();

e1.printId();
e2.printId();
e3.printId();

ExampleClass.printCount();
}
}
Output
Instance ID: 1
Instance ID: 2
Instance ID: 3
Number of instances: 3

27. Write a Java program to demonstrate super keyword with


variables

// super keyword in java example


// Base class vehicle
class Vehicle {
int maxSpeed = 120;
}
// sub class Car extending vehicle
class Car extends Vehicle {
int maxSpeed = 180;
void display()
{
// print maxSpeed of base class (vehicle)
System.out.println("Maximum Speed: "+ super.maxSpeed);
}
}
// Driver Program
class Test {
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}

Output
Maximum Speed: 120

28. Write a Java program to demonstrate super keyword with


methods
// super keyword in java example

// superclass Person
class Person {
void message()
{
System.out.println("This is person class\n");
}
}
// Subclass Student
class Student extends Person {
void message()
{
System.out.println("This is student class");
}
// Note that display() is
// only in Student class
void display()
{
// will invoke or call current
// class message() method
message();

// will invoke or call parent


// class message() method
super.message();
}
}
// Driver Program
class Test {
public static void main(String args[])
{
Student s = new Student();

// calling display() of Student


s.display();
}
}
Output
This is student class
This is person class
29. Write a Java program to demonstrate super keyword with
constructor

// Java Code to show use of super keyword with constructor


// superclass Person
class Person {
Person()
{
System.out.println("Person class Constructor");
}
}
// subclass Student extending the Person class
class Student extends Person {
Student()
{
// invoke or call parent class constructor
super();

System.out.println("Student class Constructor");


}
}
// Driver Program
class Test {
public static void main(String[] args)
{
Student s = new Student();
}
}

Output
Person class Constructor
Student class Constructor

30. Write a Java program to demonstrate final keyword


public class Example {
public static void main(String[] args) {
final int VALUE = 10; // declaring a final variable

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


// VALUE = 20; // uncommenting this line will cause a compiler error
// System.out.println("The new value is: " + VALUE);

final String MESSAGE = "Hello, world!"; // declaring a final variable


System.out.println(MESSAGE);

MyClass myObj = new MyClass();


myObj.printMessage();
myObj.printFinalMessage();

// MyOtherClass extends MyClass {} // uncommenting this line will


cause a compiler error
}
}

class MyClass {
final String message = "Hello!"; // declaring a final instance variable

void printMessage() {
System.out.println(message);
}

void printFinalMessage() {
final String finalMessage = "Hello, final!";
System.out.println(finalMessage);
}
}

final class MyOtherClass { // declaring a final class


// ...
}

Output
The value is: 10
Hello, world!
Hello!
Hello, final!

31. Write a Java program to demonstrate this keyword

// Java Program to implement Java this reference


// Driver Class
public class Person {
// Fields Declared
String name;
int age;
// Constructor
Person(String name, int age)
{
this.name = name;
this.age = age;
}
// Getter for name
public String get_name() { return name; }
// Setter for name
public void change_name(String name)
{
this.name = name;
}
// Method to Print the Details of the person
public void printDetails()
{
System.out.println("Name: " + this.name);
System.out.println("Age: " + this.age);
System.out.println();
}
// main function
public static void main(String[] args)
{
// Objects Declared
Person first = new Person("ABC", 18);
Person second = new Person("XYZ", 22);
first.printDetails();
second.printDetails();
first.change_name("PQR");
System.out.println("Name has been changed to: "
+ first.get_name());
}
}

Output
Name: ABC
Age: 18
Name: XYZ
Age: 22
Name has been changed to: PQR

You might also like