Mca r20 Java
Mca r20 Java
KOMMADI, VISAKHAPATNAM
(Approved by AICTE, New Delhi & Affiliated to JNTU Gurajada Vizianagaram)
NBA & NAAC Accredited
CERTIFICATE
is a student studying
in the subject
1 1 2 3 5 8 13 21 34 55
With Recursion
class FibonacciExample2{
static int n1=1,n2=1,n3=0;
static void printFibonacci(int count){
if(count>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
printFibonacci(count-1);
}
}
public static void main(String args[]){
int count=10;
System.out.print(n1+" "+n2);//printing 1 and 1
printFibonacci(count-2);//n-2 because 2 numbers are already printed
}
}
Output:
D:\maha>javac FibonacciExample2.java
D:\maha>java FibonacciExample2
1 1 2 3 5 8 13 21 34 55
2. Write a Java Program that prompts the user for an integer and then prints out all the
prime numbers up to that Integer.
import java.util.Scanner;
class PrimeNumbers{
public static void main(String[] args){
int n;
int p;
Scanner s=new Scanner(System.in);
System.out.println("Enter a number: ");
n=s.nextInt();
for(int i=2;i<n;i++){
p=0;
for(int j=2;j<i;j++){
if(i%j==0)
p=1;
}
if(p==0)
System.out.println(i);
}
}
}
Output:
D:\maha>javac PrimeNumbers.java
D:\maha>java PrimeNumbers
Enter a number:
20
prime numbers are:2
prime numbers are:3
prime numbers are:5
prime numbers are:7
prime numbers are:11
prime numbers are:13
prime numbers are:17
prime numbers are:19
3. Write a Java Program that checks whether a given string is a palindrome or not. Ex.
MALAYALAM is a palindrome
import java.util.Scanner;
class ChkPalindrome
{
public static void main(String args[])
{
String str, rev = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
str = sc.nextLine();
int length = str.length();
for ( int i = length - 1; i >= 0; i-- )
rev = rev + str.charAt(i);
if (str.equals(rev))
System.out.println(str+" is a palindrome");
else
System.out.println(str+" is not a palindrome");
}
}
Output:
D:\maha>javac ChkPalindrome.java
D:\maha>java ChkPalindrome
Enter a string:
maha
maha is not a palindrome
D:\maha>javac ChkPalindrome.java
D:\maha>java ChkPalindrome
Enter a string:
malayalam
malayalam is a palindrome
4. Write a Java Program for sorting a given list of names in ascending order.
import java.util.Scanner;
public class Ascending_Order
{
public static void main(String[] args)
{
int n;
String temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter number of names you want to enter:");
n = s.nextInt();
String names[] = new String[n];
Scanner s1 = new Scanner(System.in);
System.out.println("Enter all the names:");
for(int i = 0; i < n; i++)
{
names[i] = s1.nextLine();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (names[i].compareTo(names[j])>0)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
System.out.print("Names in Sorted Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(names[i] + ",");
}
System.out.print(names[n - 1]);
}
}
Output:
D:\maha>javac Ascending_Order.java
D:\maha>java Ascending_Order
Enter number of names you want to enter:4
Enter all the names:
satish
yoshitha
maha
mani
Names in Sorted Order:maha,mani,satish,yoshitha
5. Write a Java Program that illustrates how runtime polymorphism is achieved.
class Shape {
void draw() {
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle");
}
}
class Square extends Shape {
@Override
void draw() {
System.out.println("Drawing a square");
}
}
package mypack
public class box
{
public int
l=10,b=20;
public void
display()
{
System.out.println(l);
System.out.println(b);
}
}
3. Create sub directory with a name same that of package name under the current working
directory by as follows. d:\>md mypack
4. Under this subdirectory store the above SOURCE-CODE with a file name “box.java”.
import
mypack.bo
x;class
packagede
mo
{
public static void main(String args[])
{
box
b1=new
box();
b1.display(
);
}
}
3. Now compile the above SOURCE-CODE in the current working directory d:\
javac packagedemo.java
4. Execute the above SOURCE-CODE in current working directory
java packagedemo
OUT-PUT:
10
20
7. Write a Java Program, using StringTokenizer class, which reads a line of integers and
then displays each integer and the sum of all integers.
import java.util.*;
class Demo_string_tokenizer{
public static void main(String args[]) {
int n;
int sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter integers with one space gap:");
String s = sc.nextLine();
StringTokenizer st = new StringTokenizer(s, " ");
while (st.hasMoreTokens()) {
String temp = st.nextToken();
n = Integer.parseInt(temp);
System.out.println(n);
sum = sum + n;
}
System.out.println("sum of the integers is: " + sum);
sc.close();
}
}
Output:
D:\maha>javac Demo_string_tokenizer.java
D:\maha>java Demo_string_tokenizer
Enter integers with one space gap:
21
2
1
sum of the integers is: 3
8.Write a Java Program that reads on file name form the user then displays information
about whether the file exists, whether the file is readable/ writable, the type of file and the
length of the file in bytes and display the content of the using FileInputStream class.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Files_example {
public static void main(String args[]) {
//Creating a Path object
Path path = Paths.get("D:/maha/sample.txt");
//Verifying if the file is readable
boolean bool = Files.isReadable(path);
if(bool) {
System.out.println("readable");
} else {
System.out.println("not readable");
}
bool = Files.isWritable(path);
if(bool) {
System.out.println("writable");
} else {
System.out.println("not writable");
}
bool = Files.isExecutable(path);
if(bool) {
System.out.println("executable");
} else {
System.out.println("not executable");
}
}
}
Output:
D:\maha>javac Files_example.java
D:\maha>java Files_example
not readable
not writable
not executable
9. Write a Java Program that displays the number of characters, lines and words in a
text/text file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Word_countin_file
{
public static void main(String[] args)
{
BufferedReader reader = null;
int charCount = 0;
int wordCount = 0;
int lineCount = 0;
try
{
reader = new BufferedReader(new FileReader("D:/maha/sample.txt"));
String currentLine = reader.readLine();
while (currentLine != null)
{
lineCount++;
String[] words = currentLine.split(" ");
wordCount = wordCount + words.length;
for (String word : words){
charCount = charCount + word.length();
}
currentLine = reader.readLine();
}
System.out.println("Number Of Chars In A File : "+charCount);
System.out.println("Number Of Words In A File : "+wordCount);
System.out.println("Number Of Lines In A File : "+lineCount);
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
reader.close(); //Closing the reader
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
Output:
D:\maha>javac Word_countin_file.java
D:\maha>java Word_countin_file
Number Of Chars In A File : 86
Number Of Words In A File : 14
Number Of Lines In A File : 4
10. Write an Applet that displays the content of a file.
import java.applet.*;
import java.awt.*;
import java.io.*;
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
String content = "";
try
{
char ch;
StringBuffer buff = new StringBuffer("");
FileInputStream fis = new FileInputStream("sample.txt");
while(fis.available()!=0)
{
ch = (char)fis.read();
buff.append(ch);
}
fis.close();
content = new String(buff);
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find the specified file...");
}
catch(IOException i)
{
System.out.println("Cannot read file...");
}
g.drawString(content,20,20);
}
}
<applet code="MyApplet" height="300" width="500">
</applet>
Output:
11. Write a Java Program that works as a simple calculator. Use a grid layout to
arrange buttons for the digits and for the + *?% operations. Add a text field to
display the result.
import java.awt.*;
import java.awt.event.*;
public class MyCalculator extends Frame implements ActionListener {
double num1,num2,result;
Label lbl1,lbl2,lbl3;
TextField tf1,tf2,tf3;
Button btn1,btn2,btn3,btn4;
char op;
MyCalculator() {
lbl1=new Label("Number 1: ");
lbl1.setBounds(50,100,100,30);
tf1=new TextField();
tf1.setBounds(160,100,100,30);
tf2=new TextField();
tf2.setBounds(160,170,100,30);
btn1=new Button("+");
btn1.setBounds(50,250,40,40);
btn2=new Button("-");
btn2.setBounds(120,250,40,40);
btn3=new Button("*");
btn3.setBounds(190,250,40,40);
btn4=new Button("/");
btn4.setBounds(260,250,40,40);
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
btn4.addActionListener(this);
add(lbl1); add(lbl2); add(lbl3);
add(tf1); add(tf2); add(tf3);
add(btn1); add(btn2); add(btn3); add(btn4);
setSize(400,500);
setLayout(null);
setTitle("Calculator");
setVisible(true);
num1 = Double.parseDouble(tf1.getText());
num2 = Double.parseDouble(tf2.getText());
if(ae.getSource() == btn1)
{
result = num1 + num2;
tf3.setText(String.valueOf(result));
}
if(ae.getSource() == btn2)
{
result = num1 - num2;
tf3.setText(String.valueOf(result));
}
if(ae.getSource() == btn3)
{
result = num1 * num2;
tf3.setText(String.valueOf(result));
}
if(ae.getSource() == btn4)
{
result = num1 / num2;
tf3.setText(String.valueOf(result));
}
}
class Slice {
double value;
Color color;
public Slice(double value, Color color) {
this.value = value;
this.color = color;
}
}
class MyComponent extends JComponent {
Slice[] slices = {
new Slice(5, Color.black), new Slice(33, Color.green), new Slice(20, Color.yellow), new
Slice(15, Color.red)
};
MyComponent() {}
public void paint(Graphics g) {
drawPie((Graphics2D) g, getBounds(), slices);
}
void drawPie(Graphics2D g, Rectangle area, Slice[] slices) {
double total = 0.0D;
Queue operations
1. Insert
2. Delete
3. Display
4. Exit
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 3
QueueError: Queue is Empty
at Que.display(Exception_queue.java:81)
at Exception_queue.main(Exception_queue.java:126)
Queue operations
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 4