0% found this document useful (0 votes)
53 views32 pages

Write A Java Program That Creates An Object and Initializes Its Data Members Using Constructor. Use Constructor Overloading Concept

1. The document provides examples of Java programs that demonstrate constructor overloading, calculating employee salary, sorting an array using bubble sort, searching an array using binary search, tracking the number of objects created using a static variable, counting the frequency of words and characters in a string, handling exceptions using the finally block, accessing variables from a user-created package, and implementing multilevel inheritance with various access controls.

Uploaded by

Vishal
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)
53 views32 pages

Write A Java Program That Creates An Object and Initializes Its Data Members Using Constructor. Use Constructor Overloading Concept

1. The document provides examples of Java programs that demonstrate constructor overloading, calculating employee salary, sorting an array using bubble sort, searching an array using binary search, tracking the number of objects created using a static variable, counting the frequency of words and characters in a string, handling exceptions using the finally block, accessing variables from a user-created package, and implementing multilevel inheritance with various access controls.

Uploaded by

Vishal
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/ 32

1.

Write a Java program that creates an object and initializes its data
members using constructor. Use constructor overloading concept.

import java.lang.*;
class student
{
String name;
int regno;
int marks1,marks2,marks3;
// null constructor
student()
{
name="raju";
regno=12345;
marks1=56;
marks2=47;
marks3=78;
}
// parameterized constructor
student(String n,int r,int m1,int m2,int m3)
{
name=n;
regno=r;
marks1=m1;
marks2=m2;
marks3=m3;
}
// copy constructor
student(student s)
{
name=s.name;
regno=s.regno;
marks1=s.marks1;
marks2=s.marks2;
marks3=s.marks3;
}
void display()
{
System.out.println(name + "\t" +regno+ "\t" +marks1+ "\t"
+marks2+ "\t" + marks3);
}
}
class studentdemo
{
public static void main(String arg[])
{
student s1=new student();
student s2=new student("john",34266,58,96,84);
student s3=new student(s1);
s1.display();
s2.display();
s3.display();
}
}

****************************OUTPUT****************************
c:\jdk1.6.0_26\bin>javac studentdemo.java
c:\jdk1.6.0_26\bin>java studentdemo
raju 12345 56 47 78
john 34266 58 96 84
raju 12345 56 47 78
2. Write a java program to calculate gross salary & net salary taking the
following data. Input: empno, empname, basic Process: DA=50%of
basic HRA=12%of basic CCA=Rs240/- PF=10%of basic PT=Rs100/-
3. Write a Java program to sort the elements using bubble sort.

import java.util.Scanner;

public class JavaProgram


