Nothing Special   »   [go: up one dir, main page]

Java (College File)

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 32

Introduction to java

1. What is java?
Ans. Java is a class-based, object-oriented programming language that is
designed to have as few implementation dependencies as possible.
2. What are the features in Java?
Ans. The main features are
Object Oriented
• • Platform Independent
• • Simple
• • Secure
• • Architecture-neutral
• • Portable
• • Robust
• • Multithreaded
• • Interpreted
• • High Performance
• • Distributed
• • Dynamic

3.What are the difference between c, c++ and java?


Ans. C++ is derived from C and has the features of both procedural and object-
oriented programming languages.
C++ was designed for application and System development.
Java is built upon a virtual machine which is very secure and highly portable in
nature.
4.What do you understand by JVM, JRE AND JDK?
Ans. JDK is a software development kit whereas JRE is a software bundle that
allows Java program to run, whereas JVM is an environment for executing
bytecode. The full form of JDK is Java Development Kit, while the full form of
JRE is Java Runtime Environment, while the full form of JVM is Java Virtual
Machine.
5.What is JIT compiler?
Ans. The Just-In-Time (JIT) compiler is an essential part of the JRE i.e. Java
Runtime Environment, that is responsible for performance optimization of java
based applications at run time. Compiler is one of the key aspects in deciding
performance of an application for both parties i.e. the end user and the
application developer.
6. How Java is platform independent?
Ans. The meaning of platform-independent is that the java compiled code(byte
code) can run on all operating systems. A program is written in a language that
is a human-readable language. It may contain words, phrases, etc. which the
machine does not understand. For the source code to be understood by the
machine, it needs to be in a language understood by machines, typically a
machine-level language. So, here comes the role of a compiler. The compiler
converts the high-level language (human language) into a format understood by
the machines. Therefore, a compiler is a
program that translates the source code for another program from a
programming language into executable code. This executable code may be a
sequence of machine instructions that can be executed by the CPU directly, or it
may be an intermediate representation that is interpreted by a virtual machine.
This intermediate representation in Java is the Java Byte Code.
7. How to compile and run java program?
Ans. Compiling and running a java program is very easy after JDK installation.
Following are the steps −
• • Open a command prompt window and go to the directory where you
saved the java program (MyFirstJavaProgram.java). Assume it's C:\.

• • Type 'javac MyFirstJavaProgram.java' and press enter to compile your


code. If there are no errors in your code, the command prompt will take you to
the next line (Assumption: The path variable is set).

• • Now, type ' java MyFirstJavaProgram ' to run your program.

• • You will be able to see the result printed on the window.


