0% found this document useful (0 votes)
21 views

Introduction to Java-notes

Uploaded by

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

Introduction to Java-notes

Uploaded by

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

Introduction to Java & Blue Environment

1. Why is Java often termed as a platform?

Ans: Platform is the environment in which programs execute. Instead of


interacting with the Operating System directly, Java programs runs on a
virtual machine provided by Java, therefore Java is often referred to as a
platform also.

1. What is a bytecode?

Ans: Bytecode is a set of pseudo mechanic language instructions that are


understood by the JVM (Java Virtual Machine) and are independent of the
underlying hardware.

1. What do you understand by JVM?

Ans: JVM or Java Virtual Machine is an abstract machine designed to be


implemented on top of existing processors. It hides the underlying OS from
Java application. Programs written in Java are compiled into Java byte-
code, which is then interpreted by a special java Interpreter for a specific
platform. Actually this Java interpreter is known as Java Virtual Machine
(JVM).

1. What is JDK (Java Development Kit)?

Ans: The Java development kit comes with a collection of tools that are
used for developing and running java programs.

1. What are Java APIs?


Ans: The Java APIs (Application Program Interface) consist of libraries of
pre-compiled code that programmers can use in their application.

1. Write the five characteristics of Java/BlueJ?

Ans: 1. Write Once Run Anywhere 2. Light weight code 3. Security 4. Built
in Graphics 5. Object Oriented Language 6. Support Multimedia 7. Platform
Independent. 8. Open Product.

1. What do you know about BlueJ?

Ans: BlueJ is a Java development environment. It is an IDE (Integrated


Development Environment), which includes an editor a debugger and a
viewer.

1. How you create, compile and execute a program in Java or BlueJ? Explain
your answer?

Ans: Create: Click on new class button from BlueJ editor, then type the
class name a program icon will be created. double click on it, a program
editor will be open, erase the code and type your program coding. Compile:
click the compile button on the left of the window or right click on the class
icon and select compile from the menu options. Execute: Right click on the
class icon and select new class name option. A dialogue box appears type
the name of the object. A object icon will be created at the bottom. Right
click on the object icon and select the method we want to execute.

1. The two types of Java programs/applications are? [2007]

Ans: The two types of Java Applications are ‘Internet Applets’ and ‘Stand
alone application’.

1. State the distinguishing features of Java and C++?

Ans: (i) Java does not support operator overloading.

(ii) Java does not use pointers.


(iii) There are no header files in Java.

(iv) Java does not have template classes as in C++.

1. State the differences between Syntax errors and Logical errors.

Ans: The compiler can only translate a program if the program is


syntactically correct; otherwise the compilation fails and you will not be able
to run your program. Syntax refers to the structure of your program and the
rules about that structure.

The second type of error is a run-time error, so-called because the error
does not appear until you run the program. In Java, run-time errors occur
when the interpreter is running the byte code and something goes wrong.

1. “Object is an instance of a class”, explain

Ans: Object of a class contains data and functions provided in a class. it


possesses all the features of a class. Hence object is termed as instance of
a class.

1. Name four basic features of JAVA.

Ans: Basic features of Java as follows:

1. i) It is an object oriented language.


2. ii) Java program is both compiled and interpreted.

iii) Java program can be application or applet.

1. iv) java is case sensitive language, i.e. it distinguished upper and lower
case letters.
2. Differentiate between Compiler and Interpreter.

Ans: Compiler convert source code to machine language whole at a time.


Interpreter converts program from high level language to machine level
language line by line or statement by statement.

1. Java uses compiler as well as interpreter, explain.


Ans: Java compiler converts Java source code to byte code. This byte code
is further converted into machine code to make it applicable for the specific
platform by using interpreter.

1. Differentiate between Source code and Byte code.

Ans: Source code is the program developed in Java Language, which is


input to a computer through the keyboard. Compiler converts source code
to byte code for interpretation.

1. Differentiate between Testing and Debugging.

Ans: Testing is the process of checking program logic manually to ensure


whether it contains any error or not. Debugging is the process of removing
errors from a program.

Elementary Concepts of Object & Class

[ICSE Syllabus on this Topic]

Modeling entities and their behavior by objects. A class as a specification of


objects and as an object factory, computation as message passing/function
call between objects (many example should be done to illustrate this).
Object encapsulate state (attribute) and have behaviors (functions). Class
as a user defined type.

1. What is an Object? [2006]

Ans: An Object is an identifiable entity with some characteristics and


behavior. E.g. take a class ‘Car’. A car class has characteristics like colour,
gears, power, length etc. now we create the object of that class ‘Car’
namely ‘Indica’.
1. What is OOP? What are the features/concepts in OOP’s? [2007]

OR

Name any two OOP’S principles. [2005]

Ans: The Object Oriented Programming Paradigm is the latest in the


software development and the most adopted one in the programming
development. The Paradigm means organising principle of a program. It is
an approach to programming. The concepts of OOP’s are: (1) Data
Abstraction (2) Data Encapsulation (3) Modularity (4) Inheritance (5)
Polymorphism.

1. Explain all the Concepts of OOP’s?

Ans: Abstraction: It refers to the act of representing essential features


