12th STD All Programs
12th STD All Programs
-: Textual Illustrations :-
1. Computer the cost of phone call and update the balance.
Script
public class CallCost
{
public static void main(String[] args)
{
double b;
double r;
double d;
double c;
b = 170;
r = 1.02;
d = 37;
c=d * r;
b= b - c;
System.out.println("duration:"+d+"Seconds");
System.out.println("balance: "+b+"Rupees");
}
}
Output
duration:37.0 Seconds
balance: 132.26 Rupees
i=p*r*n/100;
a=p+i;
System.out.println(“interest=”+i);
System.out.println(“Maturity Amount=”+a);
}
}
Output
Interest=285.0
Maturity Amount=1285.0
class A
{
public static void main (String[] args)
{
int x=6;
int y=4;
System.out.println("x + y = " + (x + y ));
System.out.println("x - y = " + (x - y ));
System.out.println("x / y = " + (x / y ));
System.out.println("x % y = " + (x % y ));
}
}
Output
x + y = 10
x-y=2
x/y=1
x%y=2
class Nested
{
public static void main(String[] args)
{
int age = 28;
Output
adult!
class odd_even
{
public static void main(String[] args)
{
int x=12;
if( x % 2 == 0)
{
System.out.println("even");
}
else
{
System.out.println("odd");
}
}
}
Output
even
class numbers
{
public static void main(String[] args)
{
for (int i= 1; i<= 100; i++)
{
System.out.println(i);
}
}
}
Output
1 2 3 4 5 6 7 8 9 . . . . . 100
1. During a sale at a store, a 10% discount is applied to purchase over Rs. 5000. Write a
program that assigns any value to variable ‘purchase’ and then calculates the discounted price.
Display purchase amount and discount offered.
Script
class discount
{
public static void main(String args[])
{
int purchase=14000;
int discount;
int amount;
Output
Discount is=1400
Amount after applying discount 10%=12600
else
{
ticket=40;
}
}
Output
Customer Age:10
Show Time:7.0
Ticket:40
Output
Your Grade is C+
Output
Output
-: Textual Illustrations :-
1. Write a Program in Java to create a class named “Room” with attributes length, width, height
and three methods. The first method will assign values to attributes, second one will calculate
area, and third will assign values to attributes.
Script
length=0.0
width=0.0
height=0.0
length=0.0
width=0.0
height=0.0
length=10.0
width=20.0
height=30.0
length=11.0
width=24.0
height=23.0
area of room=200.0
Script
class Room
{
float length, width, height;
byte nWindows;
static int totwindows; //class variable
void setWindows(byte n)
{
totwindows = totwindows - nWindows + n;
nWindows = n;
}
double area()
{
return (length*width);
}
void display()
{
System.out.println("\nLength:" + length+ "\nwidth" +width);
System.out.println("Height:" + height);
System.out.println("Numbers of windows:" + nWindows);
}
}
class RoomDemoStatic
{
public static void main(String args[])
{
Room r1= new Room(); Room r2= new Room();
Output
Length:18.0
width:12.5
Height:10.0
Numbers of windows:2
Length:0.0
width0.0
Height:0.0
Numbers of windows:0
Script
class PrintLine
{
static void printline()
{
for (int i=0; i<40;i++)
System.out.print("=");
System.out.println();
}
========================================
##############################
++++++++++++++++++++
class Room
{
float lenght, width, height;
byte nWindows;
static int totwindows;
double area()
{
return (lenght*width);
}
void display()
{
System.out.println("\nLength:" + lenght+ "\nwidth" +width);
System.out.println("Height:" + height);
System.out.println("Numbers of windows:" + nWindows);
}
}
class RoomConstractorDemoA
{
public static void main(String args[])
{
Room r1= new Room(16,12.5f);
Room r2= new Room(20,14,12,(byte)2);
r1.display();
HR ZONE Computer Classes TM 19
System.out.println("\n Total number windows:" + Room.totwindows);
}
}
Output
Length:16.0
width12.5
Height:10.0
Numbers of windows:1
Total number windows:3
class Room
{
float lenght, width, height;
byte nWindows;
static int totwindows;
Room(){}
Room (float l, float w,float h,byte n)
{
lenght = l; width = w; height = h;
nWindows = n; totwindows+=n;
}
double area()
{
return (lenght*width);
}
void display()
{
System.out.println("\nLength:" + lenght+ "\nwidth" +width);
System.out.println("Height:" + height);
System.out.println("Numbers of windows:" + nWindows);
}
}
class RoomConstractorDemoB
{
public static void main(String args[])
{
Room r1= new Room();
HR ZONE Computer Classes TM 21
Room r2= new Room(20,14,12,(byte)2);
r1.display(); r2.display();
System.out.println("\n Total number windows:" + Room.totwindows);
}
}
Output
Length:0.0
width0.0
Height:0.0
Numbers of windows:0
Length:20.0
width14.0
Height:12.0
Numbers of windows:2
Total number windows:2
class Rectangle
{
double length, width;
double area()
{
return length*width;
}
void display()
{
System.out.println("Rectangle with length= " + length + "width= " +
width);
}
}
class RectangleDemo
{
public static void main(String args[])
{
Rectangle rect1;
rect1= new Rectangle();
Rectangle rect2=new Rectangle();
rect1.setAttributes(10.5,20);
rect1.display();
System.out.println("Area of rectangle is: " + rect1.area());
rect2.setAttributes(10,15);
System.out.println("Area of rectangle with length: " + rect2.length+ ",
width="+ rect2.width+"is"+rect2.area());
}
}
class Rectangle
{
private double length, width;
Rectangle(double x, double y)
{
length = x; width = y;
}
Rectangle(){};
double area()
{
return length*width;
}
void display()
{
System.out.println("Rectangle with length= " + length + "width= " +
width);
}
}
class visibilityPrivateB
{
public static void main(String args[])
{
Rectangle rect1;
rect1= new Rectangle();
Rectangle rect2=new Rectangle(10,15);
rect1.display(); rect2.display();
System.out.println("Area of rectangle with length: " + rect2.length+ ",
width="+ rect2.width+"is"+rect2.area());
}
}
HR ZONE Computer Classes TM 25
Output
Error
2 errors
class Rectangle
{
private double length, width;
Rectangle(double x, double y)
{
length = x; width = y;
}
Rectangle(){};
double area()
{
return length*width;
}
void display()
{
System.out.println("Rectangle with length= " + length + "width= " +
width);
}
double getLength(){return length;}
double getWidth(){return width;}
}
class visibilityPrivateB
{
public static void main(String args[])
{
Rectangle rect1;
rect1= new Rectangle();
Rectangle rect2=new Rectangle(10,15);
rect1.display(); rect2.display();
System.out.println("Area of rectangle with length: " + rect2.getLength()+
", width="+ rect2.getWidth()+"is"+rect2.area());
}
}
HR ZONE Computer Classes TM 27
Output
class Rectangle
{
private double length, width;
Rectangle(double x, double y)
{
length = x; width = y;
}
Rectangle(){};
class ObjectParameter
{
public static void main(String[] s)
{
Rectangle rect1 = new Rectangle(8,20);
Rectangle rect2 = new Rectangle(10,15);
rect1.display();
System.out.println("Area of rectangle 1 is: " + rect1.area()+ "\n");
rect2.display();
System.out.println("Area of rectangle 2 is: " + rect2.area()+ "\n");
if(rect1.isLarge(rect2))
Output
Script
length=l;
width=w;
height=h;
double area()
return(length*width);
void display()
System.out.println("\nlength="+length);
System.out.println("width="+width);
System.out.println("height="+height);
int benches,seats;
super(l,w,h);
benches=b;
seats=s;
int getseats()
return(benches*seats);
void show()
super.display();
System.out.println("benches="+benches);
System.out.println("seats="+seats);
void display()
System.out.println("Total seats="+getseats());
class inheritancedemo
c1.show();
c1.display();
System.out.println("area of room="+r1.area());
System.out.println("area of classroom="+c1.area());
Output
length=10.0
width=20.0
height=30.0
length=15.0
width=25.0
height=35.0
benches=10
seats=5
Total seats=50
area of room=200.0
area of classroom=375.0
Script
class room
{
protected float length,width,height; //local
room(float l,float w,float h)
{
length=l;
width=w;
height=h;
}
double area()
{
return(length*width);
}
void display()
{
System.out.println("length="+length);
System.out.println("width="+width);
System.out.println("height="+height);
}
}
class library
{
int books,magazines,newspaper;
room readingroom;
library(int b,int m,int n,room r)
{
books=b;
magazines=m;
newspaper=n;
readingroom=r;
}
void display()
{
System.out.println("books="+books);
System.out.println("magazines="+magazines);
System.out.println("newspaper="+newspaper);
readingroom.display();
HR ZONE Computer Classes TM 34
}
}
class container
{
public static void main(String args[])
{
room r1=new room(10,20,30);
library l1=new library(300,200,100,r1);
r1.display();
l1.display();
}
}
Output
length=10.0
width=20.0
height=30.0
books=300
magazines=200
newspaper=100
length=10.0
width=20.0
height=30.0
1. Create a class named ‘Fixed Deposit’ that contains three attributes (principal amount,annual
interest rate and period(years) of deposit) and a method that returns maturity amount using
compound interest.Create another class named ‘FixedDepositDemo’ with main()
method,create two objects,assign the values to their attributes and display them with maturity
amount.
Script
class FixedDeposit
{
int principle,rate,year;
void setAttr(int p, int r, int n)
{
principle = p;rate = r;year = n;
}
int compint()
{
return (principle*(1+rate/100)^year);
}
void display()
{
System.out.println("\n Principle: " +principle);
System.out.println("\n rate: " +rate);
System.out.println("\n year: " +year);
}
}
class FixedDepositDemo
{
public static void main(String args[])
{
FixedDeposit f1;
f1= new FixedDeposit();
f1.setAttr(1500,10,2);
f1.setAttr(1000,9,3);
HR ZONE Computer Classes TM 36
System.out.println("\n Principle Ammount" + f1.principle + "Rate" +
f1.rate + "Year: " + f1.year +"Compound Amount is"+ f1.compint());
System.out.println("\n Principle Ammount" + f2.principle + "Rate" +
f2.rate + "Year: " + f2.year +"Compound Amount is"+ f2.compint());
}
}
Output
Script
class FixedDeposit
{
int principle,rate,year;
void setAttr(int p, int r, int n)
{
principle = p;rate = r;year = n;
}
int compint()
{
return (principle*(1+rate/100)^year);
}
void display()
{
System.out.println("\n Principle: " +principle);
System.out.println("\n rate: " +rate);
System.out.println("\n year: " +year);
}
}
class FixedDepositDemo
{
public static void main(String args[])
{
FixedDeposit f1;
f1= new FixedDeposit();
f1.setAttr(1500,10,2);
f1.setAttr(1000,9,3);
Output
Script
import java.io.*;
class FixedDepositPrivate
{
private double princi_amt,intr,dur,comp_intr;
public double calculateCompoundInterest()
{
comp_intr=(princi_amt)*(Math.pow(1+(intr/100),dur));
return(comp_intr);
}
public void get() throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter principle amount");
princi_amt=Double.parseDouble(dis.readLine());
System.out.println("Enter Interest rate");
intr=Double.parseDouble(dis.readLine());
System.out.println("Enter Duration");
dur=Double.parseDouble(dis.readLine());
}
public void display()
{
System.out.println("Principle Amount:" +princi_amt);
System.out.println("Interest rate is:" +intr);
System.out.println("Duration is:" +dur);
System.out.println("Compound interest is:" +comp_intr);
}
}
class FixedDepositC
{
public static void main(String[] args)throws Exception
{
FixedDepositPrivate depo1= new FixedDepositPrivate();
depo1.get();
depo1.calculateCompoundInterest();
depo1.display();
}
}
Script
import java.io.*;
class FixedDepositPrivate
{
private double princi_amt,intr,dur,comp_intr,totdeposit;
public double calculateCompoundInterest()
{
comp_intr=(princi_amt)*(Math.pow(1+(intr/100),dur));
return(comp_intr);
}
public void get() throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter principle amount");
princi_amt=Double.parseDouble(dis.readLine());
System.out.println("Enter Interest rate");
intr=Double.parseDouble(dis.readLine());
System.out.println("Enter Duration");
dur=Double.parseDouble(dis.readLine());
}
public void calculateTotalDeposit()
{
totdeposit=princi_amt+comp_intr;
}
public void displayTotalDeposit()
{
System.out.println("Total deposit is:"+ totdeposit);
}
public void display()
{
System.out.println("Principle Amount:" +princi_amt);
System.out.println("Interest rate is:" +intr);
System.out.println("Duration is:" +dur);
System.out.println("Compound interest is:" +comp_intr);
}
}
HR ZONE Computer Classes TM 42
class FixedDepositD
{
public static void main(String[] args)throws Exception
{
FixedDepositPrivate depo1= new FixedDepositPrivate();
depo1.get();
depo1.calculateCompoundInterest();
depo1.display();
}
}
Output
Script
import java.io.*;
class Rectangle
{
int length,breadth;
}
Output
20
15
10
class testarray
{
public static void main(String[] s)
{
int marks[];
marks=new int[7];
Output
class testarray
{
public static void main(String[] s)
{
int marks[];
marks=new int[3];
Array marks 1: 0 0 0
Array marks 2: 0 0 0
Array marks 3: 0 0 0
Array marks 4: 50 60 70
Array marks 5: 70 80 90
class ArrayAvg
{
avg = sum/10;
System.out.println("The average of above number is"+avg);
}
}
Output
list of number is
10.5
20.6
30.8
15.5
17.3
25.5
27.2
20.0
30.0
18.5
The average of above number is21.59
class ArrayClassSortFill
{
public static void main(String[] s)
{
double list[]= {6.4,8,7.8,9.8,9.5,6,7,8,8.5,5.9};
int index;
java.util.Arrays.fill(list,7);
System.out.println("\n Fill whole array");
display(list);
java.util.Arrays.fill(list,2,6,5);
System.out.println("\n fill partial array: list[2] to list[5]:");
display(list);
}
Initial Elements:
6.4 8.0 7.8 9.8 9.5 6.0 7.0 8.0 8.5 5.9
7.0 7.0 5.0 5.0 5.0 5.0 7.0 7.0 7.0 7.0
class LinearSrch
{
public static void main(String[] s)
{
double list[]={6,5,7,9,9.5,6.5,7.5,8};
int index;
index=search(list,8);
if(index<0)
System.out.println("\nElement 8 is not found in array");
else
System.out.println("\nElement 8 is found at position" +index);
index=search(list,5.5);
if(index<0)
System.out.println("\nElement 5.5 is not found in array");
else
System.out.println("\nElement 5.5 is found at position" +index);
}
Output
class Array2D
{
public static void main(String[] s)
{
int marks1[][];
marks1=new int[5][3];
int marks2[][]=new int[5][3];
int marks3[][]=new int[5][3];
int
marks4[][]={{50,60,70},{35,30,50},{70,75,80},{80,85,90},{50,50,55}};
int
marks5[][]={{50,60,70},{35,30,50},{70,75,80},{80,85,90},{50,50,55}};
class Array2Dchar
{
public static void main(String[] s)
{
char
names[][]={{'j','a','v','a'},{'C'},{'C','+','+'},{'B','a','s','i','c'},{'P','a','s','c','a','T'}};
System.out.println("Number o elements in 2-D
array:"+names.length+"\n");
class Array2Dbyte
{
public static void main(String[] s)
{
byte names[]
[]={{'j','a','v','a'},{67},{'C','+','+'},{'B','a','s','i','c'},{'P','a','s','c','a','T'}};
System.out.print("Five names stored in 2-d Array of bytes:\n");
display(names,5);
}
static void display(byte arr[][],int rows)
{
for(int i=0;i<rows;i++)
{
for(int j=0;j<arr[i].length;j++)
{
System.out.print(arr[i][j]+"\t");
}
System.out.println();
}
}
}
Output
class StringComparison
{
public static void main(String[] s)
{
String str1="India is great";
String str2="INDIA IS GREAT";
Output
int max=tem[0];
for(int j=1; j<=12;j++)
{
if(max<tem[j])
max=tem[j];
}
System.out.println("Maximum temperature is: "+max);
int min=tem[0];
for(int i=1; i<=12;i++)
{
if(min>tem[i])
min=tem[i];
}
System.out.println("Lowest temperature is: "+min);
}
}
Output
class PalindromeTest
{
public static void main (String[] args)
{
StringBuffer s1= new StringBuffer("madam");
StringBuffer s2= new StringBuffer(s1);
s1.reverse();
System.out.println("Given String is:"+s2);
System.out.println("Given String is:"+s1);
if(String.valueOf(s1).compareTo(String.valueOf(s2))==0)
System.out.println("Palindrome");
else
System.out.println("Not Palindrome");
}
}
Output
Palindrome
Script
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample
{
public static void main(String[] args)
{
Date today=new Date();
Calendar c=Calendar.getInstance();
SimpleDateFormat dateFormat= new SimpleDateFormat("EEEEE");
String dayOfWeek=dateFormat.format(c.getTime());
System.out.println("Today's day is:"+ dayOfWeek);
}
}
Output
Script
import java.util.*;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
return f.format(d);
Output
Script
class RuntimeErrorDemo
{
public static void main(String args[])
{
String citylist[]={"Ahemedabad","Baroda","Rajkot","Surat"};
System.out.println(citylist[5]);
Output
Script
class RuntimeErrorDemo2
{
public static void main(String args[])
{
int numerator = 15;
int denominator = 0;
int answer;
answer = numerator/denominator;
}
}
Output
at RuntimeErrorDemo2.main(RuntimeErrorDemo2.java:11
Script
class TryBlockdemo
{
public static void main(String args[])
{
String citylist[]={"Ahemedabad","Baroda","Rajkot","Surat"};
try
{
System.out.println("Statement to be executed before displaying the
fifth element");
System.out.println(citylist[5]);
Output
at TryBlockdemo.main(TryBlockdemo.java:13)
Script
class TryCatchdemo
{
public static void main(String args[])
{
String citylist[]={"Ahemedabad","Baroda","Rajkot","Surat"};
try
{
System.out.println("Statement to be executed before displaying the
fifth element");
System.out.println(citylist[5]);
Output
Script
class FinallyDemo
{
public static void main(String args[])
{
String citylist[]={"Ahemedabad","Baroda","Rajkot","Surat"};
int numerator = 15, denominator = 0, answer;
System.out.println("Statement to be executed before try block");
try
{
System.out.println("Begininig of try block...");
System.out.println(citylist[5]);
answer = numerator/denominator;
System.out.println("End of try block");
}
finally
{
System.out.println("this part of code will always get executed");
}
System.out.println("End of program...");
}
}
Output
at FinallyDemo.main(FinallyDemo.java:13)
Script
class ThrowDemo
{
public static void main(String args[])
{
try
{
System.out.println("Before throwing an exception object....");
throw myobject;
}
catch(Exception eobj)
{
System.out.println("Exception caught: "+eobj);
}
}
}
Output
Script
class ThrowDemoB
try
performDivision();
catch(ArithmeticException eobj)
int ans;
ans = 15/0;
Output
Script
import java.util.Scanner;
class InvalidMarksException extends java.lang.Exception
{
public InvalidMarksException(String message)
{
super(message);
}
}
class CustomExceptionDemo2
{
public static void main(String args[])
{
Scanner kbinput=new Scanner(System.in);
int marks;
boolean continueLoop = true;
do
{
System.out.println("Enter the marks: ");
marks = kbinput.nextInt();
System.out.println("You entered"+ marks);
try
{
if(marks<0||marks>100)
{
throw new InvalidMarksException ("Wrong
marks...");
}
else{
System.out.println("Marks are valid");
}
continueLoop = false;
}
catch(InvalidMarksException eobj)
{
System.out.println("Exception Caught: "+ eobj);
HR ZONE Computer Classes TM 71
}
}
while(continueLoop);
}
}
Output
Error: Main method not found in class InvalidMarksException, please define the main
method as:
Script
import java.io.*;
class ArrayDemo1
{
static int arr[]=new int[10];
public static void add()throws IOException
{
int p,n;
DataInputStream dis= new DataInputStream(System.in);
System.out.println("Enter Array element");
n=Integer.parseInt(dis.readLine());
System.out.println("At which index you want to insert this element");
p=Integer.parseInt(dis.readLine());
try
{
arr[p]=n;
System.out.println("Element inserted");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception occurs");
System.out.println("provied index is out of array bounds");
}
}
Script
import java.io.*;
class ArrayDemo2
{
static int arr[]=new int[10];
public static void add()throws IOException,ArrayIndexOutOfBoundsException
{
int p,n;
DataInputStream dis= new DataInputStream(System.in);
System.out.println("Enter Array element");
n=Integer.parseInt(dis.readLine());
System.out.println("At which index you want to insert this element");
p=Integer.parseInt(dis.readLine());
arr[p]=n;
System.out.println("Element inserted");
}
Output
Script
import java.io.*;
class SqrtException
{
public static void main(String ar[])throws IOException
{
double n,r;
DataInputStream dis= new DataInputStream(System.in);
System.out.println("Enter Value to obtain aquare root");
n=Double.parseDouble(dis.readLine());
try
{
if(n<0)
{
throw new ArithmeticException();
}
r=Math.sqrt(n);
System.out.println("Square root is :"+ r);
}
catch(ArithmeticException e)
{
System.out.println("Exception occurs");
System.out.println("Cannot find the square of negative value ");
}
}
}
Output
625
Script
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.*;
class InvalidBirthDateException extends Exception
{
public InvalidBirthDateException(String m)
{
System.out.println(m);
System.out.println("You entered an invalid date");
}
}
class BirthDateDemo
{
public static void main(String[] args) throws IOException,ParseException
{
String s1,s2;
DataInputStream dis= new DataInputStream(System.in);
System.out.println("Enter your birth date in DD.MM.YYYY format");
s1=dis.readLine();
SimpleDateFormat sdf1=new SimpleDateFormat("dd.MM.yyyy");
Date date1=sdf1.parse(s1);
SimpleDateFormat df=new SimpleDateFormat("dd.MM.yyyy");
Date date=new Date();
s2=df.format(date);
Date date2=df.parse(s2);
try
{
if(date1.after(date2) || date1.equals(date2))
{
throw new InvalidBirthDateException("Exception occurs");
}
else
{
System.out.println("This is a valid date,no exception");
HR ZONE Computer Classes TM 77
}
}
catch(InvalidBirthDateException e)
{}
}
}
Output
10-09-2004
at java.base/java.text.DateFormat.parse(DateFormat.java:399)
at BirthDateDemo.main(InvalidBirthDateException.java:23)
Script
import java.io.*;
class InvalidTransaction extends Exception
{
public InvalidTransaction(String m)
{
class BankTransaction
{
public static void main(String ar[]) throws IOException
{
int withdrawAmount,balanceAmount;
DataInputStream dis= new DataInputStream(System.in);
System.out.println("Enter balance amount");
balanceAmount=Integer.parseInt(dis.readLine());
System.out.println("Enter withdrawal amount");
withdrawAmount=Integer.parseInt(dis.readLine());
try
{
if(withdrawAmount>balanceAmount)
{
throw new InvalidTransaction("No enough balance
amount");
}
else
{
System.out.println("Withdrawal is possible");
}
}
catch (InvalidTransaction e)
{
System.out.println(e);
HR ZONE Computer Classes TM 79
}
}
}
Output
50000
20000
Withdrawal is possible
Script
import java.io.*;
class FileWriterDemo
{
public static void main(String args[])
{
FileReader frobject=null;
try
{
frobject=new FileReader("Charfile.txt");
int i;
char ch;
while ((i=frobject.read())!=-1)
{
ch=(char) i;
System.out.print(ch);
}
}
catch(Exception eobj)
{
System.out.println(eobj);
}
finally
{
try
{
frobject.close();
}
catch(Exception eobj)
{
System.out.println(eobj);
}
Output
Script
import java.io.*;
class FileWriterDemo
{
public static void main(String args[])
{
FileReader frobject=null;
try
{
frobject=new FileReader("Charfile1.txt");
int i;
char ch;
while ((i=frobject.read())!=-1)
{
ch=(char) i;
System.out.print(ch);
}
}
catch(Exception eobj)
{
System.out.println(eobj);
}
finally
{
try
{
frobject.close();
}
catch(Exception eobj)
{
System.out.println(eobj);
}
}
}
}
Output
Script
import java.io.*;
class BinaryFileDemo
{
public static void main (String args[])
{
FileOutputStream outobject= null;
FileInputStream inobject= null;
try
{
outobject= new FileOutputStream("Binaryfile.dat");
outobject.write(citiesarray);
outobject.close();
int i;
while((i=inobject.read())!=-1)
{
System.out.print((char)i);
}
inobject.close();
}
catch(Exception eobj)
{
System.out.println(eobj);
}
}
}
Script
import java.io.*;
import java.util.*;
class ScannerInputDemo
{
public static void main(String args[])
{
Scanner kbinput=null;
int number1;
int number2;
int sum=0;
try{
kbinput = new Scanner(System.in);
System.out.println("Enter The first number: ");
number1=kbinput.nextInt();
System.out.println("Enter The Second number: ");
number2=kbinput.nextInt();
sum= number1+number2;
System.out.println("Sum is:"+sum);
}
catch(Exception eobj)
{
System.out.println(eobj);
}
finally {
try
{
kbinput.close();
}
catch(Exception eobj)
{
System.out.println(eobj);
}
}
}
}
HR ZONE Computer Classes TM 86
Output
Enter The first number:
21
16
Sum is:37
Script
import java.io.*;
import java.util.*;
class ScannerFileDemo
{
public static void main (String args[])
{
Scanner fileinput=null;
int rollno, mark1,mark2,mark3,total;
String name=null;
File fobject;
try
{
fobject=new File("Studets.dat");
fileinput=new Scanner(fobject);
while(fileinput.hasNext())
{
rollno=fileinput.nextInt();
name=fileinput.next();
mark1=fileinput.nextInt();
mark2=fileinput.nextInt();
mark3=fileinput.nextInt();
total=mark1+mark2+mark3;
System.out.println("Total marks of rollno "+ rollno
+","+name+ "are :"+ total);
}
fileinput.close();
}
catch(Exception eobj)
{
HR ZONE Computer Classes TM 88
System.out.println(eobj);
}
}
}
Output
java.io.FileNotFoundException: Studets.dat (The system cannot find the file specified)
Script
import java.io.Console;
import java.util.Arrays;
public class ConsoleDemo {
public static void main(String[] args)
{
Console console=System.console();
String username=console.readLine("Username: ");
char[] password= console.readPassword("Password");
if(username.equals("admin")&&
String.valueOf(password).equals("secret"))
{
console.printf("Welcome to java application \n");
}
else {
console.printf("Invalid username or password. \n");
}
}
}
Output
at ConsoleDemo.main(ConsoleDemo.java:7)