Basic Programs:
1.Write a program to print “Hello World” in java.
import java.util.*;
public class Hello{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
Output:
Hello World
2.Write a program to perform arithmetic operations such as addition,
subtraction, multiplication and division of two numbers.
import java.util.Scanner;
public class Aroperation
{
public static void main(String args[]){
int first, second, add, subtract, multiply;
float devide;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Two Numbers : ");
first = scanner.nextInt();
second = scanner.nextInt();
add = first + second;
subtract = first - second;
multiply = first * second;
devide = (float) first / second;
System.out.println("Sum = " + add);
System.out.println("Difference = " + subtract);
System.out.println("Multiplication = " + multiply);
System.out.println("Division = " + devide);
}
}
Output:
Enter Two Numbers : 6
9
Sum = 15
Difference = -3
Multiplication = 54
Division = 0.6666667
3. Write a program to calculate simple interest.
import java.util.Scanner;
class SI {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the principal: ");
double principal = input.nextDouble();
System.out.print("Enter the rate: ");
double rate = input.nextDouble();
System.out.print("Enter the time: ");
double time = input.nextDouble();
double interest = (principal * time * rate) / 100;
System.out.println("Principal: " + principal);
System.out.println("Time Duration: " + time);
System.out.println("Simple Interest: " + interest);
input.close();
}
}
Output :
Enter the principal: 1000
Enter the rate: 5
Enter the time: 2
Principal: 1000.0
Time Duration: 2.0
Simple Interest: 100.0
4. Write a program to check given number is even number or odd number.
import java.util.Scanner;
public class EvenOdd {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = reader.nextInt();
if(num % 2 == 0)
System.out.println(num + " is even");
else
System.out.println(num + " is odd");
}
}
Output :
Enter a number: 69
69 is odd
5.Write a program to calculate factorial of given number.
import java.util.*;
public class factorial
{
public static void main(String[] args)
{
int i,number , fact=1;
System.out.println("Enter a number");
Scanner sc = new Scanner(System.in);
number = sc.nextInt();
for(i=1;i<=number;i++)
{
fact = fact*i;
}
System.out.printf("Factorial of %d is %d ",number,fact);
}
}
Output
Enter a number
7
Factorial of 7 is 5040
6.Write a program to convert temperature from Fahrenheit to Celsius.
import java.util.*;
public class FtoC {
public static void main(String[] args) {
float F, C;
System.out.println("Enter Temperature in Fahrenheit");
Scanner sc = new Scanner(System.in);
F = sc.nextFloat();
System.out.println("Converting F To C");
C = ((F - 32)*5)/9;
System.out.printf("Temperature in Celsius is %f C ",C);
}
}
Output:
Enter Temperature in Fahrenheit
212
Converting F To C
Temperature in Celsius is 100.000000 C
7.Write a program to find largest no is 3 numbers.
import java.util.*;
public class Largestno {
public static void main(String [] args){
int a ,b,c;
Scanner sc = new Scanner(System.in);
System.out.println("Input the value of number 1");
a = sc.nextInt();
System.out.println("Input the value of number 2");
b = sc.nextInt();
System.out.println("Input the value of number 3");
c = sc.nextInt();
if(a>b && a>c)
{
System.out.println(+a+" is largest number ");
}
else if (b>a && b>c)
{
System.out.println(+b+ " is largest number ");
}
else
{
System.out.println(+c+ " is largest number ");
}
}
}
Output :
Input the value of number 1
5
Input the value of number 2
6
Input the value of number 3
9
9 is largest number
8.Write a program to print first 10 terms of Fibonacci series.
import java.util.*;
public class Fibonacci {
public static void main(String[] args) {
{
{
int i, number, Fibonacci;
int a = 0, b = 1;
System.out.println("Enter a number");
Scanner sc = new Scanner(System.in);
number = sc.nextInt();
System.out.println("Fionacci series of number is ");
for (i = 1; i <= number; i++) {
Fibonacci = a + b;
System.out.printf("%d\t", Fibonacci);
a = b;
b = Fibonacci;
}
}
}
}
}
Output:
Enter a number
8
Fionacci series of number is
1 2 3 5 8 13 21 34
9.Write a program to print a table of any given number.
import java.util.*;
public class Table
{
public static void main(String[] args)
{
int i,num;
System.out.println("Enter any value");
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
System.out.println("Table of given number is ");
for(i=1;i<=10;i++)
{
System.out.printf("%d X %d = %d\n",num,i,num*i );
}
}
}
Output:
Enter any value
69
Table of given number is
69 X 1 = 69
69 X 2 = 138
69 X 3 = 207
69 X 4 = 276
69 X 5 = 345
69 X 6 = 414
69 X 7 = 483
69 X 8 = 552
69 X 9 = 621
69 X 10 = 690
10.Write a program to print reverse of a given number.
import java.util.*;
public class Reverse {
public static void main(String[] args) {
int i,num,rev=0,rem;
Scanner sc = new Scanner(System.in);
System.out.println("Enter any value");
num = sc.nextInt();
System.out.printf("Reverse of a given number %d is\n ",num);
while(num!=0)
{
rem = num%10;
rev = rev*10 + rem;
num = num/10;
}
System.out.println(rev);
}
}
Output:
Enter any value
369
Reverse of a given number 369 is
963
11.Write a program to convert decimal value to binary value.
import java.util.*;
public class BinarytoD {
public static void main(String args[])
{
int dec_num, quot, i=1, j;
int bin_num[] = new int[100];
Scanner sc = new Scanner(System.in);
System.out.println("Input a Decimal Number : ");
dec_num = sc.nextInt();
quot = dec_num;
while(quot != 0)
{
bin_num[i++] = quot%2;
quot = quot/2;
}
System.out.print("Binary number is: ");
for(j=i-1; j>0; j--)
{
System.out.print(bin_num[j]);
}
• b. 101 to 150 units----------3Rs/Unit
• c. 151 and above units-----7Rs/Unit

System.out.print("\n");
}
}
Output:
Input a Decimal Number :
69
Binary number is: 1000101
12.Write a program to calculate electricity bill according to the following
charges (Units given by user): a. 0 to 100 units -------------2Rs/Unit
Also add fixed charges of 200Rs
import java.util.Scanner;
public class ElectricityBill
{
private static Scanner sc;
public static void main(String[] args)
{
int Units;
double X,Amount,Total_Amount;
sc = new Scanner(System.in);
System.out.print("Please Enter the Consumed Units: ");
Units = sc.nextInt();
if (Units <=100)
{
Amount = Units * 2;
}
else if (Units <= 150)
{
Amount = 300 + ((Units - 100 ) * 3);
}
else
{
Amount = 1050+ ((Units - 150 ) * 7);
}
X = Amount;
Total_Amount = Amount + 200;
System.out.println("\nElectricity Charges = " + X );
System.out.println("Fixed Charge = 200");
System.out.println("Total Electricity Bill = " + Total_Amount);
}
}
Output:
Please Enter the Consumed Units: 625
Electricity Charges = 4375.0
Fixed Charge = 200
Total Electricity Bill = 4575.0
Experiment 1
Aim: Write a program to implement Stack and Queue using Array.
Stack
import java.io.*;
class Stack
{
static int max=10,i,top,ch,item;
static int a[]=new int[10];
StackArray()
{
top=-1;
}
public static void main(String args[])throws IOException
{
while((boolean)true)
{
System.out.println("enter 1.Push 2.Pop 3.Display 4.Exit");
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ch=Integer.parseInt(br.readLine());
}
catch(Exception e) { }
if(ch==4)
break;
else
{
switch(ch)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
}
}
}
}
static void push()
{
if(top==max)
System.out.println("stack is full");
else
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the element:");
item=Integer.parseInt(br.readLine());
a[++top]=item;
}
catch(Exception e) { }
}
static void pop()
{
if(top==-1)
System.out.println("stack is empty");
else
top--;
System.out.println("poped item:"+a[top]);
}
static void display()
{
System.out.println("elements in stack are:");
for(i=top; i>0; i--)
System.out.println(a[i]);
}
}
Output:
enter 1.Push 2.Pop 3.Display 4.Exit
1
enter the element:
5
enter 1.Push 2.Pop 3.Display 4.Exit
1
enter the element:
6
enter 1.Push 2.Pop 3.Display 4.Exit
1
enter the element:
7
enter 1.Push 2.Pop 3.Display 4.Exit
2
poped item:7
enter 1.Push 2.Pop 3.Display 4.Exit
3
elements in stack are:
6
5
enter 1.Push 2.Pop 3.Display 4.Exit
4
Queue
import java.io.*;
class Queue
{
static int i,front,rear,item,max=5,ch;
static int a[]=new int[5];
QueueArr()
{
front=-1;
rear=-1;
}
public static void main(String args[])throws IOException
{
while((boolean)true)
{
try
{
System.out.println("Select Option 1.insert 2.delete 3.display 4.Exit");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ch=Integer.parseInt(br.readLine());
}
catch(Exception e)
{}
if(ch==4)
break;
else
{
switch(ch)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
}
}
}
}
static void insert()
{
if(rear>=max)
{
System.out.println("Queue is Full");
}
else
{
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Element: ");
item=Integer.parseInt(br.readLine());
}
catch(Exception e)
{}
rear=rear+1;
a[rear]=item;
}
}
static void delete()
{
if(front==-1)
{
System.out.println("Queue is Empty");
}
else
{
front=front+1;
item=a[front];
System.out.println("Deleted Item: "+item);
}
}
static void display()
{
System.out.println("Elements in the Queue are:");
for(int i=front+1; i<=rear; i++)
{
System.out.println(a[i]);
}
}
}
Output:
Select Option 1.insert 2.delete 3.display 4.Exit
1
Enter the Element:
5
Select Option 1.insert 2.delete 3.display 4.Exit
1
Enter the Element:
6
Select Option 1.insert 2.delete 3.display 4.Exit
1
Enter the Element:
7
Select Option 1.insert 2.delete 3.display 4.Exit
2
Deleted Item: 5
Select Option 1.insert 2.delete 3.display 4.Exit
3
Elements in the Queue are:
6
7
Select Option 1.insert 2.delete 3.display 4.Exit
4
Experiment 2
Aim : Write a Java Program with default and paramaterized constructor.
public class Vehicle1 {
int passengers;
int fuelCapacity;
int mileage;
Vehicle1() {
System.out.println("This is Default constructor");
}
Vehicle1(int passengers, int fuelCapacity, int mileage) {
System.out.println(" This is Parameterized constructor");
this.passengers = passengers;
this.fuelCapacity = fuelCapacity;
this.mileage = mileage;
}
void fuelConsumption() {
int fc = (fuelCapacity * 100) / mileage;
System.out.println("Fuel consumption : " + fc + " litre ");
}
public static void main(String args[]) {
Vehicle1 v = new Vehicle1(8, 60, 14);
Vehicle1 v1 = new Vehicle1();
v.fuelConsumption();
}
}
Output:
This is Parameterized constructor
This is Default constructor
Fuel consumption : 428 litre
Experiment 3
Inheritance
Aim: Write a Java Program and create a class Shape which has width,
height, radius and create three classes Rectangle, Square and Circle and
shows Inheritance Properties among them.
import java.util.*;
import java.util.*;
class Shape{
int width,height,radius;
Shape()
{
}
Shape(int p)
{
}
Shape(int c,int b)
{
}
}
class Rectangle extends Shape{
Rectangle(int width, int height)
{
super(width,height);
this.width = width;
this.height = height;
}
void area()
{
int a = width*height;
System.out.println("Area of Rectangle is :"+a);
}
}
class Square extends Shape{
Square(int width)
{
super(width);
this.width = width;
}
void area()
{
int a = width*width;
System.out.println("Area of Square is :"+a);
}
}
class Circle extends Shape{
Circle(int radius)
{
super(radius);
this.radius = radius;
}
void area()
{
double a = (double) (Math.PI*radius*radius);
System.out.println("Area of Circle is :"+a);
}
}
public class exp3{
public static void main(String[] args){
Rectangle n = new Rectangle(4,5);
n.area();
Square p = new Square(6);
p.area();
Circle m = new Circle(3);
m.area();
Shape s = new Shape();
}
}
Output:
Area of Rectangle is :20
Area of Square is :36
Area of Circle is :28.274333882308138
Experiment 4
Aim : Program on String
import java.util.Scanner;
public class exp4
{
public static void main (String args[])
{
String S1 = new String ("This is string");
String S2 = new String ("\nHi");
System.out.println ("String Length :" +S1.length ());
System.out.println ("String Length :" +S2.length ());
String S3 = S1.concat(S2);
System.out.println (S3);
int index1=S1.indexOf("is");
System.out.println("Index:" +index1);
String a = new String ("123");
String b = new String ("123");
String c = new String ("124");
System.out.println (a.equals (b));
System.out.println (a.equals (c));
}
}
Output:
String Length :14
String Length :3
This is string
Hi
Index:2
true
false
Experiment 5
Aim: Program using StringBuffer Class.
public class exp5
{
public static void main(String[] args)
{
StringBuffer a = new StringBuffer("Hello");
a.append(50.55);
System.out.println("appending double = " + a);
a.append('N');
System.out.println("appending character = " + a);
a.append("java");
System.out.println("appending string = "+ a);
a.insert(11, "program5");
System.out.println("inserting string = "+ a);
a.insert(5, 60.66);
System.out.println("inserting double = "+ a);
a.reverse();
System.out.println("reverse = " + a);
}
}
Output :
appending double = Hello50.55
appending character = Hello50.55N
appending string = Hello50.55Njava
inserting string = Hello50.55Nprogram5java
inserting double = Hello60.6650.55Nprogram5java
reverse = avaj5margorpN55.0566.06olleH
Experiment 6
Aim: Program to convert int, float integer, gloat object into
string.
public class exp6
{
public static void main(String args[])
{
int a = 10;
String str_1 = Integer.toString(a);
System.out.println("\nint:"+a);
System.out.println("After int to stirng = " + str_1);
float x = 50.55f;
System.out.println("\nfloat:"+x);
String str_2 = Float.toString(x);
System.out.println("After float to stirng = " + str_2);
Float fobj = new Float(10.25);
System.out.println("\nfloat object:"+fobj);
String str_3 = fobj.toString();
System.out.println("Float converted to String as " + str_3);
}
}
Output:
int:10
After int to stirng = 10
float:50.55
After float to stirng = 50.55
float object:10.25
Float converted to String as 10.25
Experiment 7
Aim: Program to display values of the field by overriding
toString() method.
public class exp7_1
{
public static void main(String[] args)
{
student s = new student();
System.out.println(s);
}
}
class student{
int Enrollment_Number;
float cgpa;
String name;
student()
{
Enrollment_Number = 214;
name = "Naman Sharma";
cgpa = 8.0F;
}
public String toString() {
return String.format("Name:"+ name + " \n" +"Enrollment_Number:" +
Enrollment_Number + "\n"+ "CGPA:"+ cgpa );
}
};
Output:
Name:Naman Sharma
Enrollment_Number:214
CGPA:8.0
Experiment 8
Aim: Exception Handling program
import java.util.*;
import java.io.*;
public class exp8 {
public static void main(String[] args)
{
//Arithmetic Exception
try {
int num1 = 10;
int num2 = 0;
int output = num1 / num2;
System.out.println("Output" + output);
} catch (ArithmeticException e1) {
System.out.println("Arithmetic Exception :");
System.out.println("Can't divide num1 by 0");
}
//Array Index Out of Bounds
try {
int arr[] = new int[10];
arr[11] = 5;
} catch (ArrayIndexOutOfBoundsException e2) {
System.out.println("Array Index is Out of Bounds Exception");
System.out.println("\n");
}
//String Index Out of Bounds
try {
String s = "Naman";
char c = s.charAt(26);
System.out.println(c);
} catch (StringIndexOutOfBoundsException e3) {
System.out.println("String Index is Out of Bounds Exception");
System.out.println("\n");
}
//NULL Pointer Exception
try {
String s1 = null;
System.out.println(s1.length());
} catch (NullPointerException e4) {
System.out.println("This is NULL Pointer Exception");
System.out.println("\n");
}
//Number Format Exception
try {
int n = Integer.parseInt("NS");
System.out.println(n);
} catch (NumberFormatException e5) {
System.out.println(" This is NUMBER FORMAT EXCEPTION");
System.out.println("\n");
}
//File Not Found Exception
try {
File f = new File(("D://xy.txt"));
FileReader fr = new FileReader(f);
} catch (FileNotFoundException e6) {
System.out.println(" Given File (D://xy.txt) Does not exist ");
}
}
}
Output:
Arithmetic Exception :
Can't divide num1 by 0
Array Index is Out of Bounds Exception
String Index is Out of Bounds Exception
This is NULL Pointer Exception
This is NUMBER FORMAT EXCEPTION
Given File (D://xy.txt) Does not exist
Experiment 9
i)Nested Try Clause
class exp9_1
{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e)
{
System.out.println(e);
}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}catch(Exception e)
{
System.out.println("handeled");
}
System.out.println("normal flow");
}
}
Output:
going to divide
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length
5
other statement
normal flow
ii) Multiple Catch Clause
public class exp9_2 {
public static void main(String[] args) {
try
{
int arr[] = new int[10];
arr[10] = 10/0;
}
catch (ArithmeticException e)
{
System.out.println("Arithmetic Exception Occurs First");
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index Out of Bounds Exception Occurs ");
}
}
}
Output:
Arithmetic Exception Occurs First
Experiment 10
i) Thread Class
class MyThread1 extends Thread{
public MyThread1(String name)
{
super(name);
}
public void run()
{
int i =0;
while (i<=40)
{
System.out.println(this.getName()+":"+i);
i++;
try { Thread.sleep(300);}
catch (Exception e){}
}
}
}
public class exp10_1 {
public static void main(String[] args) {
MyThread1 t1 = new MyThread1("Hello");
MyThread1 t2 = new MyThread1("Java");
t1.start();
t2.start();
}

You might also like