{
public static void main(String args[])
{
int n, i, j, temp;
int arr[] = new int[50];
Scanner scan = new Scanner(System.in);

System.out.print("Enter Total Number of Elements : ");


n = scan.nextInt();

System.out.print("Enter " +n+ " Numbers : ");


for(i=0; i<n; i++)
{
arr[i] = scan.nextInt();
}

System.out.print("Sorting Array using Bubble Sort


Technique...\n");
for(i=0; i<(n-1); i++)
{
for(j=0; j<(n-i-1); j++)
{
if(arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}

System.out.print("Array Sorted Successfully..!!\n");

System.out.print("Sorted List in Ascending Order : \n");


for(i=0; i<n; i++)
{
System.out.print(arr[i]+ " ");
}
}
}

****************************OUTPUT****************************
4. Write a Java program to search an element using binary search.
import java.util.Scanner;

public class JavaProgram


{
public static void main(String args[])
{
int n, i, search, first, last, middle;
int arr[] = new int[50];
Scanner scan = new Scanner(System.in);

System.out.print("Enter Total Number of Elements : ");


n = scan.nextInt();

System.out.print("Enter " +n+ " Elements : ");


for(i=0; i<n; i++)
{
arr[i] = scan.nextInt();
}

System.out.print("Enter a Number to Search..");


search = scan.nextInt();

first = 0;
last = n-1;
middle = (first+last)/2;

while(first <= last)


{
if(arr[middle] < search)
{
first = middle+1;
}
else if(arr[middle] == search)
{
System.out.print(search+ " Found at Location "
+middle);
break;
}
else
{
last = middle - 1;
}
middle = (first+last)/2;
}
if(first > last)
{
System.out.print("Not Found..!! " +search+ " is not
Present in the List.");
}
}
}

****************************OUTPUT****************************
5. Write a Java program that counts the number of objects created by
using static variable.
class VariableDemo
{
static int count=0;
public void increment()
{
count++;
}
public static void main(String args[])
{
VariableDemo obj1=new VariableDemo();
VariableDemo obj2=new VariableDemo();
obj1.increment();
obj2.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
}
}

****************************OUTPUT****************************
Obj1: count is=2
Obj2: count is=2
6. Write a Java program to count the frequency of words, characters in
the given line of text.
import java.util.Scanner;

public class Frequency_of_Characters_in_String


{
public static void main(String args[])
{
String str;
Scanner scan = new Scanner(System.in);

System.out.print("Enter a String : ");


str=scan.nextLine();

System.out.print("Total Number of Words in Entered Sentence is


" + countWords(str)+"\n\n");

System.out.print("Total Number of Characters in Entered


Sentence is " + countCharacter(str));
}

public static int countCharacter(String str)


{
int i, j, k, count=0;
char c, ch;
i=str.length();
for(c='A'; c<='z'; c++)
{
k=0;
for(j=0; j<i; j++)
{
ch = str.charAt(j);
if(ch == c)
{
k++;
count++;
}
}
if(k>0)
{
System.out.println("The character " + c + " has occurred for
" + k + " times");
}
}
return count;
}

public static int countWords(String str)


{
int count = 1;
for(int i=0; i<=str.length()-1; i++)
{
if(str.charAt(i) == ' ' && str.charAt(i+1)!=' ')
{
count++;
}
}
return count;
}
}

****************************OUTPUT****************************
Enter a String : This is GFGC Raibag
Total Number of Words in Entered Sentence is 4

The character C has occurred for 1 times


The character F has occurred for 1 times
The character G has occurred for 2 times
The character R has occurred for 1 times
The character T has occurred for 1 times
The character a has occurred for 2 times
The character b has occurred for 1 times
The character g has occurred for 1 times
The character h has occurred for 1 times
The character i has occurred for 3 times
The character s has occurred for 2 times

Total Number of Characters in Entered Sentence is 16


7. Write a java program to identify the significance of finally block in
handling exceptions.
class TestFinallyBlock1
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}

Output:
finally block is always executed
Exception in thread main java.lang.ArithmeticException: / by zero
8. Write a java program to access member variables of classes defined in
user created package.

/*Source code of package p1 under the directory C:\jdk1.6.0_26\bin>p1\edit


Student.java */
package p1;
public class Student
{
int regno;
String name;
public void getdata(int r,String s)
{
regno=r;
name=s;
}
public void putdata()
{
System.out.println("regno = " +regno);
System.out.println("name = " + name);
}
}

/* Source code of the main function under C:\jdk1.6.0_26\bin>edit StudentTest.java */


import p1.*;
class StudentTest
{
public static void main(String arg[])
{
student s=new student();
s.getdata(123,"xyz");
s.putdata();
}
}

*********************************OUTPUT****************************
C:\jdk1.6.0_26\bin>javac p1\Student.java
C:\jdk1.6.0_26\bin>javac StudentTest.java
C:\jdk1.6.0_26\bin>java StudentTest
regno = 123
name = xyz
9. Write a Java Program to implement multilevel inheritance by applying
various access controls to its data members and methods.

import java.io.DataInputStream;
class Student
{
private int rollno;
private String name;
DataInputStream dis=new DataInputStream(System.in);
public void getrollno()
{
try
{
System.out.println("Enter rollno ");
rollno=Integer.parseInt(dis.readLine());
System.out.println("Enter name ");
name=dis.readLine();
}
catch(Exception e){ }
}

void putrollno()
{
System.out.println("Roll No ="+rollno);
System.out.println("Name ="+name);
}
}

class Marks extends Student


{
protected int m1,m2,m3;
void getmarks()
{
try
{
System.out.println("Enter marks :");
m1=Integer.parseInt(dis.readLine());
m2=Integer.parseInt(dis.readLine());
m3=Integer.parseInt(dis.readLine());
}
catch(Exception e) { }
}

void putmarks()
{
System.out.println("m1="+m1);
System.out.println("m2="+m2);
System.out.println("m3="+m3);
}
}

class Result extends Marks


{
private float total;
void compute_display()
{
total=m1+m2+m3;
System.out.println("Total marks :" +total);
}
}

class MultilevelDemo
{
public static void main(String arg[])
{
Result r=new Result();
r.getrollno();
r.getmarks();
r.putrollno();
r.putmarks();
r.compute_display();
}
}
*********************OUTPUT*****************************
C:\jdk1.6.0_26\bin>javac MultilevelDemo.java
Note: MultilevelDemo.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
C:\jdk1.6.0_26\bin>java MultilevelDemo
Enter rollno
12345
Enter name
Avinash
Enter marks :
54
78
46
Roll No =12345
Name =Avinash
m1=54
m2=78
m3=46
Total marks :178.0
10. Write a Java Program to implement Vector class and its methods.
import java.lang.*;
import java.util.Vector;
import java.util.Enumeration;
class vectordemo
{
public static void main(String arg[])
{
Vector v=new Vector();
v.addElement("one");
v.addElement("two");
v.addElement("three");
v.insertElementAt("zero",0);
v.insertElementAt("oops",3);
v.insertElementAt("four",5);
System.out.println("Vector Size :"+v.size());
System.out.println("Vector apacity :"+v.capacity());
System.out.println(" The elements of a vector are :");
Enumeration e=v.elements();
while(e.hasMoreElements())
System.out.println(e.nextElement() +" ");
System.out.println();
System.out.println("The first element is : " +v.firstElement());
System.out.println("The last element is : " +v.lastElement());
System.out.println("The object oops is found at position :
"+v.indexOf("oops"));
v.removeElement("oops");
v.removeElementAt(1);
System.out.println("After removing 2 elements ");
System.out.println("Vector Size :"+v.size());
System.out.println("The elements of vector are :");
for(int i=0;i<v.size();i++)
System.out.println(v.elementAt(i)+" ");
}
}
**************************OUTPUT******************************
C:\jdk1.6.0_26\bin>javac vectordemo.java
C:\jdk1.6.0_26\bin>java vectordemo
Vector Size :6
Vector apacity :10
The elements of a vector are :
zero
one
two
oops
three
four

The first element is : zero


The last element is : four
The object oops is found at position : 3
After removing 2 elements
Vector Size :4
The elements of vector are :
zero
two
three
four
11. Write a program to demonstrate use of user defined packages.

Package is a keyword of Java followed by the package name. Just


writing the package statement followed by the name creates a new
package; see how simple Java is to practice. For this reason, Java is
known as a production language.

While create User Defined Packages Java, the order of statements is


very important. The order must be like this, else, compilation error.
1. Package statement
2. Import statement
3. Class declaration
package forest;
import java.util.*;
public class Tiger
{
public void getDetails(String nickName, int weight)
{
System.out.println("Tiger nick name is " + nickName);
System.out.println("Tiger weight is " + weight);
}
}

When the code is ready, the next job is compilation. We must compile
with package notation. Package notation uses –d compiler option as
follows.
C:\snr > javac -d . Tiger.java

The –d compiler option creates a new folder called forest and places
the Tiger.class in it. The dot (.) is an operating system's environment
variable that indicates the current directory. It is an instruction to the
OS to create a directory called forest and place the Tiger.class in it.

Using User Defined Packages Java


After creating the package let us use it.

2nd step: Set the classpath from the target directory.


Let us assume D:\sumathi is the target directory. Let us access
Tiger.class in forest package from here.
From the target directory set the classpath following way.
D:\vinay> set classpath=C:\snr;%classpath%;

classpath is another environment variable which gives the address of


the forest directory to the OS. %classpath% informs the OS to append
the already existing classpath to the current classpath that is right
now set.

3rd Step: Now finally, write a program from the target directory
D:\vinay and access the package.
D:\vinay> notepad Animal.java
import forest.Tiger;
public class Animal
{
public static void main(String args[])
{
Tiger t1 = new Tiger ();
t1.getDetails("Everest", 50);
}
}

The compilation and execution is as usual as follows.


D:\vinay>javac Animal.java
D:\vinay> java Animal
12. Write a java program to implement exception handling using multiple
catch statements.

public class MultipleCatchBlock1


{
public static void main(String[] args)
{
try
{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception
occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exc
eption occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

Output:
Arithmetic Exception occurs
rest of the code
13. Design stack and queue classes with necessary exception handling.
import java.util.*;

/* Class arrayStack */

class arrayStack
{
protected int arr[];
protected int top, size, len;

/* Constructor for arrayStack */


public arrayStack(int n)
{
size = n;
len = 0;
arr = new int[size];
top = -1;
}

/* Function to check if stack is empty */


public boolean isEmpty()
{
return top == -1;
}

/* Function to check if stack is full */


public boolean isFull()
{
return top == size -1 ;
}

/* Function to get the size of the stack */


public int getSize()
{
return len ;
}

/* Function to check the top element of the stack */


public int peek()
{
if( isEmpty() )
throw new NoSuchElementException("Underflow
Exception");
return arr[top];
}

/* Function to add an element to the stack */


public void push(int i)
{
if(top + 1 >= size)
throw new IndexOutOfBoundsException("Overflow
Exception");
if(top + 1 < size )
arr[++top] = i;
len++ ;
}

/* Function to delete an element from the stack */


public int pop()
{
if( isEmpty() )
throw new NoSuchElementException("Underflow
Exception");
len-- ;
return arr[top--];
}

/* Function to display the status of the stack */


public void display()
{
System.out.print("\nStack = ");
if (len == 0)
{
System.out.print("Empty\n");
return ;
}
for (int i = top; i >= 0; i--)
System.out.print(arr[i]+" ");
System.out.println();
}
}

/* Class StackImplement */
public class StackImplement
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Stack Test\n");
System.out.println("Enter Size of Integer Stack ");
int n = scan.nextInt();

/* Creating object of class arrayStack */


arrayStack stk = new arrayStack(n);

/* Perform Stack Operations */


char ch;
do
{
System.out.println("\nStack Operations");
System.out.println("1. push");
System.out.println("2. pop");
System.out.println("3. peek");
System.out.println("4. check empty");
System.out.println("5. check full");
System.out.println("6. size");
int choice = scan.nextInt();
switch (choice)
{
case 1 : System.out.println("Enter integer
element to push");
try
{
stk.push( scan.nextInt() );
}
catch (Exception e)
{
System.out.println("Error : " +
e.getMessage());
}
break;

case 2 :
try
{
System.out.println("Popped Element = " +
stk.pop());
}
catch (Exception e)
{
System.out.println("Error : " +
e.getMessage());
}
break;

case 3 :
try
{
System.out.println("Peek Element = " +
stk.peek());
}
catch (Exception e)
{
System.out.println("Error : " +
e.getMessage());
}
break;

case 4 :
System.out.println("Empty status = " +
stk.isEmpty());
break;

case 5 :
System.out.println("Full status = " +
stk.isFull());
break;

case 6 :
System.out.println("Size = " +
stk.getSize());
break;

default :
System.out.println("Wrong Entry \n ");
break;
}

/* display stack */
stk.display();
System.out.println("\nDo you want to continue (Type y
or n) \n");
ch = scan.next().charAt(0);
}
while (ch == 'Y'|| ch == 'y');
}
}

OutPut:
Stack Test

Enter Size of Integer Stack


5

Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size

4
Empty status = true
Stack = Empty

Do you want to continue (Type y or n)


y

Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size

1
Enter integer element to push
24

Stack = 24

Do you want to continue (Type y or n)


y

Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size

1
Enter integer element to push
6

Stack = 6 24

Do you want to continue (Type y or n)


y
14. Write a Java program to illustrate basic calculator using grid layout
manager.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*<applet code="Calculator1" width=300 height=300></applet>*/

public class Calculator1 extends Applet implements ActionListener


{
TextField t;
Button b[]=new Button[15];
Button b1[]=new Button[6];
String op2[]={"+","-","*","%","=","C"};
String str1="";
int p=0,q=0;
String oper;
public void init()
{
setLayout(new GridLayout(5,4));
t=new TextField(20);
setBackground(Color.pink);
setFont(new Font("Arial",Font.BOLD,20));
int k=0;
t.setEditable(false);
t.setBackground(Color.white);
t.setText("0");
for(int i=0;i<10;i++)
{
b[i]=new Button(""+k);
add(b[i]);
k++;
b[i].setBackground(Color.pink);
b[i].addActionListener(this);
}

for(int i=0;i<6;i++)
{
b1[i]=new Button(""+op2[i]);
add(b1[i]);
b1[i].setBackground(Color.pink);
b1[i].addActionListener(this);
}
add(t);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("+"))
{
p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("-"))
{
p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("*"))
{
p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("%"))
{
p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("="))
{
str1="";
if(oper.equals("+"))
{
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p+q)));
}
else if(oper.equals("-"))
{
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p-q)));
}
else if(oper.equals("*"))
{
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p*q)));
}
else if(oper.equals("%"))
{
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p%q)));
}
}
else if(str.equals("C"))
{
p=0;q=0;
t.setText("");
str1="";
t.setText("0");
}
else
{
t.setText(str1.concat(str));
str1=t.getText();
}
}
}
15. Illustrate creation of thread by extending Thread class.

