Introduction to Java-notes
Introduction to Java-notes
1. What is a bytecode?
Ans: The Java development kit comes with a collection of tools that are
used for developing and running java programs.
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. 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.
Ans: The two types of Java Applications are ‘Internet Applets’ and ‘Stand
alone application’.
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. iv) java is case sensitive language, i.e. it distinguished upper and lower
case letters.
2. Differentiate between Compiler and Interpreter.
OR
1. What is an abstraction?
Ans: It mean the ability to take more than one form. For example, an
operation, many types of data used in the operation.
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.
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.
Ans: BASE CLASS – A class from which another class inherits (Also called
SUPER CLASS)
Ans: Keywords are the words that convey a special meaning to the
language compiler. No, keywords can never be used as 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. What are literals? How many types of integer literals are available in 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?
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.
Ans: Floating constants are real numbers. A floating constant can either be
a fractional or in exponent form.
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: Primitive data types are those that are not composed of other data
types. Numeric Integral, Fractional, character and boolean are different
primitive data types.
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: 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: 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. Find the value of x after evaluating x += x++ + –x + 4 where x=3 before the
evaluation. Explain your answer.
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:
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
line comes at the start of a file and is not inside any class. Although it is sometimes referred
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
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
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
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
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
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
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
import java.util.*;
class Automorphic
int n = sc.nextInt();
else
Write a program to find the shortest and the longest word in a sentence and print them along with
their length.
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.
Write a main method to create an object of the class and call the above member methods.
Solution -
int acc_num;
String title;
String author;
acc_num = Integer.parseInt(br.readLine());
title = br.readLine();
author = br.readLine();
System.out.println("Accession Number\tTitle\tAuthor");
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:
Income Tax in
Nil
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;
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) {
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;
input = input.toUpperCase();
int count = 0;
count++;
}
}
System.out.println(count);
(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
below.
Example:
Output:
OO
OO
Output:
@@@@@
@@@@@
(iii) Output:
**
***
Solution.
System.out.print(ch);
System.out.println();
System.out.print("@");
System.out.println();
System.out.print("*");
System.out.println();
}
}
Program 5- Using the switch statement, writw a menu driven program to:
series 0,1,1,2,3,5….The first two Fibonacci numbers are 0 and 1, and each
Solution.
import java.util.Scanner;
System.out.println("Menu");
switch (choice) {
case 1:
int a = 0;
int b = 1;
System.out.print("0 1 ");
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);
}
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);
}
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;
cities[i] = scanner.next();
std[i] = scanner.nextInt();
}
if (cities[i].equals(target)) {
System.out.println("Search successful");
searchSuccessful = true;
break;
if (!searchSuccessful) {
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:
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);
}
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);
}
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%
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;
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.
Here access specifier is private, return type double and function name is
simpleInterst with three parameters. In Java convention function start with
small character.