without including the background details or explanation. Encapsulation: It is
the way of combining both data and the function that operates on the data
under a single unit. Modularity: It is the property of a system that has been
decomposed into a set of cohesive and loosely couple modules.
Inheritance: It is the capability of one class of thing to inherit properties
from another class. Polymorphism: It is the ability for a message or data to
be processed in more then one form.

1. What are the advantages of OOP’s?

Ans: (1) Elimination of redundant coding system and usage of existing


classes through inheritance. (2) Program can be developed by sharing
existing modules. (3) Possibilities of multiple instance of an objects without
any interference. (4) Security of data values from other segment of the
program through data hiding.

1. What is Class? How Object is related to the Class?


Ans: A Class represent a set of Objects that share common characteristics
and behavior. Objects are instance of a class. The Object represents the
abstraction representation by the class in the real sense.

1. What is the need of a class in Java?

Ans: Classes in Java are needed to represent real-world entities, which


have data type properties. Classes provide convenient methods for packing
together a group of logical related data items and functions that work on
them. In java the data items are called fields & the functions are called
methods.

1. What are Methods? How are these related to an Objects?

Ans: A Method is an operation associated to an Object. The behavior of an


Object is represented through associated function, which are called
Methods.

1. Point out the differences between Procedural Programming and Object


Oriented Programming.

Ans: Procedural programming aims more at procedures. The emphasis is a


doing things rather then the data being used. In procedural Programming
parading data are shared among all the functions participating thereby
risking data safety and security. Object Oriented Programming is based on
principles of data hiding, abstraction, inheritance and polymorphism. It
implements programs using classes and objects, In OOP’s data and
procedure both given equal importance. Data and functions are
encapsulated to ensure data safety and security.

1. What is an abstraction?

Ans: An abstraction is a named collection of attributes and behaviors


required to represent an entity or concept for some particular problem
domain.

1. What is inheritance and how it is useful in Java. [2008]


Ans: It is process by which objects of one class acquire the properties of
objects of another class. Inheritance supports the concepts of hierarchical
representation. In OOP the concepts of inheritance provides the idea of
reusability.

1. What role does polymorphism play as java feature?

Ans: It mean the ability to take more than one form. For example, an
operation, many types of data used in the operation.

1. What is Data hiding?

Ans: Data Hiding means restricting the accessibility of data associated with
an object in such a way that it can be used only through the member
methods of the object.

1. What are nested classes?

Ans: It is possible to define a class within another class, such classes are
known as nested classes. A nested class has access to the members
including private members of the class in which it is nested. However the
enclosing class not have access to the members of the nested class.

1. Differentiate between base and derived class. [2008]

Ans: BASE CLASS – A class from which another class inherits (Also called
SUPER CLASS)

DERIVED CLASS – A class inheriting properties from another class. (Also


called SUB CLASS)

Class as the Basis of all Computation

[ICSE Syllabus on this Topic]


Objects encapsulates state and behavior- numerous example, member
variables, attributes or features. Variable define states, Member
functions/operation/methods/messages defines behaviors. Class as
abstractions for set of objects, class as an object factory, concept of type,
primitive data types, composite data types. Variable declaration for both
types, difference between the two types. Objects as instance of a class.
Modeling by composition.

1. What are keywords? can keywords be used as a identifiers?

Ans: Keywords are the words that convey a special meaning to the
language compiler. No, keywords can never be used as identifiers.

1. What is an identifier? What is the identifier formatting rule of Java? OR


What are the rules for naming a variable?

Ans: Identifiers are names given to different parts of a program e.g.


variables, functions, classes etc. The identifiers in Java.

(i) Can contains alphabets, digits, dollar sign and underscore.

(ii) Must not start with a digit.

(iii) Can not be a Java keywords.

(iv) Can have any length and are case-sensitive.

1. Why keyword is different from identifiers?

Ans: Keywords are predefine sets of words that have a special meaning for
the Java compiler. Identifiers on the other hand are created by Java
programmers in order to give names to variables, function, classes etc.

1. State the difference between Token and Identifier.[2008]


Ans: The smallest individual unit of a program is known as Token. The
following Tokens are available in Java: Keywords, Identifiers, Literals,
Punctuations, Operators.

Identifiers are names given to different parts of a program e.g. variables,


functions, classes etc. The identifiers in Java.

1. What are literals? How many types of integer literals are available in Java?

Ans: A literal is sequence of characters used in a program to represent a


constant value. For example ‘A’ is a literal that represents the value A of
type char, and 17L is a literal that represents the number 17 as value of
type long. Different types of literals available in Java, they are: Integer
literal, Float literal, Boolean literal, Character literal, String literal and null
literal.

1. What is an integer constant? Write integer forming rule of Java.

Ans: Integer constants are whole numbers without any decimal part. The
rule for forming an integer constants is: An integer constant must have at
least one digit and cannot contain a decimal point. It may contains + or –
sign. A number with no sign is interpreted to be positive.

1. What do you mean by Escape sequence and name few escape sequences
in Java?

