Java Programming Concepts and Examples
Java Programming Concepts and Examples
com
Model Questions
Group A
i. What is use of valueOf () function?
All enumerations automatically have two predefined methods: values () and valueOf (). The general syntax for
valueOf() method is:
public static enum-type valueOf(String str);
The valueOf() method returns the enumeration constant whose value corresponds to the string passes in str.
[Link]
[Link]
prevent errors. With auto boxing it is not necessary to manually construct an object in order to wrap a primitive
type. For example;
Integer I = 300;
The object I is not explicitly created through the use of new. Java handles this automatically.
Group “B”
[Link] a Java program to display all the numbers between -300 to -1 which when divided by 17
gives 7 as remainder and also displays sum of those numbers.
public class Sum {
public static void main(String[] args) {
int i,s=0;
for(i=-300;i<-1;i++)
{
if(i%17==-7){
[Link] two threads, one displays odd number after one second and another thread display even
number after half second between -200 and -10.
class Odd extends Thread{
public void run(){
for(int i=-200;i<=-10;i++){
try{
[Link](1000);
}catch(InterruptedException e){
[Link]("Thread Interrupted ");
}
if(i%2==-1)
[Link](" "+i);
}
}
}
class Even extends Thread{
public void run(){
for(int i=-200;i<=-10;i++){
try{
[Link](500);
[Link]
[Link]
}catch(InterruptedException e){
[Link]("Thread Interrupted ");
}
if(i%2==0)
[Link] (" "+i);
}
}
}
public class EvenOddDemo {
public static void main(String[] args) {
Odd o = new Odd();
Even e = new Even();
[Link]();
[Link]();
}
}
4. Write a program that displays all the read-only files of a given folder.
import [Link].*;
public class FileList {
public static void main(String[] args) {
File dir = new File("e:/java");
if([Link]()){
String[] s = [Link]();
for(int i=0;i<[Link];i++){
File f = new File(dir+"/"+s[i]);
if([Link]())
[Link](s[i]);
}
}
else
[Link]("Its is not directory");
}
}
[Link] a class named student with private member variables name, age, and public functions to set,
display and return values of member variables. Then create ten objects of the student class, set them and
display the name of youngest student in the main function of another class named
student_demo.
class Student{
private String name;
private int age;
public void setData(String n, int a ){
name = n;
age =a;
}
public void display(){
[Link]
[Link]
[Link]("Name : "+name);
[Link]("Age : "+age);
}
public int getAge(){
return age;
}
public String getName(){
return name;
}
}
class StudentDemo {
public static void main(String[] args) {
int minage,j=0;
Student []s = new Student[10];
for(int i=0;i<[Link];i++)
s[i] = new Student();
s[0].setData("Kamal", 22);
s[1].setData("Suresh", 21);
s[2].setData("Binita", 20);
s[3].setData("Kamala", 29);
s[4].setData("keshav", 50);
s[5].setData("Raju", 11);
s[6].setData("Hari", 88);
s[7].setData("Krishna", 1);
s[8].setData("Ram", 40);
s[9].setData("Bimala", 30);
minage = s[0].getAge();
for(int i=1;i<[Link];i++){
if(minage>s[i].getAge()){
minage = s[i].getAge();
j = i;
}
}
[Link]("The name of the student with minimum age is "+s[j].getName());
}
}
6. Write a super class named furniture with member variables weight and price. From this furniture class
derive class named chair. These both super and sub classes have functions to set values of their member
variables. In another class, named furn_demo make objects of class chair and display values of member
variables of those objects.
class Furniture{
private int weight;
private int price;
public void setData(int w, int p){
weight = w;
[Link]
[Link]
price = p;
}
public void display(){
[Link]("Weight:"+weight);
[Link]("Price : "+price);
}
}
class Chair extends Furniture{
private String color;
public void setData(int w, int p, String c){
[Link](w, p);
color = c;
}
public void display(){
[Link]();
[Link]("Color :"+color);
}
}
public class Furn_Demo {
public static void main(String[] args) {
Chair ch = new Chair();
[Link](20, 400, "Red");
[Link]();
}
}
Group “C”
Ans: An exception is an event which occurs during the execution of a program that disrupts the normal flow of
the program's instructions. Java terminology, creating object and handling it to the runtime system called
throwing an exception. The exception handler chosen is said to catch the exception.
ArrayIndexOutOfBoundsException: This is runtime exception. This exception is thrown to indicate that an array
has been accessed with an illegal index. The index is either negative or greater or equal to the size of the array.
[Link]
[Link]
for(int i=0;i<=[Link];i++)
[Link] (arr[i]+ " ");
}catch(ArrayIndexOutOfBoundsException e){
[Link]("Exception Occurred "+e);
}
}
}
Output:-
[Link]
[Link]
Year 2015
1. What is JVM?
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in
which java byte code can be executed. JVMs are available for many hardware and software platforms (i.e. JVM
is platform dependent).
2. What is operator?
An operator, in Java, is a special symbols performing specific operations on one, two or three operands and then
returning a result.
[Link]
[Link]
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a
way to destroy the unused objects. To do so, we were using free() function in C language and delete() in C++.
But, in java it is performed automatically. So, java provides better memory management.
Advantage of Garbage Collection
• It makes java memory efficient because garbage collector removes the unreferenced objects from heap
memory.
• It is automatically done by the garbage collector (a part of JVM) so we don't need to make extra efforts.
[Link]
[Link]
13. Write a program that reads line of text from keyboard and write to file. Also read the content of the
same file and display on monitor.
import [Link].*;
class ReadingFromKeyBoard {
public static void main(String args[]) throws IOException {
String str;
BufferedReader br = new BufferedReader(new InputStreamReader ([Link]));
FileWriter fw=null;
[Link]("Enter line of text and 'stop' at the end");
try{
fw = new FileWriter("d://janak//[Link]");
do{
str = [Link]();
if([Link] ("stop")==0)break;
str = str+"\r\n";
[Link](str);
}while([Link]("stop")!=0);
}catch(IOException e){
[Link]("I/O Error occured");
}
finally{
if(fw!=null)
[Link]();
}
}
}
[Link] 14
class Rectange{
int length,breadth,area;
public void computeArea(int l, int b){
length=l;
breadth=b;
area=length*breadth;
}
public void displayArea(){
[Link]("The area is: " +area);
}
}
public class tu15Q14 extends Rectang{
public static void main(String[] args) {
Rectang obj1= new Rectang();
[Link](10, 20);
[Link]
[Link]
if([Link]>[Link]){
[Link]();
}
else
{
[Link]();
}
}
15. Make an interface named num with two functions int add (int x, int y) and int diff(int x, int y) then
make a class that implements that interface num
interface num{
int add(int x,int y);
int diff(int x,int y);
}
@Override
public int diff(int x,int y){
sub=x-y;
[Link]("The difference is "+sub);
return sub;
}
public static void main(String[] args) {
calc obj=new calc();
[Link](2, 3);
[Link](30, 20);
[Link]
[Link]
}
}
Group C
16. What is an exception? Explain nested try catch with example.
An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is
a run time error. When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore these exceptions are to be
handled.
[Link]
[Link]
example
Year 2016
1. What is an operator?
An operator, in Java, is a special symbols performing specific operations on one, two or three operands and then
returning a result.
4. Define multithreading?
Java is a multi-threaded programming language which means we can develop multi-threaded program using
Java. A multi-threaded program contains two or more parts that can run concurrently and each part can handle a
different task at the same time making optimal use of the available resources specially when your computer has
multiple CPUs.
[Link]
[Link]
10. What difference do you find between “final” and “finally” keywords .
Final class can't be inherited, final method can't be overridden and final variable value can't be changed. Finally
is used to place important code, it will be executed whether exception is handled or not. Finalize is used to
perform clean up processing just before object is garbage collected.
[Link] 11
public class tu16Q11 {
public static void main(String[] args) {
int [] a={1,22,23,3,4,67,87,23,56,35,47,5,61,7,80,9,23,23,45,456,345,67,0,23,45,67,87,1,3,4};
for(int i=0;i<30;i++){
if(a[i]>16 &&a[i]<47){
[Link](a[i]);
}
}
}
}
or
import [Link].*;
public class ArrayDemo {
public static void main(String[] args) {
int arr[] = new int[30];
Random r = new Random();
int i;
for(i=0;i<[Link];i++){
int num = [Link]()%50;
arr[i] = num;
}
for(i=0;i<[Link];i++){
if(arr[i]>16&&arr[i]<47)
[Link](arr[i]+" ");
}
[Link]
[Link]
}
}
[Link] 12 Create two classes Thread A and Thread B which implement Runnable interface. Thread A
displays all even numbers from 50 to 100 and Thread B displays all odd numbers from 100 to 200. Define
a main class which creates the objects of both the classes and displays the numbers as per the above
mentioned specifications .
class ThreadA implements Runnable{
public void run(){
int i;
for(i=50;i<100;i++){
if(i%2==0){
[Link](i);
}
}
}
}
class ThreadB implements Runnable{
public void run(){
int j;
for(j=100;j<200;j++){
if(j%2==1){
[Link](j);
}
}
}
}
public class tu16Q12 {
public static void main(String[] args) {
ThreadA t1=new ThreadA();
Thread objA=new Thread(t1);
[Link]();
13. Create an interface called Calculate which has methods int add (int x, int y) and diff (int x, int y) to
perform addition and subtraction of numbers passed as arguments. Then define a class that implements
interface calculate .
[Link]
[Link]
interface Calculate{
int add(int x, int y);
int diff(int x, int y);
}
class Calculator implements Calculate{
public int add(int x,int y){
return x+y;
}
public int diff(int x,int y){
return x-y;
}
}
public class CalculatorDemo {
public static void main(String[] args) {
Calculator c = new Calculator();
[Link]("The sum of 4 and 5 is ="+[Link](4, 5));
[Link]("The difference of 10 and 5 ="+[Link](10, 5));
14. Define String array of size 4 and store name of 4 students. Then display the names of students whose
name has character ‘t’
public class tu16Q14 {
public static void main(String[] args) {
String []name={"abc","ukutyy","ags","yasty"};
for(int i=0;i<4;i++){
if(name[i].contains("t")){
[Link](name[i]);
}
}
}
}
15. Write a program that displays content of folder database stored in d: drive.
import [Link];
public class DirList {
public static void main(String[] args) {
String dirname = “D:/database";
File f1 = new File(dirname);
if([Link]()){
String s[] = [Link]();
for(int i=0;i<[Link];i++){
File f = new File(dirname+ "/"+s[i]);
if([Link]()){
[Link](s[i]+" is a directory");
}
else
[Link]
[Link]
[Link](s[i]+" is a file");
}
}
}
}
Group C
16: Explain dynamic polymorphism with example.
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is
resolved at runtime rather than compile-time. In this process, an overridden method is called through the
reference variable of a super class. The determination of the method to be called is based on the object being
referred to by the reference variable.
class Bike{
void run(){[Link]("running");}
}
class Splender extends Bike{
void run(){[Link]("running safely with 60km");
}
}
public class DynamicPolymorphismDemo {
public static void main(String[] args) {
Bike b;
Splender s = new Splender();
Bike b1 = new Bike();
b = b1;
[Link]();
b = s;
[Link]();
}
}
17. What is exception? Write a program to catch the ArrayIndexOutOfBoundsException.
An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is
a run time error. When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore these exceptions are to be
handled. Some reasons that may cause exception to occur
• A user has entered invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications or the JVM has run out of memory.
[Link]
[Link]
Year 2017
[Link] Recursion
Recursion in java is a process in which a method calls itself continuously. A method in java that calls itself is
called recursive method
[Link]
[Link]
[Link] 11
}
}
}
[Link] 12
class Student {
int roll_no;
}
class Test extends Student{
int markJava,markWeb;
}
class Results extends Test{
[Link]
[Link]
int total;
public void calculate(){
total=markJava+markWeb;
}
public void display(){
[Link]("The total marks is :"+total);
}
public static void main(String[] args) {
Results obj=new Results();
[Link](1);
[Link](49,40);
[Link]();
[Link]();
[Link]();
[Link]();
[Link] 13
interface Shape{
public void get_data(int l,int b);
public void display_area();
}
class Rectangle implements Shape{
int length,breadth,area;
public void get_data(int l,int b){
length=l;
breadth=b;
}
public void display_area(){
area=length*breadth;
[Link]("The area of rectangle is:"+area);
}
}
class Square implements Shape{
int length,breadth,area;
public void get_data(int l,int b)
{
length=l;
}
public void display_area(){
area=length*length;
[Link]
[Link]
[Link] 14
public class tu17Q14 {
public static void main(String[] args) {
String []country={"Nepal","USA","Australia","Brazil","Paragua","Canada"};
int i;
for(i=0;i<6;i++){
if(country[i].endsWith("a")){
[Link](country[i]);
}
}
}
[Link]
[Link]
Make an array of integers of size 30, store 30 integers, then display that are between 16 and 47.
import [Link];
class ArraySize30Demo {
public static void main(String args[]){
Scanner in=new Scanner([Link]);
int arr[]=new int[10];
int i;
for(i=0; i<[Link]; i++){
int num=[Link]();
}
for(i=0; i<[Link]; i++){
if (arr[i]>16 && arr[i]<47)
{
[Link](arr[i]);
}
}
}
}
Write a program to get sum of 10 numbers.
import [Link];
public class sum2019 {
public static void main(String args[]){
int sum=0, avg=0;
Scanner in=new Scanner([Link]);
[Link]("Enter the elements");
int a[]=new int[10];
for(int i=0; i<[Link]; i++){
[Link]
[Link]
a[i]=[Link]();
{
[Link]("Elements are:"+a[i]);
sum=sum+a[i];
}
avg=sum/[Link];
}
[Link]("The sum is:"+sum);
[Link]("The average is:"+avg);
}
}
Write a java program that asks the user to enter numbers in the array of size n. Then displays only the
numbers that are divisible by 2 and 3.
import [Link];
public class DivisibleBy2and3 {
public static void main(String args[]){
int i, n;
Scanner in=new Scanner([Link]);
[Link]("Enter the size of n");
n=[Link]();
[Link]("Enter the elements");
int num[]=new int[n];
for(i=0; i<n; i++){
num[i]=[Link]();
if(num[i]%2==0 && num[i]%3==0){
}
[Link](num[i]);
}
}
}
Create two classes ThreadA and ThreadB which implements Runnable interface. ThreadA displays all
even numbers from 50 to 100 and ThreadB displays all odd numbers from 100 to 200. Define a main class
which creates the objects of the both the classes and displays the numbers as per the above mentioned
specifications.
class ThreadA implements Runnable{
public void run(){
int i;
for(i=50;i<100;i++){
if(i%2==0){
[Link](i);
}
}
}
}
class ThreadB implements Runnable{
public void run(){
[Link]
[Link]
int j;
for(j=100;j<200;j++){
if(j%2==1){
[Link](j);
}
}
}
}
public class TU2016Q12 {
public static void main(String[] args) {
ThreadA t1=new ThreadA();
Thread objA=new Thread(t1);
[Link]();
ThreadB t2=new ThreadB();
Thread objB=new Thread(t2);
[Link]();
}
}
Write a Java program that creates two threads, one displays numbers from 1 to 100 after one second and
another thread displays numbers from 100 to 1 after one and half second.
class ThreadOne extends Thread{
public void run(){
try{
for(int i=0;i<=100;i++){
[Link](i+" ");
[Link](1000);
}
}catch(InterruptedException e){
[Link]("Thread interrupted");
}
}
}
class ThreadTwo extends Thread{
public void run(){
try{
for(int i=100;i>=0;i--){
[Link](i+" ");
[Link](1500);
}
}catch(InterruptedException e){
[Link]("Thread interrupted");
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
[Link]
[Link]
[Link]
[Link]
}
}
}
Write a java program to Demonstrate throw Exception.
class ThrowDemo
{
static void demoproc(){
try{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
[Link]("Caught inside demoproc");
throw e;//rethrow the exception
}
}
public static void main (String args[])
{
try{
demoproc();
}
catch(NullPointerException e)
{
[Link]("Recaught:" +e);
}
}
}
Write a java program to show use of Super keyword in Inheritance.
class dog{
String color = "black";
String habit = "bark";
void behave() {
[Link](color);
[Link](habit);
}
}
class Kitten extends dog{
String color = "white";
void bark()
{
[Link]([Link]);
[Link](habit);
}
}
public class SupperInheritance {
public static void main(String[] args) {
[Link]
[Link]
[Link]
[Link]
Create a class Number with two int instance variable x and y. The class will have one constructor. The
class also will contain method getMax() method that will return larger number. Create a class
NumberDemo with main method that will create an object of Number and will print the larger number.
class Number{
int x,y;
Number(){
x=10;
y=20;
}
int getMax(){
if(x>y)
return x;
else
return y;
}}
public class numberDemo {
public static void main(String[] args) {
[Link]
[Link]
Create a class Number with three int instance variable x ,y and z. The class will have one constructor. The
class also will contain method getMax() method that will return larger number. Create a class
NumberDemo with main method that will create an object of Number and will print the larger number.
class Number2{
int x,y,z;
Number2()
{
x=10; y=20; z=30;
}
int getMax(){
if(x>y && x>z){
return x;
}
else if(y>x && y>z){
return y;
}
else
return z;
}}
public class numberDemo2 {
public static void main(String[] args) {
Number2 n= new Number2();
[Link]("The Largest Number :"+[Link]());
}}
Create a class Swapper class with two integer instance variablex and y and constructor with two
parameters that initializes the two variables. Also include three methods: A getX () method that returns x,
a getY () method that returns y, a void swap () method that swaps the values of x and y. Then create a
SwapperDemo class that tests all the methods.
class Swapper{
int x,y;
Swapper(){
x=13;
y=15;
}
int getx(){
return x;
}
int gety(){
return y;
}
void swap(){
x=x+y;
[Link]
[Link]
y=x-y;
x=x-y;
}
}
public class swapperDemo {
public static void main(String[] args) {
Swapper s=new Swapper();
[Link]("Number before swappingg");
[Link]("x = "+[Link]());
[Link]("y = "+[Link]());
[Link]("Number after swapping");
[Link]();
[Link]("x = "+[Link]());
[Link]("y = "+[Link]());
}
}
Create a Die class with one integer variable called sideUp. Give up. Give it a constructor and a
getSideUp() method that returns the value of sideUp and a void roll() method that changes sideUp() to a
random value from 1 to 6. Then create a DieDemo class with a main method that creates two Die objects,
rolls them, and prints the sum of the two sides up.
class Die{
int sideUp;
Die(){
sideUp=0;
}
int getSideUp(){
return sideUp;
}
void roll(){
sideUp = (int)([Link]()*6) + 1;
}
}
public class dieDemo {
public static void main(String[] args) {
Die dice1=new Die();
Die dice2=new Die();
int sum;
[Link]();
[Link]("First roll : "+[Link]());
[Link]();
[Link]("Second roll : "+[Link]());
sum=[Link]()+[Link]();
[Link]("The sum of sideUp when dice rolled two times : "+sum);
[Link]
[Link]
}
Define a string array of size 10 and store 10 countries name in it. Then list name of countries that ends
with letter a.
import [Link];
public class tu201714 {
public static void main(String args[])
{
Scanner in=new Scanner([Link]);
[Link]("Ener the array size");
int n=[Link]();
[Link]("Enter the elememts");
String a[]=new String [n];
for(int i=0; i<[Link]; i++){
a[i]=[Link]();
if((a[i].contains("a")))
{
[Link](a[i]);
}
}
}
}
Write a program that asks the user to enter names of any 7 countries. Then the user is required to count
and display those countries that ends with a vowel.
import [Link];
public class TU2019StringRaviFinal {
public static void main(String args[]){
Scanner in=new Scanner([Link]);
int i, count=0;
[Link]("Enter the name of the country");
String country[]=new String[2];
for(i=0; i<[Link]; i++){
country[i]=[Link]();
}
for(i=0; i<[Link];i++){
if(country[i].endsWith("a")==true ||country[i].endsWith("e")==true
||country[i].endsWith("i")==true ||country[i].endsWith("o")==true ||country[i].endsWith("u")==true)
{
count++;
}}
[Link]("count="+count);
}
}
Write a program to create a string array of size n and promote the user to enter 10 names in it. Then you
are required to replace all “i” with “!” and display the result.
import [Link];
[Link]
[Link]
a[i]=(a[i].replace('i','!'));
{
[Link](a[i]);
}
}}}
Define String array of size 4 and store name of 4 students. Then display the name of students whose name
has character e.
import [Link];
public class Tu2016String {
public static void main(String args[]){
Scanner in=new Scanner([Link]);
int i;
[Link]("Enter the name of the country");
String name[]=new String[4];
for(i=0; i<[Link]; i++){
name[i]=[Link]();
}
for(i=0; i<[Link];i++){
if(name[i].contains("e")) {
[Link]("Name of Country which contains e charater:"+name[i]);
}
}
}
}
Write a program that reads line of text from keyboard and write to file. Also read the content of the same
file and display on monitor
import [Link].*;
class ReadingFromKeyBoard {
public static void main(String args[]) throws IOException {
String str;
BufferedReader br = new BufferedReader(new InputStreamReader ([Link]));
FileWriter fw=null;
[Link]("Enter line of text and 'stop' at the end");
try{
[Link]
[Link]
fw = new FileWriter("d://janak//[Link]");
do{
str = [Link]();
if([Link] ("stop")==0)break;
str = str+"\r\n";
[Link](str);
}while([Link]("stop")!=0);
}catch(IOException e){
[Link]("I/O Error occured");
}
finally{
if(fw!=null)
[Link]();
}
}
}
Write a program to take employee id, name, address, DOB and phone number from user and then store
it in a file called “[Link]”. Also display the content of “[Link]”.
import [Link].*;
import [Link];
public class Question152017 {
public static void main(String args[])
{
try{
FileOutputStream fout=new FileOutputStream("[Link]");
PrintStream pout=new PrintStream(fout);
[Link]
[Link]
[Link]("success...");
FileInputStream fin=new FileInputStream("[Link]");
int i=0;
while((i=[Link]())!=-1){
[Link]((char)i);
}
[Link]();
}
catch(Exception e)
{
[Link](e);
}
}
}
Write a program that ask the user to enter his/her name, address and college and store it in a file called
“[Link]”. Then copy the contents of “[Link]” to “[Link]”. Also display the content of
“[Link]”.
import [Link].*;
import [Link];
[Link]
[Link]
while((i=[Link]())!=-1)
{
[Link]((byte)i);
}
[Link]();
[Link]();
[Link]("File has been copied");
}
catch(Exception e)
{
[Link](e);
}
}
}
Make a thread using runnable interface to display number from 1 to 20; each number should be
displayed in the interval of 2 seconds.
//This class is made as a thread by implementing "Runnable" interface.
public class FirstThread implements Runnable
{
//This method will be executed when this thread is executed
public void run()
{
//Looping from 1 to 20 to display numbers from 1 to 20
for ( int i=1; i<=20; i++)
{
//Displaying the numbers from this thread
[Link]( "Messag from First Thread : " +i);
[Link]
[Link]
}
}
Make an interface named num with two functions int add (int x, int y) and int diff(int x, int y) then make a
class the implements that interface num.
interface Num }
{
int add(int x, int y);
int sub(int x, int y);
}
class XYZ implements Num
{
public int add(int x, int y)
{
[Link](x+y); interface Num
} {
int add(int x, int y);
public void sub(int x, int y) { int diff(int x, int y);
}
[Link](x-y); class Calculator implements Num
} {
} public int add(int x,int y){
return x+y;
public class Program { }
public static void main(String[] args) public int diff(int x,int y)
{ {
return x-y;
XYZ obj = new XYZ(); }
[Link](2,6); }
[Link](4,7);
} public class CalculatorDemo {
[Link]
[Link]
[Link]
[Link]
• fw = new • finally{
FileWriter("d://janak//[Link]"); • if(fw!=null)
do{ • [Link]();
• str = [Link](); • }
if([Link] •
("stop")==0)break; • }
• str = str+"\r\n"; • }
• [Link](str);
•
}while([Link]("stop")!=0);
• }catch(IOException e){
• [Link]("I/O Error
occured");
}
Make a thread using Runnable interface to display numbers from 1 to 20, each number should be displayed in
the interval of 2 seconds.
class ThreadNum implements Runnable{
public void run(){
try{
for(int i=1;i<=20;i++){
[Link](i+" ");
[Link](2000);
}
}catch(InterruptedException e){
[Link]("Thread Interrupted");
}
}
}
public class EvenNumThreadDemo {
public static void main(String[] args) {
ThreadNum n = new ThreadNum();
Thread t = new Thread(n);
[Link]();
}
}
Write a Java Program to display all the even numbers from 1 to 500
public class EvenNumDemo {
[Link]
[Link]
2016
[Link] an array of integers of size 30, store 30 integers, then display integers that are between 16 and 47.
import [Link].*;
public class ArrayDemo {
public static void main(String[] args) {
int arr[] = new int[30];
Random r = new Random();
int i;
for(i=0;i<[Link];i++){
int num = [Link]()%50;
arr[i] = num;
}
for(i=0;i<[Link];i++){
if(arr[i]>16&&arr[i]<47)
[Link](arr[i]+" ");
} } }
12. Create two classes ThreadA and ThreadB which implement Runnable interface. ThreadA displays all even
numbers from 50 to 100 and ThreadB displays all odd numbers from 100 to 200. Define a main class which
creates the objects of both the classes and displays the numbers as per the above mentioned specifications .
class ThreadA implements Runnable{
public void run(){
for(int i=50;i<=100;i++){
if(i%2==0)
[Link](i+“ ");
} } }
class ThreadB implements Runnable{
[Link]
[Link]
[Link]
[Link]
[Link](s[i]+" is a file");
}
}
}
}
Model Question
2. Write a Java program to display all the numbers between -300 to -1 which when divided by 17 gives 7 as
remainder and also displays sum of those numbers.
public class Sum {
public static void main(String[] args) {
int i,s=0;
for(i=-300;i<-1;i++)
{
if(i%17==-7){
[Link](i+ " ");
s = s+i;
}
}
[Link]("The sum = "+s);
}
}
Write a program that creates an integer array of length 30, fills the array with the sequence 1,-2,3,-4,…..29,-30 using a
for loop. Also print the above sequence using for loop.
[Link]
[Link]
}
}
Make two threads, one displays odd number after one second and another thread display even
• class Odd extends Thread.
public void run(){
for(int i=-200;i<=-10;i++){
try{
[Link](1000);
}catch(InterruptedException e){
[Link]("Thread Interrupted ");
}
if(i%2==-1)
[Link](" "+i);
}
}
}
class Even extends Thread{
public void run(){
for(int i=-200;i<=-10;i++){
try{
[Link](500);
}catch(InterruptedException e){
[Link]("Thread Interrupted ");
}
if(i%2==0)
[Link] (" "+i);
}
}
}
public class EvenOddDemo {
public static void main(String[] args) {
Odd o = new Odd();
Even e = new Even();
[Link]();
[Link]();
[Link]
[Link]
}
}
number after half second between -200 and -10.
[Link]
[Link]
Write a program that displays all the read-only files of a given folder.
import [Link].*;
public class FileList {
public static void main(String[] args) {
File dir = new File("e:/java");
if([Link]()){
String[] s = [Link]();
for(int i=0;i<[Link];i++){
File f = new File(dir+"/"+s[i]);
if([Link]())
[Link](s[i]);
}
}
else
[Link]("Its is not directory");
}
}
Write a program that creates an integer array of size 20 and then uses a for loop to check whether the array is
sorted from smallest to largest. If so, print sorted. Otherwise, prints “Not sorted”.
public class SortingTestDemo {
public static void main(String[] args) {
int arr[] = {1,4,3,5,7,8,11,22,33,10,11,18,17,20,29,28,22,99,88,44};
boolean b = true;
for(int i=0;i<[Link]-1;i++){
if(arr[i+1]<arr[i]){
b=false;
break;
}
}
if(b)
[Link]("Array is sorted");
else
[Link]("Array is not sorted");
}
5. Make a class named student with private member variables name, age, and public functions to set, display and
return values of member variables. Then create ten objects of the student class, set them and display the name of
youngest student in the main function of another class named student_demo.
class Student{
private String name;
private int age;
[Link]
}
}
Write a super class named furniture with member variables weight and price. From this furniture class derive class
named chair. These both super and sub classes have functions to set values of their member variables. In another
class, named furn_demo make objects of class chair and display values of member variables of those objects.
class Furniture{
private int weight;
private int price;
public void setData(int w, int p){
weight = w;
price = p;
}
public void display(){
[Link]("Weight:"+weight);
[Link]("Price : "+price);
}
}
[Link]
} }
Write a program that creates an array of doubles of length 50. It then fills the array with the sequence of values
21/2,21/4,21/8,21/16,,… and then loops through the array printing out the values.
public class twoPower {
public static void main(String[] args) {
double arr[]=new double[50];
int i,j=1;
for(i=0;i<50;i++){
arr[i] = [Link](2,1/([Link](2,j)));
j=j+1;
}
for(i=0;i<50;i++){
[Link](arr[i]+",");
}}}
Write a program that creates two integer arrays data1 and data2, possibly of different lengths. Then it uses for
loops to create a new array data3 whose length is the sum of the lengths of data1 and data2 and whose contents
consists of the contents of data1 followed by contents of data2. For example, if the two arrays are {1,2,3} and
{4,5,6,7}, then the code should create the new array {1,2,3,4,5,6,7}.
import [Link];
public class threeArray {
public static void main(String[] args) {
Scanner s=new Scanner([Link]);
int n=5,m=8,i;
int data1[] = new int[n];
int data2[]=new int[m];
int data3[]=new int[n+m];
[Link]("Enter the elements of first array");
for(i=0;i<[Link];i++){
data1[i]=[Link]();
}
[Link]("Enter the elements of second array");
for(i=0;i<[Link];i++){
data2[i]=[Link]();
}
[Link]("Elements of Combined array ");
for(i=0;i<[Link];i++){
data3[i]=data1[i];
}
[Link]
for(i=0;i<[Link];i++){
data3[i+n]=data2[i];
}
for(i=0;i<[Link];i++)
{
[Link](data3[i]+",");
} } }
Write a program that creates an integer array and then uses a for loop to check whether the array is sorted from
smallest to largest. If so, print sorted. Otherwise, prints “Not sorted”.
public class checkArray {
public static void main(String[] args) {
int arr[]={7,3,4,9,2,13,5};
int i;
for(i=0;i<[Link]-1;i++){
if(arr[i]<arr[i+1]){
[Link]("Array is sorted");
break;
}
else
[Link]("Array is not sorted");
break;
}} }
Create a Die class with one integer variable called sideUp. Give up. Give it a constructor and a getSideUp() method
that returns the value of sideUp and a void roll() method that changes sideUp() to a random value from 1 to 6.
Then create a DieDemo class with a main method that creates two Die objects, rolls them, and prints the sum of
the two sides up.
class Die{
int sideUp;
Die(){
sideUp=0;
}
int getSideUp(){
return sideUp;
}
void roll(){
sideUp = (int)([Link]()*6) + 1;
}
}
public class dieDemo {
public static void main(String[] args) {
Die dice1=new Die();
Die dice2=new Die();
int sum;
[Link]();
[Link]("First roll : "+[Link]());
[Link]();
[Link]("Second roll : "+[Link]());
sum=[Link]()+[Link]();
[Link]("The sum of sideUp when dice rolled two times
: "+sum);
[Link]
}
}
Create a Card class that represents a playing card. It should have an int instance variable named rank and a char
variable named suit. Give it a constructor with two parameters for initializing the two instance variables and give
it a getSuit () method and agetRank () method that return the values of two instance variables. Then create a
ClassTester class with a main method that creates five cards that make up a full house (that is, three of the cards
have the same rank and other two cards have the same rank) and prints out the ranks and suits of the five Cards
using the getSuit() and getRank() methods.
class Card{
int rank;
char suit;
Card(int x,char y){
rank = x;
suit = y;
int getRank(){
return rank;
}
char getSuit(){
return suit;
}
}
public class classTester {
public static void main(String[] args) {
Card Club2=new Card(2,'C');
Card Spades2=new Card(2,'S');
Card Diamond3=new Card(3,'D');
Card Star3=new Card(3,'S');
Card Hearts3=new Card(3,'H');
[Link]("Suit of Card :"+[Link]());
[Link]("Rank of Card :"+[Link]());
[Link]("Suit of Card :"+[Link]());
[Link]("Rank of Card :"+[Link]());
[Link]("Suit of Card :"+[Link]());
[Link]("Rank of Card :"+[Link]());
[Link]("Suit of Card :"+[Link]());
[Link]
}
}
Create a class Number with two int instance variable x and y. The class will have one constructor. The class also
will contain method getMax() method that will return larger number. Create a class NumberDemo with main
method that will create an object of Number and will print the larger number.
class Number{
int x,y;
Number(){
x=10;
y=20;
}
int getMax(){
if(x>y)
return x;
else
return y;
} }
public class numberDemo {
public static void main(String[] args) {
Number x= new Number();
[Link]("Larger Number= "+[Link]());
} }
Create a class Number with three int instance variable x ,y and z. The class will have one constructor. The class
also will contain method getMax() method that will return larger number. Create a class NumberDemo with main
method that will create an object of Number and will print the larger number.
class Number2{
int x,y,z;
Number2()
{
x=10; y=20; z=30;
}
int getMax(){
if(x>y && x>z){
return x;
}
else if(y>x && y>z){
return y;
}
else
return z;
} }
public class numberDemo2 {
public static void main(String[] args) {
Number2 n= new Number2();
[Link]("The Largest Number :"+[Link]());
}}
Create a class Swapper class with two integer instance variablex and y and constructor with two parameters that
initializes the two variables. Also include three methods: A getX () method that returns x, a getY () method that
[Link]
returns y, a void swap () method that swaps the values of x and y. Then create a SwapperDemo class that tests all
the methods.
class Swapper{
int x,y;
Swapper(){
x=13;
y=15;
}
int getx(){
return x;
}
int gety(){
return y;
}
void swap(){
x=x+y;
y=x-y;
x=x-y;
}
public class swapperDemo {
public static void main(String[] args) {
Swapper s=new Swapper();
[Link]("Number before swappingg");
[Link]("x = "+[Link]());
[Link]("y = "+[Link]());
[Link]("Number after swapping");
[Link]();
[Link]("x = "+[Link]());
[Link]("y = "+[Link]());
}
}
Write a Java program that creates two threads, one displays numbers from 1 to 100 after one second and
another thread displays numbers from 100 to 1 after one and half second.
class ThreadOne extends Thread{
public void run(){
try{
for(int i=0;i<=100;i++){
[Link](i+" ");
[Link](1000);
}
}catch(InterruptedException e){
[Link]("Thread interrupted");
}
}
}
class ThreadTwo extends Thread{
public void run(){
[Link]
try{
for(int i=100;i>=0;i--){
[Link](i+" ");
[Link](1500);
}
}catch(InterruptedException e){
[Link]("Thread interrupted");
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
ThreadOne t1= new ThreadOne();
ThreadTwo t2 = new ThreadTwo();
[Link]();
[Link]();
}
}