0% found this document useful (0 votes)
5 views50 pages

Java Programming Concepts and Examples

The document contains a series of model questions and answers related to Java programming, covering topics such as the use of the valueOf() function, interfaces, comments, classpath, garbage collection, thread priority, auto boxing, and exception handling. It includes sample Java programs demonstrating various concepts like displaying numbers, creating threads, file handling, and implementing interfaces. Additionally, it explains key Java concepts like JVM, operators, wrapper classes, and method overriding.

Uploaded by

Ashish Dahait
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)
5 views50 pages

Java Programming Concepts and Examples

The document contains a series of model questions and answers related to Java programming, covering topics such as the use of the valueOf() function, interfaces, comments, classpath, garbage collection, thread priority, auto boxing, and exception handling. It includes sample Java programs demonstrating various concepts like displaying numbers, creating threads, file handling, and implementing interfaces. Additionally, it explains key Java concepts like JVM, operators, wrapper classes, and method overriding.

Uploaded by

Ashish Dahait
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

[Link].

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.

ii. What is use of interface?


In Java, an interface defines a set of methods that will be implemented by a class. An interface is a construct that
describes functionality without specifying implementation. Once an interface is defined, any number of classes
can implement it. This makes it possible for two or more classes to provide the same functionality even though
they might do so in different ways. One class can implement any number of interfaces.

iii. Why are comments used in programs?


The comments are used in for documentation purpose. Comments are ignored by compiler. The comment is not
part of Java program

iv. What do you mean by CLASSPATH?


Classpath is a parameter –set either on the command line or through environment variable –that tells the Java
Virtual Machine or Java compiler where to look for user defined classes and packages.

[Link] syntax of any one of the control statements.


The selection or control statements allow us to decide a statement of code or block of code to execute depending
upon the given condition. Java supports following conditional or selection statements which are if, if –else and
switch.
The syntax for if statement is:
if(booleanExpression)
{
……..
}

vii. What do you mean by garbage collection?


The Java runtime environment deletes objects when it determines that they are no longer being used, this process
is called garbage collection. The Java runtime environment has a garbage collector that periodically frees the
memory used by used by objects that are no longer referenced.

[Link] do you mean by thread priority?


A thread's priority determines how much CPU time a thread receives relative to the other active threads. In
general, low priority threads receive little, whereas high priority thread receives a lot. As we might expect, how
much CPU time a thread receives has a profound impact on its execution characteristics and its interaction with
other threads currently executing in the system.

[Link] is auto boxing?


Auto boxing is the process by which a primitive type is automatically encapsulated (boxed) into its equivalent
type wrapper whenever an object of that type is needed. There is no need to explicitly construct object. It helps

[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](i+ " ");


s = s+i;
}
}
[Link]("The sum = "+s);
}
}

[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”

[Link] is exception? Explain ArrayIndexOutOfBoundsException with an example.

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.

Let us consider the following program:

public class ExcpeptionDemo {

public static void main(String[] args) {


int arr[] = {1,2,3,4,5,6};
try{

[Link]
[Link]

for(int i=0;i<=[Link];i++)
[Link] (arr[i]+ " ");
}catch(ArrayIndexOutOfBoundsException e){
[Link]("Exception Occurred "+e);
}
}
}

Output:-

1 2 3 4 5 6 Exception Occurred [Link]. ArrayIndexOutOfBoundsException: 6

[Link] the steps required to create package with an example.


Creating a package in Java is quite easy. Simply include a package command followed by name of the package
as the first statement in Java source file.
package mypack
Public class employee
{
……statement;
}

The above statement creates a package called mypack


Let us consider the following example:
Import mypack;
Class Book
{
String bookname;
String author;
Book(String b, String c)
{
[Link] = b;
this. Author = c;
}
Public void show()
{
[Link](bookname+” “+author);
}
}
Class Test{
Public static void main(String []agrs)
{
B Book bk = new Book(“java”,”Herbert”);
[Link]();
}

[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.

3. Differentiate between interface and base class.


A base class can contain non static and non-final fields whereas an interface has static fields by default. A base
class can contain implemented methods whereas interface has no implemented methods.

5. What is wrapper class.


• Wrapper class in java are classes that provide the mechanism to convert primitive into object and
object into primitive. The eight classes of [Link] are known as wrapper classes in java.

6. Define thread.
Threads: A program can be composed of multiple independent flow of control. Java supports the creation of
programs with concurrent flows of control. These independent flows of control are called threads. Threads run
with in a program and make use of that program's resources in their execution. For this reason threads are also
called lightweight processes (LWP).Both processes and threads provide an execution environment, but creating a
new thread requires fewer resources than creating a new process.

7. What do you mean by enumeration?


An enumeration is a list of named constants that define a new data type. An object of an enumeration type
can hold only the values that are defined by the list. Thus, enumeration gives us a way to precisely define a new
type of data that has a fixed number of valid values. From a programming perspective, enumerations are useful
whenever we need to define a set of values that represent a collection of items.
An enumeration is created using the enum keyword.
enum Transport {
CAR, TRUCK, AIRLINES, TRAIN, BOAT
}

8. How constant variable is declared in Java?


The constant variables in Java can be declared using final keyword.
For example:
final double PI = 3.1416
final int N =100

9. What is garbage collection?

[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.

10. What is method overriding?


When the name of method in subclass is similar to the name of method in super class then subclass method
overrides or hides the super class method when we call the method by subclass object and this is called method
overriding.
Group B
[Link] 11 Write a Java Program to display all the even numbers from 1 to 500
public class tu15Q11 {
public static void main(String[] args) {
int i;
for(i=1;i<=500;i++){
if(i%2==0){
[Link](i);
}
}
}
}
12. 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]();
}
}

[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]

Rectang obj2=new Rectang();


[Link](34, 20);

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);
}

class calc implements num {


int sum;
int sub;
@Override
public int add(int x,int y){
sum=x+y;
[Link]("The sum is "+sum);
return sum;
}

@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.

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.

public class NestedTry {


public static void main(String[] args) {
int num[] = {8,16,32,64,128,256,512,1024};
int den[] = {1,0,4,0,8,0,16};
int a;
for(int i=0;i<[Link];i++)
{
try{
try{
a = num[i]/den[i];
[Link](a);
}catch(ArrayIndexOutOfBoundsException e){
[Link]("No matching element :");
}
}catch(ArithmeticException e){
[Link]("Division by 0: ");
}
}
}
}
17. Define package? Write down steps to create package. Explain with example
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations )
providing access protection and namespace management.
• Some of the existing packages in Java are −
• [Link]− bundles the fundamental classes
• [Link]− classes for input , output functions are bundled in this package
• Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a good
practice to group related classes implemented by you so that a programmer can easily determine that the
classes, interfaces, enumerations, and annotations are related.

[Link]
[Link]

Steps to create a Java package


• Come up with a package name.
• Pick up a base directory.
• Make a subdirectory from the base directory that matches your package name.
• Place your source files into the package subdirectory.
• Use the package statement in each source file.
• Compile your source files from the base directory.

example

The package keyword is used to create a package in java.


Package mypack;
Public class Simple{
publicstatic void main(String args[]){
[Link]("Welcome to package");
}
}

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.

2. What are the use of parenthesis?


Parentheses are used for two purposes: (1) to control the order of operations in an expression, and (2) to supply
parameters to a constructor or method.

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.

5. Why Java is called platform neutral language?


Java is known as platform independent because it uses the concept of generating the byte code of the high level
program ,and then run that byte code(intermediate code) on JVM(Java Virtual Machine),now what is JVM,
actual JVM is a virtual computer system that run on your original computer system.

6. Differentiate between super class and subclass .


• Super class: Super class refers to a high level class, which passes some kind of attribute and procedures.
This is usually followed down to the hierarchy to subclasses. Most of the time abstract super classes are
referred to as master structures and almost most of the time no objects are created for it.
Sub class: On the other hand, a subclass is that inherits different kinds of specifications and also
behaviors. This could also include methods, procedures and variables from any other class.

[Link]
[Link]

8. What is reflection in Java?


Java Reflection is a process of examining or modifying the run time behavior of a class at run time.
The [Link] class provides many methods that can be used to get meta data, examine and change the run
time behavior of a class. The [Link] and [Link] packages provide classes for java reflection.

9. How does Java supports multiple inheritance?


Multiple Inheritance: It is an inheritance in which a sub class can inherit from more than one super class.
Unlike many other languages java doesn’t support it. It is just to remove ambiguity, because multiple
inheritance can cause ambiguity in some cases. Java supports the multiple inheritance by using interface. That is
a class can implement any number of interface.

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]();

ThreadB t2=new ThreadB();


Thread objB=new Thread(t2);
[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.

public class ArrayIndexOutOfBoundsExceptionDemo {


public static void main(String[] args) {
int arr[] = {3,4,5,6,1};
try{
for(int i=0;i<=[Link];i++)
[Link](arr[i]+" ");
}catch(ArrayIndexOutOfBoundsException e){

[Link]
[Link]

[Link]("Exception occurred "+e);


}

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

2. Why Java is a strongly typed programming language?


Java is a strongly typed programming language because every variable must be declared with a data type.

[Link] between Public constructors & Private constructors .


Public constructors are used to instantiate and initialize the fields during object instantiation .Private constructors
are used to restrict the instantiation of object using ' new' operator .

[Link] identifiers can’t be used by keywords?


You cannot use keywords as variable name. It's because keywords have predefined meaning. For example,
int float;
The above code is wrong. It's because float is a keyword and cannot be used as a variable name.

[Link] is the role of JVM?


It interprets the compiled java code know s as the byte code and helps in program execution depending upon the
specific platform.

6. List out 3 oops principles.


1) Encapsulation.
2) Inheritance.
3) Polymorphism.

[Link] are different thread states?


new, runnable ,timed waiting, waiting, blocked, terminated

[Link] Auto boxing.


Auto boxing is the automatic conversion that the Java compiler makes between the primitive types and their
corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double etc.

[Link]
[Link]

[Link] 11

public class tu17Q11 {


public static void main(String[] args) {
int n,i;

[Link]("Enter the number of numbers to enter");


Scanner sn=new Scanner([Link]);
n=[Link]();
[Link]("Enter the numbers");
int num[];
for(i=0;i<n;i++){
num[i]=[Link]();
if(num[i]%2==0&&num[i]%3==0){
[Link](num[i]);
}

}
}
}
[Link] 12
class Student {
int roll_no;

public void readRoll(int r){


roll_no=r;
}
public void displayRoll(){
[Link](roll_no);
}

}
class Test extends Student{
int markJava,markWeb;

public void readMarks(int mj,int mw){


markJava=mj;
markWeb=mw;
}
public void displayMarks(){
[Link]("Java:"+markJava+" "+"Web:"+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]("The area of Square is:"+area);


}
}

public class tu17Q13 {


public static void main(String[] args) {
Rectangle obj=new Rectangle();
obj.get_data(10, 20);
obj.display_area();

Square obj1=new Square();


obj1.get_data(10, 0);
obj1.display_area();

[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] user defined exception in java with a suitable example.


In java we can create our own exception class and throw that exception using throw keyword. These exceptions
are known as user-defined or custom exceptions.

class MyException extends Exc


String str1;

MyException( String str2) {


str1=str2;
}

[Link]
[Link]

public String toString(){


return ( "MyException details[]”)
}
}
class Example1 {
public static void main( String args[]){
try{
System. [Link](“details[]”);
// I'm throw
throw new My
}
catch( MyException exp
System. [Link](“details[]”);
System. [Link](“details[]”);
}
}

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]

ThreadOne t1= new ThreadOne();


ThreadTwo t2 = new ThreadTwo();
[Link]();
[Link]();
}
}
Show the example of nested try-catch Exception.
public class NestedTryCatch {
public static void main(String args[]){
int num[]={8,16,32,64,128,256,512,1024};
int den[]={1,0,4,0,8,0,16};
int a, i;
for(i=0; i<[Link]; i++)
{
try{
try{
a=num[i]/den[i];
[Link](a);
}
catch(Exception e){
[Link](e);
}
}
catch(Exception e){
[Link](e);
}
}
}
}
Show the example of custom exception in java.
class MyException extends Exception{
public MyException(String s)
{
super(s);
}
}
public class UserDefineException{
public static void main(String args[])
{
try{
throw new
MyException("error1...................");
}
catch (MyException ex)
{
[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]

Kitten k = new Kitten();


[Link]();
}
}
Write a program to show the varargs in Java.
class varargsDemo
{
public static void main(String args[])
{
fun();
}
static void fun(float...a)
{
[Link]("float varargs");
}
static void fun(int...b)
{
[Link]("int vargs");
}
static void fun(double...c)
{
[Link]("Double");
}
}
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 diff(int x, int y);
}
class Calculator implements Num
{
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 voidmain(String[] args)
{
Calculator c = new Calculator();
[Link]("The sum of 4 and 5 is ="+[Link](4, 5));

[Link]
[Link]

[Link]("The difference of 10 and 5 ="+[Link](10, 5));


}
}
Make a class “Rectangle” with attributes length and breadth. The class contains methods computeArea()
and displayArea(). Write a program with main() method that creates two objects of Rectangle class and
find their areas and display area of larger rectangle.
class Rectangle{
private int length;
private int breadth;
public Rectangle(){}
public Rectangle(int l,int b){
length=l;
breadth=b;
}
public int computeArea(){
return length*breadth;
}
public void displayArea(int a){
[Link]("The area of rectangle = "+a);
}
}
public class RectangleDemo {
public static void main(String[] args) {
Rectangle r = new Rectangle(10,5);
int a = [Link]();
[Link](a);
}
}

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]

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 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]

public class TU201814 {


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]();

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);

String id, name,address;


int dob,number;
Scanner sc= new Scanner([Link]);
[Link]("Enter employee id:");
id=[Link]();
[Link]("Enter employee name:");
name=[Link]();
[Link]("Enter employee address:");
address=[Link]();
[Link]("Enter employee dob:");
dob=[Link]();
[Link]("Enter employee Phone number:");
number=[Link]();
[Link](id);
[Link](name);
[Link](address);
[Link](dob);
[Link](number);
[Link]();

[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];

public class Tu201815demo {


public static void main(String args[])
{
try{
FileOutputStream fout=new FileOutputStream("D:\\Test\\[Link]");
PrintStream pout=new PrintStream(fout);
String name,address,college;
Scanner sc= new Scanner([Link]);
[Link]("Enter Name:");
name=[Link]();
[Link]("Enter address:");
address=[Link]();
[Link]("Enter college:");
college=[Link]();
[Link](name);
[Link](address);
[Link](college);
[Link]();
[Link]("success...");
FileInputStream fin=new FileInputStream("D:\\[Link]");
int i=0;
while((i=[Link]())!=-1){
[Link]((char)i);
}
FileInputStream fin1=new FileInputStream("D:\\Test\\[Link]");
FileOutputStream fout1=new FileOutputStream("D:\\[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);

/*taking a delay of one second before displaying next number


*
* "[Link](2000);" - when this statement is executed,
* this thread will sleep for 2000 milliseconds (2 second)
* before executing the next statement.
*
* Since we are making this thread to sleep for two second,we need to
* handle "InterruptedException". Our thread may throw this exception if it
*is interrupted while it is sleeping.
*/
try
{
[Link] (2000);
}
catch (InterruptedException interruptedException)
{
/*Interrupted exception will be thrown when a sleeping or waiting
*thread is interrupted.
*/

[Link]
[Link]

[Link]( "First Thread is interrupted when it is sleeping"


+interruptedException);
} } } }

public class ThreadDemo


{
public static void main(String args[]) Output is :-
{
Messag from First Thread : 1
//Creating an object of the first thread
FirstThread firstThread = new FirstThread(); Messag from First Thread : 2
Messag from First Thread : 3
Time limit exceeded
//Starting the thread
Thread thread1 = new Thread(firstThread);
[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]

public static voidmain(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));

Make a class “Rectangle” with attributes length and int a = [Link]();


breadth. The class contains methods computeArea() [Link](a);
and displayArea(). Write a program with main() }
method that creates two objects of Rectangle class }
and find their areas and display area of larger
rectangle.
class Rectangle{
private int length;
private int breadth;
public Rectangle(){}
public Rectangle(int l,int b){
length=l;
breadth=b; • Write a program that reads line of text from
} keyboard and write to file. Also read the content of
public int computeArea(){ the same file and display on monitor
return length*breadth; • import [Link].*;
} • class ReadingFromKeyBoard {
public void displayArea(int a){ • public static void main(String
[Link]("The area of args[]) throws IOException {
rectangle = "+a); • String str;
} • BufferedReader br = new
} BufferedReader(new InputStreamReader
public class RectangleDemo { ([Link]));
public static void main(String[] • FileWriter fw=null;
args) { • [Link]("Enter line of
Rectangle r = new text and 'stop' at the end");
Rectangle(10,5); • try{

[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]

public static void main(String[] args) {


for(int i=1;i<=500;i++){
if(i%2==0)
[Link](i+" ");
}
}
}

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]

public void run(){


for(int i=100;i<=200;i++){
if(i%2==1)
[Link](i+" ");
}}}
public class ThreadDemo {
public static void main(String[] args) {
ThreadA a = new ThreadA();
ThreadB b = new ThreadB();
Thread t1 = new Thread(a);
Thread t2 = new Thread(b);
[Link]();
[Link]();
} }
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 NameDemo {
public static void main(String[] args) {
String name[] = {"Sita","Gita","Ram","Kamala"};
for(int i=0;i<[Link];i++){
if(name[i].contains("t"))
[Link](name[i]);
}
}
}

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");
}
}
}
}

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.

public class oddNeg {


public static void main(String[] args) {
int arr[]=new int[30];
int i;
for(i=1;i<30;i++){
arr[i]=i;
}
for(i=1;i<31;i++)
{
if(i%2==0)
[Link](-i+",");
else
[Link](i+",");

[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]

public void setData(String n, int a ){


name = n;
age =a;
}
public void display(){
[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());

}
}
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]

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]();

} }

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]

[Link]("Rank of Card :"+[Link]());


[Link]("Suit of Card :"+[Link]());
[Link]("Rank of Card :"+[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]();
}
}

You might also like