Ans: Java have certain nongraphic characters (nongraphic characters are


those characters that can not be typed directly from keyboard e.g.
backspace, tab, carriage return etc.). Those nongraphic character can be
represented by escape sequence. An escape sequence is represented by
backslash followed by one or more character. The few escape sequence
characters are: \n for new line, \t for Horizontal Tab, \v for Vertical Tab, \b
for Backspace, \” for Double Quotes etc.

1. How many integer constants are allowed in Java? How are they written?
Ans: Java allows three types of integer constants: Octal (base 8), Decimal
(base 10), and Hexadecimal (base 16). An Octal integer must be started
with a zero ‘0’, a Hexadecimal integer starts with a ‘0X’, all others are
treated as decimal integer constant.

1. What is meant by a floating constant in Java? How many ways can a


floating constant be represented into?

Ans: Floating constants are real numbers. A floating constant can either be
a fractional or in exponent form.

1. Differentiate between Integer and Floating type constants.

Ans: Integer constants are the whole numbers (without decimal points). e.g.
1231. Floating point constants are fractional numbers (number with decimal
points). e.g. 14.2356

1. Write the following real constants into fractional form: 0.113E04, 0.417E-
04, 0.4E-05, 0.123E02

Ans: 0.113E04 becomes 1130, 0.417E-04 becomes .0000417, 0.4E-05


becomes .000004, 0.123E02 becomes 12.3

1. What is a type or ‘Data Type’? How this term is related to programming?

Ans: A type or datatype represents a set of possible values. When we


specify that a variable has certain type, we are saying what values the
expression can have. For example to say that a variable is of type int says
that integer values in a certain range can be stored in that variable.

1. What is primitive data type? Name its different types.

Ans: Primitive data types are those that are not composed of other data
types. Numeric Integral, Fractional, character and boolean are different
primitive data types.

1. State the two kind on data types? [2006]


Ans: The two types of data types are: Primitive and
non-primitive/composite/user define data types. The primitive data types
are: byte, short, int, long, float, double, char and Boolean. The non-
primitive/reference data types are: class, array and interface.

1. Write down the names of three primitive and three non-primitive/reference


data types in Java/BlueJ.

Ans: The primitive data types are: byte, short, int, long, float, double, char
and Boolean. The non-primitive/reference data types are: class, array and
interface.

1. How many bytes occupied by the following data types: byte, short, int, long,
float, double, char, boolean.

Ans: char-2 byte, byte-1 byte, short-2 bytes, int-4 bytes, long-8 bytes, float-
4 bytes, double-8 bytes, boolean-Java reserve 8 bits but only use 1 bit.

1. What is the range of the following data types: byte, short, int, long, float,
double, char, boolean.

Ans: byte -> -128 to 127

short -> -32768 to 32767

int -> -231 to 231-1

long ->-263 to 263-1

float -> -3.4×1038 to 3.4×1038

double -> -1.7×10308 to 1.7×10308

char -> 0 to 65536

boolean – > true or false


1. What is the largest and smallest value for floating point primitive data types
float?

Ans: The smallest value is -3.4E+38 and largest values is 3.4E+38 of


floating point data type.

1. What is Token? What are the tokens available in Java? [2008]

Ans: The smallest individual unit of a program is known as Token. The


following Tokens are available in Java:- Keywords, Identifiers, Literals,
Punctuations, Operators.

1. What do you mean by variables? [2006]

Ans: A variable is a named memory location, which holds a data value of a


particular data types. E.g. double p;

1. What do you mean by variables? What do you mean by dynamic


initialization of a variable?

Ans: A variable is a named memory location, which holds a data value of a


particular data types. When a method or functions is called and the return
value is initialise to a variable is called dynamic initialisation. example
double p=Math.pow(2,3);

1. What is the function of an operator?

Ans: Operators are special symbols that represent operations that can be
carried out on variables, constants or expressions.

1. What do you mean by operator and write the name of all operators given in
your textbook.

Ans: The operations are represented by operators and the object of the
operations are referred to as operands. The types of Operators available in
Java are: 1. Arithmetic 2. Increment/Decrement 3. Relational 4. Logical 5.
Shift 6. Bitwise 7. Assignment 8. Conditional 9. [] operator 10. new operator
11. (type) cast Operator 12. () operator. 13. dot operator.
1. What are arithmetic operators?

Ans: Arithmetical operators are used for various mathematical calculations.


The result of an arithmetical expression is a numerical values. Arithmetical
operators are of following types: Unary and Binary operators.

1. Write major difference between the unary and binary operators?

Ans: The operators that acts on one operand are referred to as Unary
Operator. There are two Unary operators Unary + operator and Unary –
operator. The operators that acts upon two operands are referred to as
Binary Operator. The Binary Operators are Addition(+), Subtraction (-),
Multiplication (*), Division (/) and Modulus (%).

1. What is increment operator? What are postfix and prefix increment


operators?

Ans: The ‘++’ operator is called increment operator. The increment


operators add 1 to its operand. These are two types (i) Prefix and (ii)
Postfix The prefix version comes before the operand for e.g. ++a, where as
postfix comes after the operand e.g. a++

1. Find the value of x after evaluating x += x++ + –x + 4 where x=3 before the
evaluation. Explain your answer.

Ans: Result is 13, because x++ is 3, –x is 2 + 4 the answer is 9 add this


with x that is 3 it becomes 12 and due to pre increment of x++ the result
becomes 13.

1. What do you mean by Relational Operators.

Ans: Relational operators are used to determine the relationship between


different operands. These are used in work of compression also. The
relational expression (condition) returns 0 if the relation is false and return 1
if the relation is true. < (less then), > (greater then), <= (less then equals
to), >= (greater then equals to), == (equals to), != (not equals to).

1. What is Logical operators?


Ans: The logical operators combine the result of or more then two
expressions. The mode of connecting relationship in these expressions
refers as logical and the expressions are called logical expression. The
logical expression returns 1 if the result is true otherwise 0 returns. The
logical operators provided by Java are && Logical AND, || Logical OR, !
Logical NOT.

1. What do you man by Assignment Statement or Assignment Operator?

Ans: Assignment operator is represent by symbol ‘=’. It takes the value on


the right and stores it in the variable on the left side. for example x = y + 30

1. What do you mean by Shift operators? OR Differentiate between Shift


LEFT and Shift RIGHT operators.

Ans: A Shift operators performs bit manipulation on data by shifting the bits
of its first operand right to left. The shift operators available in Java are:

(1) >> shift bits of right by distance. (signed shifting)

(2) << shift bits of left by distance. (signed shifting)

(3) >>> shift bits of right by distance (unsigned shifting)

1. Differentiate between Shift LEFT and Shift RIGHT operators.

Ans: Shift LEFT (<<) operatr shifts the bit pattern of the operand towards
left by defined number of bits. Shift RIGHT (>>) operator shifts the bit
pattern of the operand towards right by defined number of bits.

e.g. 13>>2 is 3

binary value of 13 is 1101>>2 is 0011 is equivalent to 3. Similarly LEFT


shift (<<) operator is also work.
APIS, PACKAGES, AND JAVADOC 143

line comes at the start of a file and is not inside any class. Although it is sometimes referred

to as a statement, it is more properly called an import directive since it is not a statement

in the usual sense. Using this import directive would allow you to say

Color rectColor;

to declare the variable. Note that the only effect of the import directive is to allow you to use

simple class names instead of full “package.class” names; you aren’t really importing anything

substantial. If you leave out the import directive, you can still access the class—you just have

to use its full name. There is a shortcut for importing all the classes from a given package. You

can import all the classes from java.awt by saying

import java.awt.*;

The “*” is a wildcard that matches every class in the package. (However, it does not match

sub-packages; you cannot import the entire contents of all the sub-packages of the java package

by saying import java.*.)

Some programmers think that using a wildcard in an import statement is bad style, since

it can make a large number of class names available that you are not going to use and might

not even know about. They think it is better to explicitly import each individual class that

you want to use. In my own programming, I often use wildcards to import all the classes from

the most relevant packages, and use individual imports when I am using just one or two classes

from a given package.

In fact, any Java program that uses a graphical user interface is likely to use many

classes from the java.awt and java.swing packages as well as from another package named

java.awt.event, and I usually begin such programs with

import java.awt.*;

import java.awt.event.*;
import javax.swing.*;

A program that works with networking might include the line “import java.net.*;”, while

one that reads or writes files might use “import java.io.*;”. (But when you start importing

lots of packages in this way, you have to be careful about one thing: It’s possible for two classes

that are in different packages to have the same name. For example, both the java.awt package

and the java.util package contain classes named List. If you import both java.awt.* and

java.util.*, the simple name List will be ambiguous. If you try to declare a variable of type

List, you will get a compiler error message about an ambiguous class name. The solution is

simple: Use the full name of the class, either java.awt.List or java.util.List. Another

solution, of course, is to use import to import the individual classes you need, instead of

importing entire packages.)

Because the package java.lang is so fundamental, all the classes in java.lang are automatically
imported into every program. It’s as if every program began with the statement

“import java.lang.*;”. This is why we have been able to use the class name String instead

of java.lang.String, and Math.sqrt() instead of java.lang.Math.sqrt(). It would still,

however, be perfectly legal to use the longer forms of the names.

Programmers can create new packages. Suppose that you want some classes that you are

writing to be in a package named utilities. Then the source code file that defines those

classes must begin with the line


Question:
Write a Program in Java to input a number and check whether it is an Automorphic Number or
not.
Note: An automorphic number is a number which is present in the last digit(s) of its square.
Example: 25 is an automorphic number as its square is 625 and 25 is present as the last digits

import java.util.*;

class Automorphic

public static void main(String args[]) throws Exception

Scanner sc = new Scanner(System.in);

System.out.print("Enter a Number : "); // Inputting the number

int n = sc.nextInt();

int sq = n*n; // Finding the square

String num = Integer.toString(n); // Converting the number to String

String square = Integer.toString(sq); // Converting the square to String

if(square.endsWith(num)) // If the square ends with the number then it is Automorphic

System.out.print(n+" is an Automorphic Number.");

else

System.out.print(n+" is not an Automorphic Number.");

Write a program to find the shortest and the longest word in a sentence and print them along with
their length.

Sample Input: I am learning Java


Sample Output:
Shortest word = I
Length = 1
Longest word = learning
Length = 8
Program 1- Define a class called Library with the following description:

Instance variables/data members:

Int acc_num – stores the accession number of the book

String title – stores the title of the book stores the name of the author

Member Methods:

(i) void input() – To input and store the accession number, title and author.

(ii)void compute – To accept the number of days late, calculate and display and fine charged at the
rate of Rs.2 per day.

(iii) void display() To display the details in the following format:

Accession Number Title Author

Write a main method to create an object of the class and call the above member methods.

Solution -

public class Library {

int acc_num;

String title;

String author;

public void input() throws IOException {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter accession number: ");

acc_num = Integer.parseInt(br.readLine());

System.out.print("Enter title: ");

title = br.readLine();

System.out.print("Enter author: ");

author = br.readLine();

public void compute() throws IOException {


BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter number of days late: ");

int daysLate = Integer.parseInt(br.readLine());;

int fine = 2 * daysLate;

System.out.println("Fine is Rs " + fine);

public void display() {

System.out.println("Accession Number\tTitle\tAuthor");

System.out.println(acc_num + "\t" + title + "\t" + author);

public static void main(String[] args) throws IOException {

Library library = new Library();

library.input();

library.compute();

library.display();

Program 2- Given below is a hypothetical table showing rates of Income Tax for male citizens below
the age of 65 years:

Taxable Income (TI) in

Income Tax in

Does not exceed 1,60,000

Nil

Is greater than 1,60,000 and less than or equal to 5,00,000


( TI – 1,60,000 ) * 10%

Is greater than 5,00,000 and less than or equal to 8,00,000

[ (TI - 5,00,000 ) *20% ] + 34,000

Is greater than 8,00,000

[ (TI - 8,00,000 ) *30% ] + 94,000

Write a program to input the age, gender (male or female) and Taxable Income of a person.If the age
is more than 65 years or the gender is female, display “wrong category*.

If the age is less than or equal to 65 years and the gender is male, compute and display the Income
Tax payable as per the table given above.

Solution.

import java.util.Scanner;

public class IncomeTax {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter age: ");

int age = scanner.nextInt();

System.out.print("Enter gender: ");

String gender = scanner.next();

System.out.print("Enter taxable income: ");

int income = scanner.nextInt();

if (age > 65 || gender.equals("female")) {

System.out.println("Wrong category");

} else {

double tax;

if (income <= 160000) { tax = 0; } else if (income > 160000 && income <=
500000) { tax = (income - 160000) * 10 / 100; } else if (income >= 500000 && income
<= 800000) {

tax = (income - 500000) * 20 / 100 + 34000;


} else {

tax = (income - 800000) * 30 / 100 + 94000;

System.out.println("Income tax is " + tax);

Program 3- Write a program to accept a string. Convert the string to uppercase. Count and output
the number of double letter sequences that exist in the string.

Sample Input: “SHE WAS FEEDING THE LITTLE RABBIT WITH AN APPLE

Sample Output: 4

Solution.

import java.util.Scanner;

public class StringOperations {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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

String input = scanner.nextLine();

input = input.toUpperCase();

int count = 0;

for (int i = 1; i < input.length(); i++) {

if (input.charAt(i) == input.charAt(i - 1)) {

count++;

}
}

System.out.println(count);

Program4- W Design a class to overload a function polygon() as follows:

(i) void polygon(int n, char ch) : with one integer argument and one character

type argument that draws a filled square of side n using the character stored

in ch.

(ii) void polygon(int x, int y) : with two integer arguments that draws a

filled rectangle of length x and breadth y, using the symbol ‘@’

(iii)void polygon( ) : with no argument that draws a filled triangle shown

below.

Example:

(i) Input value of n=2, ch=’O’

Output:

OO

OO

(ii) Input value of x=2, y=5

Output:

@@@@@

@@@@@

(iii) Output:

**

***
Solution.

public class Overloading {

public void polygon(int n, char ch) {

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= n; j++) {

System.out.print(ch);

System.out.println();

public void polygon(int x, int y) {

for (int i = 1; i <= x; i++) {


for (int j = 1; j <= y; j++) {

System.out.print("@");

System.out.println();

public void polygon() {

for (int i = 1; i <= 3; i++) {

for (int j = 1; j <= i; j++) {

System.out.print("*");

System.out.println();

}
}

Program 5- Using the switch statement, writw a menu driven program to:

(i) Generate and display the first 10 terms of the Fibonacci

series 0,1,1,2,3,5….The first two Fibonacci numbers are 0 and 1, and each

subsequent number is the sum of the previous two.

(ii)Find the sum of the digits of an integer that is input.

Sample Input: 15390

Sample Output: Sum of the digits=18

For an incorrect choice, an appropriate error message should be displayed

Solution.

import java.util.Scanner;

public class Menu {


public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Menu");

System.out.println("1. Fibonacci Sequence");

System.out.println("2. Sum of Digits");

System.out.print("Enter choice: ");

int choice = scanner.nextInt();

switch (choice) {

case 1:

int a = 0;

int b = 1;

System.out.print("0 1 ");

for (int i = 3; i <= 10; i++) { int c = a + b; System.out.print(c + " ");


a = b; b = c; } break; case 2: System.out.print("Enter a
number: "); int num = scanner.nextInt(); int sum = 0; while (num > 0) {

int rem = num % 10;


sum = sum + rem;

num = num / 10;

System.out.println("Sum of digits is " + sum);

break;

default:

System.out.println("Invalid Choice");

Question 4.
Design a program in Java to calculate the tax for the people living in Mango city. Specify a class taxpayer whose
class description is given below:
[15]
Class name: TaxCalculator
Data members: int PAN
String name
double taxableIncome
double tax
Member methods: inputData()
displayData()
computeData()
The tax is calculated according to the following rules:
Total Annual Taxable Income Rate of Taxation
Up to 60000 0%
Above 60000 but up to 150000 5%
Above 150000 but up to 500000 10%
Above 500000 15%

Solution
import java.io.*;
/**
* class TaxCalculator here.
*
*
*/
public class TaxCalculator
{
int pan;
String name;
double taxableIncome;
double tax;
void input()throws IOException
{
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(in);
System.out.println("Enter name and taxable income:");
name=br.readLine();
taxableIncome=Double.parseDouble(br.readLine());
}
void computeData()
{
if(taxableIncome<=60000)
tax=0;
else if(taxableIncome>60000 && taxableIncome<=150000)
tax=taxableIncome*0.05;
else if(taxableIncome>150000 && taxableIncome<=500000)
tax=taxableIncome*0.1;
else
tax=taxableIncome*0.2;
}
void displayData()
{
System.out.println("Display Data”);
System.out.println("Name =" + name);
System.out.println("Taxable Income =" + taxableIncome);
System.out.println("Tax Paid =" + tax);
}

public static void main(String args[])throws IOException


{
TaxCalculator ob=new TaxCalculator();
ob.input();
ob.computeData();
ob.displayData();
}
}
Output:
Enter name and taxable income:
Rehan
120000
Display Data
Name=Rehan
Taxable Income=120000.0
Tax Paid=6000.0

Question 5
Write a menu driven program to convert Fahrenheit to Celsius and Celsius to Fahrenheit.

Solution:
import java.io.*;
import java.io.*;
/**
* Class FahrenToCelsius
*
*/
public class FahrenToCelsius
{
public static void main(String args[])throws IOException
{
int ch,c,f;
InputStreamReader ab=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(ab);
// Menu List
System.out.println("Enter 1. Farenheit to Celsius:");
System.out.println("Enter 2. Celsius To Farenheit:");
System.out.print("Enter Choice :");
ch=Integer.parseInt(br.readLine());
// switch statement
switch(ch)
{
case 1:
System.out.print("Enter Temperature in Farenheit :");
f=Integer.parseInt(br.readLine());
c=((f-32)*5)/9;
System.out.println("Temperature in Celsius :"+c);
break;
case 2:
System.out.print("Enter Temperature in Celsius :");
c=Integer.parseInt(br.readLine());
f=(9*c/5)+32;
System.out.println("Temperature in Farenheit :"+f);
break;
}
}
}

Output :
Enter 1. Farenheit to Celsius:
Enter 2. Celsius To Farenheit:
Enter Choice :1
Enter Temperature in Farenheit :100
Temperature in Celsius :37
Enter 1. Farenheit to Celsius:
Enter 2. Celsius To Farenheit:
Enter Choice :2
Enter Temperature in Celsius :100
Temperature in Farenheit :212

Question 6.
Write a class Automorphic to check whether a number is Automorphic or not using function with
the help of a method
Int digit(int n)
Solution
import java.io.*;
/**
* class Automorphic
*
*/
public class Automorphic
{
int digits(int n)
{
int c,p,k;c=0;k=0;
while(n!=0)
{
k=n/10;
c=c+1;
n=k;
}
return(c);
}

public static void main(String args[])throws IOException


{
InputStreamReader read =new InputStreamReader(System.in);
BufferedReader in =new BufferedReader(read);
int m,n,p,b;
double r;
r = 0;
Automorphic ob= new Automorphic();
System.out.println("Enter your no.");
n=Integer.parseInt(in.readLine());
m= n;
p= m * m;
b=ob.digits(n);
r=p % (Math.pow(10,b));
if(m==r)
System.out.println(m + " is an Automorphic no.");
else
System.out.println(m + " is not an Automorphic no.");
}
}

Output;
Enter your no.
625
625 is an Automorphic no.
Enter your no.
525
525 is not an Automorphic no.

Program6- Write a program to accept the names of 10 cities in a single dimension string array and
their STD (Subscribers Trunk Dialing) codes in another single dimension integer array. Search for a
name of

a city input by the user in the list. If found, display “Search Successful” and print the name of the city
along with its STD code, or else display the message “Search Unsuccessful, No such city in the list’.

Solution.
import java.util.Scanner;

import java.util.Scanner;

public class Cities {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

String[] cities = new String[10];

int[] std = new int[10];

for (int i = 0; i < 10; i++) {

System.out.print("Enter city: ");

cities[i] = scanner.next();

System.out.print("Enter std code: ");

std[i] = scanner.nextInt();
}

System.out.print("Enter city name to search: ");

String target = scanner.next();

boolean searchSuccessful = false;

for (int i = 0; i < 10; i++) {

if (cities[i].equals(target)) {

System.out.println("Search successful");

System.out.println("City : " + cities[i]);

System.out.println("STD code : " + std[i]);

searchSuccessful = true;

break;

if (!searchSuccessful) {

System.out.println("Search Unsuccessful, No such city in the list");


}

Question 4.
Design a program in Java to calculate the tax for the people living in Mango city. Specify a class taxpayer whose
class description is given below:
[15]
Class name: TaxCalculator
Data members: int PAN
String name
double taxableIncome
double tax
Member methods: inputData()
displayData()
computeData()
The tax is calculated according to the following rules:

Total Annual Taxable Income Rate of Taxation


Up to 60000 0%
Above 60000 but up to 150000 5%
Above 150000 but up to 500000 10%
Above 500000 15%

Solution
import java.io.*;
/**
* class TaxCalculator here.
*
*
*/
public class TaxCalculator
{
int pan;
String name;
double taxableIncome;
double tax;
void input()throws IOException
{
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(in);
System.out.println("Enter name and taxable income:");
name=br.readLine();
taxableIncome=Double.parseDouble(br.readLine());
}
void computeData()
{
if(taxableIncome<=60000)
tax=0;
else if(taxableIncome>60000 && taxableIncome<=150000)
tax=taxableIncome*0.05;
else if(taxableIncome>150000 && taxableIncome<=500000)
tax=taxableIncome*0.1;
else
tax=taxableIncome*0.2;
}
void displayData()
{
System.out.println("Display Data”);
System.out.println("Name =" + name);
System.out.println("Taxable Income =" + taxableIncome);
System.out.println("Tax Paid =" + tax);
}

public static void main(String args[])throws IOException


{
TaxCalculator ob=new TaxCalculator();
ob.input();
ob.computeData();
ob.displayData();
}
}
Output:
Enter name and taxable income:
Rehan
120000
Display Data
Name=Rehan
Taxable Income=120000.0
Tax Paid=6000.0
Question 5
Write a menu driven program to convert Fahrenheit to Celsius and Celsius to Fahrenheit.

Solution:
import java.io.*;
import java.io.*;
/**
* Class FahrenToCelsius
*
*/
public class FahrenToCelsius
{
public static void main(String args[])throws IOException
{
int ch,c,f;
InputStreamReader ab=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(ab);
// Menu List
System.out.println("Enter 1. Farenheit to Celsius:");
System.out.println("Enter 2. Celsius To Farenheit:");
System.out.print("Enter Choice :");
ch=Integer.parseInt(br.readLine());
// switch statement
switch(ch)
{
case 1:
System.out.print("Enter Temperature in Farenheit :");
f=Integer.parseInt(br.readLine());
c=((f-32)*5)/9;
System.out.println("Temperature in Celsius :"+c);
break;
case 2:
System.out.print("Enter Temperature in Celsius :");
c=Integer.parseInt(br.readLine());
f=(9*c/5)+32;
System.out.println("Temperature in Farenheit :"+f);
break;
}
}
}

Output :
Enter 1. Farenheit to Celsius:
Enter 2. Celsius To Farenheit:
Enter Choice :1
Enter Temperature in Farenheit :100
Temperature in Celsius :37
Enter 1. Farenheit to Celsius:
Enter 2. Celsius To Farenheit:
Enter Choice :2
Enter Temperature in Celsius :100
Temperature in Farenheit :212

Question 6.
Write a class Automorphic to check whether a number is Automorphic or not using function with
the help of a method
Int digit(int n)
Solution
import java.io.*;
/**
* class Automorphic
*
*/
public class Automorphic
{
int digits(int n)
{
int c,p,k;c=0;k=0;
while(n!=0)
{
k=n/10;
c=c+1;
n=k;
}
return(c);
}

public static void main(String args[])throws IOException


{
InputStreamReader read =new InputStreamReader(System.in);
BufferedReader in =new BufferedReader(read);
int m,n,p,b;
double r;
r = 0;
Automorphic ob= new Automorphic();
System.out.println("Enter your no.");
n=Integer.parseInt(in.readLine());
m= n;
p= m * m;
b=ob.digits(n);
r=p % (Math.pow(10,b));
if(m==r)
System.out.println(m + " is an Automorphic no.");
else
System.out.println(m + " is not an Automorphic no.");
}
}

Output;
Enter your no.
625
625 is an Automorphic no.
Enter your no.
525
525 is not an Automorphic no.

Question 7
. A cloth showroom has announced the following festival discounts on the purchase of items based on
the total cost of the items purchased:
Total cost Discount (in Percentage)
Less than Rs. 2000 5%

Rs. 2001 to Rs. 5000 25%


Rs. 5001 to Rs. 10000 35%
Above Rs. 10000 50%
Write a program to input the total cost and to compute and display the amount to be paid by
the customer after availing the discount. Three methods also their input(), calculate() and
display().

olution
import java.io.*;
/**
* class Showroom
*
*/
public class Showroom
{
private double cost; // For cost
private double dis; // For Discount
private double amt; // For Amount
void input()throws IOException
{
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(in);
System.out.println("Enter Cost of the product:");
cost=Double.parseDouble(br.readLine());
}
void calculate()
{
if(cost<=2000)
dis = cost * 0.05;
else if(cost>2000 && cost<=5000)
dis = cost * 0.25;
else if(cost>5000 && cost<=10000)
dis = cost *0.35;
else
dis = cost * 0.5;
amt= cost - dis;
}
void display()
{
System.out.println("Cost of the product="+cost);
System.out.println("Discount given="+dis);
System.out.println("Amount Paid="+amt);
}
public static void main(String args[])throws IOException
{
Showroom ob=new Showroom();
ob.input();
ob.calculate();
ob.display();
}
}
Output:
Enter Cost of the product:
5630
Cost of the product=5630.0
Discount given=1970.4999999999998
Amount Paid=3659.5

Question 8.
Write a program to enter a sentence. Calculate total Vowel, Space, Consonant, and word.

Solution.
import java.io.*;
/**
* class SentenceCounter
*
* Vowel, Space, Consonant and word counter program
*/
class SentenceCounter
{
public static void main(String args[])throws IOException
{
String st="";
int i,l,v,c,sp;
char a;
v=c=sp=0;
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(in);
System.out.println("Enter a sentence:");
st=br.readLine();
l=st.length();
for(i=0;i<l;i++)
{
a=st.charAt(i);
if(a=='a' || a=='A' || a=='e' || a=='E' || a=='i' || a=='I' || a=='o' || a=='O'
|| a=='u' || a=='U')
v++;
if(a==' ')
sp++;

}
c=l-(v+sp);
System.out.println("Total Vowel="+v);
System.out.println("Total Space="+sp);
System.out.println("Total Consonent="+c);
System.out.println("Total Words="+(sp+1));
}
}

Output:
Enter a sentence:
the quick brown fox jumps over a lazy hungry dog
Total Vowel=13
Total Space=9
Total Consonent=27
Total Words=10

Question 9.
Define a class Employee having the following description :
Instance variables :
int pan – to store personal account number
String name – to store name
double taxIncome – to store annual taxable income
double tax – to store tax that is calculated
Member functions :
input ( ) – Store the pan number, name, taxable income
calc( ) – Calculate tax for an employee
display ( ) – Output details of an employee
Write a program to compute the tax according to the given conditions and display the output as
per given format.
Total Annual Taxable Income Tax Rate
Upto Rs, 1,00,000 No tax
From 1,00,001 to 1,50,000 10% of the income exceeding Rs. 1,00,000
From 1,50,001 to 2,50,000 Rs. 5000 + 20% of the income exceeding Rs. 1,50,000
Above Rs. 2,50,000 Rs. 25,000 + 30% of the income exceeding Rs.
2,50,000
Output :
Pan Number Name Tax-income Tax
======= ========== ========= =====
======= ========== ========= =====
======= ========== ========= =====

Solution
import java.io.*;
/**
* class Employee
*
*
*/
class Employee
{
// instance variables
int pan;
String name;
double taxIncome, tax;

// read the data from keyboard


public void input()throws IOException
{
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(in);
System.out.println("Enter the name, pan and taxable income : ");
name = br.readLine();
pan = Integer.parseInt(br.readLine());
taxIncome = Double.parseDouble(br.readLine());

// Method calculate tax


public void calc()
{
tax = 0.0;
if( (taxIncome > 100000) && (taxIncome <= 150000) )
tax = (taxIncome - 100000) * 0.1;
else if( (taxIncome > 150000) && (taxIncome <= 250000) )
tax = 5000.0 + (taxIncome - 150000) * 0.2;
else
tax = 25000.0 + (taxIncome - 250000) * 0.3;
}

// display details of an employee


public void display()
{
System.out.println("Pan Number Name Tax-income Tax");
System.out.println(pan+" " + name + " " + taxIncome + " " + tax);
}
// Main method
public static void main(String args[])throws IOException
{
Employee ob=new Employee();
ob.input();
ob.calc();
ob.display();
}
}

Output:
Enter the name, pan and taxable income :
Abdulla
20938
150000
Pan Number Name Tax-income Tax
20938 Abdulla 150000.0 5000.0

Function / Method
When we define a set of code within a block having a name is called
method. It can call or invoked at any time.

We can define Java method as follows

A simple Java method requires a minimum of three items:


Access Level : public, private, protected
Return Type : void, int, double, (etc.)
Name : whatever you want to call the method

Simple example of a function


private double simpleInterest(double p, double t, double r)
{
double si=(p*t*r)/100;
return si;
}

Here access specifier is private, return type double and function name is
simpleInterst with three parameters. In Java convention function start with
small character.

Full example of function


public class Function1
{
int a,b,c;
int Add() // return method
{
a=10;
b=30;
c=a+b;
return c;
}
public static void main(String smart[])
{
int x;
Function1 ob=new Function1();
x=ob.Add();
System.out.println("Sum="+x);
}
}

What is Actual parameter?


Ans: The actual parameter is a parameter as appear in a method/function.
Actual parameters (also known as arguments) are what are passed by the
caller.

What is Formal parameter?Ans: the Identifier used in a method to


stand for the value that is passed into the method by a caller. Formal
parameters also known as parameter of the function.

You might also like