import java.lang.Thread;
class A extends Thread
{
public void run()
{
System.out.println("thread A is started:");
for(int i=1;i<=5;i++)
{
System.out.println("\t from thread A:i="+i);
}
System.out.println("exit from thread A:");
}
}

class B extends Thread


{
public void run()
{
System.out.println("thread B is started:");
for(int j=1;j<=5;j++)
{
System.out.println("\t from thread B:j="+j);
}
System.out.println("exit from thread B:");
}
}

class C extends Thread


{
public void run()
{
System.out.println("thread C is started:");
for(int k=1;k<=5;k++)
{
System.out.println("\t from thread C:k="+k);
}
System.out.println("exit from thread C:");
}
}

class Threadtest
{
public static void main(String arg[])
{
new A().start();
new B().start();
new C().start();
}
}

*********************************OUTPUT****************************
thread A is started:
thread B is started:
thread C is started:
from thread A:i=1
from thread B:j=1
from thread C:k=1
from thread A:i=2
from thread B:j=2
from thread C:k=2
from thread A:i=3
from thread B:j=3
from thread C:k=3
from thread A:i=4
from thread B:j=4
from thread C:k=4
from thread A:i=5
from thread B:j=5
from thread C:k=5
exit from thread A:
exit from thread B:
exit from thread C:
16. Illustrate thread creation by implementing runnable interface.

import java.lang.Runnable;

class X implements Runnable


{
public void run()
{
for(int i=1;i<10;i++)
{
System.out.println("\t Thread X:"+i);
}
System.out.println("End of Thread X");
}
}

class Runnabletest
{
public static void main(String arg[])
{
X R=new X();
Thread T=new Thread(R);
T.start();
}
}

*********************************OUTPUT****************************
Thread X:1
Thread X:2
Thread X:3
Thread X:4
Thread X:5
Thread X:6
Thread X:7
Thread X:8
Thread X:9
End of Thread X

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy