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

Java Practicals 1

The document provides examples of Java programs to demonstrate basic programming concepts like: - Printing output - Taking user input - Performing arithmetic operations - Using if/else conditional statements - Calculating things like call costs, interest, and determining even/odd numbers It includes the code examples along with the corresponding output for each program to showcase how to write, compile, and run simple Java programs.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
106 views

Java Practicals 1

The document provides examples of Java programs to demonstrate basic programming concepts like: - Printing output - Taking user input - Performing arithmetic operations - Using if/else conditional statements - Calculating things like call costs, interest, and determining even/odd numbers It includes the code examples along with the corresponding output for each program to showcase how to write, compile, and run simple Java programs.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Std 12th Java Practical Notes

How to create Java Programs.

• Application - Programming - SciTE Text Editor.


• Type the Java Program.
• Save file with extension ".java". Remember your file name and main class name must be same.
Ex. like in our first program our class name is "welcome" so our file name should be "welcome.java".
• Tools - Compile (Exit code: 0). (To compile the program)
• Tools – Go. (To execute the program)
• class visibility is always be public in Ubuntu Operating system so there is no need to write
public keyword with class name.

1.(a) Display Welcome Message.


public class welcome
{
public static void main(String[] s)
{
System.out.println("Hello, world");
System.out.println("This is Core Java");
}
}

Output:
Hello world
This is Core Java

1.(b) Display User name, class and school name.


class username
{
public static void main(String[] args)
{
int c=12;
String n="Sonu Shah";
String s="RHHS";
System.out.println("My name is "+n);
System.out.println("I study in "+c+" class");
System.out.println("My school name is "+s);

}
}

Output:
My name is Sonu Shah
I study in 12 class
My school name is RHHS

1 RSCD
Std 12th Java Practical Notes

2. Display all arithmetic operators.


class ao
{
public static void main (String[] args)
{
short x = 6;
int y = 4;
float a = 12.5f;
float b = 7.2f;

System.out.println ("x is " + x + ", y is " + y);


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));
System.out.println ("x % y = " + (x % y));
x = -6;
System.out.println ("x % y = " + (x % y));
y=-4;
System.out.println ("x % y = " + (x % y));
x=6; y=-4;
System.out.println ("x % y = " + (x % y));

System.out.println ("a is " + a + ", b is " + b);


System.out.println ("a / b = " + (a / b));
System.out.println ("a / x = " + (a / x));
System.out.println ("a % x = " + (a*x));
System.out.println ("a % b = " + (a%b));
}
}

Output:
x is 6, y is 4 x%y=2
x + y = 10 a is 12.5, b is 7.2
x-y=2 a / b = 1.7361112
x/y=1 a / x = 2.0833333
x%y=2 a % x = 0.5
x % y = -2 a % b = 5.3
x % y = -2

2 RSCD
Std 12th Java Practical Notes

3. Display Block.
class block
{
public static void main (String[] args)
{
int x = 10;
blk1:
{
int y = 50;
System.out.println("inside the block1:");
System.out.println("x: " + x);
System.out.println("y: " + y);
}
blk2:
{
int y = 20;
//int x = 30; // conflict with x in main
System.out.println("inside the block2:");
System.out.println("x: " + x);
System.out.println("y: " + y); }
}
System.out.println("outside the block: x is " + x);
}
}
Output:
inside the block1: x: 10
x: 10 y: 20
y: 50 outside the block: x is 10
inside the block2:

4. Calculate The cost of phone call and balance.


public class CallCost
{
public static void main(String[] args)
{
double balance=170;
double rate=1.02;
double duration=37;
double cost;
cost = duration * rate;
balance = balance - cost;
System.out.print("Call Duration: ");
System.out.print(duration);
System.out.println(" Seconds");
System.out.println("Balance: " + balance + "Rupees ");
}
}

Output:
Call Duration: 37.0 Seconds
Balance: 132.26Rupees

3 RSCD
Std 12th Java Practical Notes

5. Calculate Simple Interest.


public class interest
{
public static void main(String[] args)
{

double principal=17000;
double rate=9.50;
double duration=3;
double maturity;
double interest;
interest = principal * duration * rate / 100;
maturity = principal + interest;

System.out.println("Principal amount: " + principal + " Rupees");


System.out.println("Deposit for duration of " + duration + " years");
System.out.println("Interest Rate: " + rate + " %");
System.out.println("Interest amount: " + interest + " Rupees");
System.out.println("Maturity amount: " + maturity + " Rupees");
}
}

Output:
Principal amount: 17000.0 Rupees
Deposit for duration of 3.0 years
Interest Rate: 9.5 %
Interest amount: 4845.0 Rupees
Maturity amount: 21845.0 Rupees

6(a). Calculate Bigger value between 2 numbers.


class big2
{
public static void main (String[] args)
{
int a=20;
int b=25;
System.out.println(“Value of A is "+a);
System.out.println(“Value of B is "+b);
if (a>b)
{
System.out.println("A is bigger");
}
else
{
System.out.println("B is bigger");
}
}
}
Output:
Value of A is 20
Value of B is 25
B is bigger

4 RSCD
Std 12th Java Practical Notes

6(b). Calculate Bigger value between 3 numbers.


class big3
{
public static void main (String[] args)
{
int a=100;
int b=150;
int c=200;
System.out.println(“Value of A is "+a);
System.out.println(“Value of B is "+b);
System.out.println(“Value of C is "+c);
if (a>b && a>c)
{
System.out.println("A is bigger");
}
else if(b>c)
{
System.out.println("B is biger");
}
else
{
System.out.println("C is bigger");
}

}
}

Output:
Value of A is 100
Value of B is 150
Value of C is 200
C is bigger

7(a). Calculate Even - Odd numbers.


class evenodd
{
public static void main(String[] args)
{
int n=12;
if(n%2==0)
{
System.out.println(n+" Is an even number");
}
else
{
System.out.println(n+" Is an odd number");
}
}
}
Output:
12 Is an even number.

5 RSCD
Std 12th Java Practical Notes

7(b). Calculate Leap Year.


class ly
{
public static void main(String[] args)
{
int n=2014;
if(n%4==0)
{
System.out.println(n +" is a leap year");
}
else
{
System.out.println(n + " is not a leap year");
}
}
}

Output:
2014 is not a leap year

7(c). Voting Eligibility using Tenary operators.


class vote
{
public static void main(String[] args)
{
int a=15;
String b;
b=(a>=18 ? "Eligible" : "Not eligible");
System.out.println(“You are ”+b+” for vote”);
}
}
Output:
You are Not eligible for vote

8(a). Print 1 to 10 counting (for loop).


class count
{
public static void main (String[] s)
{
System.out.println("Counting is:");
for (int i =1; i <=10; i++)
{
System.out.println (i);
}
}
}
Output:
1 6
2 7
3 8
4 9
5 10

6 RSCD
Std 12th Java Practical Notes

8(b). Print 1 to 10 counting (do while loop).


class count
{
public static void main(String[] args)

{
int i=1;
do
{
System.out.println(i++);
}
while (i<=10);
}
}

Output:
1 6
2 7
3 8
4 9
5 10

8(c). Print 1 to 10 counting (while loop).

class while1
{
public static void main(String[] args)

{
int i=1;
while (i<=10)
{
System.out.println(i++);
}

}
}
Output:
1 6
2 7
3 8
4 9
5 10

7 RSCD
Std 12th Java Practical Notes

9(a). Print 2's table.

class table2
{
public static void main (String[] s)
{
System.out.println("Table is:");
for (int i =2; i <=20; i=i+2)
{
System.out.println (i);
}
}
}

Output:
2 12
4 14
6 16
8 18
10 20

9(b) Print Odd numbers from 1 to 9.


class odd
{
public static void main(String[] args)
{
System.out.println("Odd table is ");
for (int i=1;i<=10;i++)
{
System.out.println(i);

i=i+1;
}

} }

Output:

Odd table is
1 7
3 9
5

8 RSCD
Std 12th Java Practical Notes

10.1 Nested Loop (Stat peramid)


class star
{
public static void main(String[] args)
{
for (int i=0;i<=4;i++)
{
for (int j=1;j<=i;j++)
{
System.out.print("* "); // “j” print 2nd pattern and “i” print 3rd pattern.
}
System.out.println();
}
}
}

Output
(1) (2) (3)
* 1 1
* * 1 2 2 2
* * * 1 2 3 3 3 3
* * * * 1 2 3 4 4 4 4 4

10.2 Nested Loop (Reverse peramid)

class star1
{
public static void main(String[] args)
{
for (int i=4;i>=1;i--)
{
for (int j=1;j<=i;j++)
{
System.out.print(j+" "); \\ “i” prints 2nd pattern.
}
System.out.println();
}
}
}

Output
(1) (2)
1 2 3 4 4 4 4 4
1 2 3 3 3 3
1 2 2 2
1 1

9 RSCD
Std 12th Java Practical Notes

10.3 Nested Loop


{
public static void main(String[] s)
{
for (int i=1;i<=6;i++)
{
for (int j=6;j>=i;j--)
{
System.out.print(j+" ");
}
System.out.println();
}
}
}

Output
6 5 4 3 2 1
6 5 4 3 2
6 5 4 3
6 5 4
6 5
6

10.4 Nested Loop


{
public static void main(String[] s)
{
int k=1;
for (int i=1;i<=4;i++)
{
for (int j=1;j<=i;j++)
{
System.out.print(k+" ");
k++;
}
System.out.println();
}
}
}

Output
1
2 3
4 5 6
7 8 9 10

10 RSCD
Std 12th Java Practical Notes

11.Switch Case (a).

class week
{
public static void main(String[] args)
{
int a=3;
switch(a)
{
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
case 4:
System.out.println("Wednesday");
break;
case 5:
System.out.println("Thursday");
break;
case 6:
System.out.println("Friday");
break;
case 7:
System.out.println("Saturday");
break;
default:
System.out.println("Invalid Number");
}

}
}

Output
Tuesday

11 RSCD
Std 12th Java Practical Notes

11.Switch Case (b).

class sw1
{
public static void main(String[] s)
{
char ch='B';
switch (ch)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
System.out.println(ch+" is an Vowel");
break;
default:
System.out.println(ch+" is a Constant");
break;
}
}
}

Output
B is a Constant

12 RSCD
Std 12th Java Practical Notes

12. (a) Using Constructors Print the sutdents id and name. (save your file with the name of main class)
class student
{
int id;
String n;
student(int i,String name)
{
id=i;
n=name;
}
void display()
{
System.out.println("Your id is "+id);
System.out.println("Your name is "+n);
System.out.println("------------");
}
}
class cons // main class
{
public static void main(String[] args)
{

student s1=new student(5,"Chirag");


student s2=new student(7,"Rahul");
s1.display();
s2.display();
}
}

Output: -
Your id is 5
Your name is Chirag
-------------------------
Your id is 7
Your name is Rahul

13 RSCD
Std 12th Java Practical Notes

12 (b) Use of default and parameters constructor. (save your file with the name of main class)
class name
{
name() // default constructor
{
System.out.println("Default Constructor");
System.out.println("--------------------");
}
name(int n,char l) // parameterized constructor
{
System.out.println("Roll Number= "+n);
System.out.println("First Letter of name= "+l);
System.out.println("--------------------");
}
name(int n,String w,double f) //parameterized constructor
{
System.out.println("Roll Number= "+n);
System.out.println("Your name= "+w);
System.out.println("Your Height= "+f);
}
}
class con // main class
{
public static void main(String[] args)
{
name n1=new name();
name n2=new name(5,'S');
name n3=new name(10,"Student",4.8);
}
}

Output:-
Default Constructure
--------------------
Roll Number= 5
First Letter of name= S
--------------------
Roll Number= 10
Your name= Student
Your Height= 4.8

14 RSCD
Std 12th Java Practical Notes

12. (c) Using Constructors find the length , width and total no. of windows of room.
(save your file with the name of main class)
class Room
{
float length, width, height;
byte nWindows;
static int totWindows;

Room (float l, float w, float h, byte n) // define constructor


{
length = l; width = w; height = h;
nWindows = n; totWindows+=n;
}

Room (float l, float w) // define constructor


{
length = l; width = w; height = 10;
nWindows = 1; totWindows++;
}

double area ( ) // user define method


{
return (length * width * height);
}

void display( )
{
System.out.println ("\nLength: " + length + "\nWidth: " + width);
System.out.println ("Height: " + height);
System.out.println ( "Windows: " + nWindows);
}
}
class RoomCon //Main class
{
public static void main (String args[])
{
Room r1 = new Room(16.7f, 12.5f);
Room r2 = new Room(20, 14.3f, 12, (byte)2);
r1.display(); r2.display();
System.out.println(“\nArea of first room is :” +r1.area());
System.out.println(“\nArea of second room is :” +r2.area());
System.out.println ("\nTotal number of Windows: " + Room.totWindows);
} }
Output:
Length: 16.7 Length: 20.0
Width: 12.5 Width: 14.3
Height: 10.0 Height: 12.0
Windows: 1 Windows: 2
Area of first room is :2087.5 Total number of Windows: 3
Area of second room is : 3432

15 RSCD
Std 12th Java Practical Notes

13. (a) Using Inheritance print the value of i, j and k. (save your file with the name of main
class)

class a //parent class


{
int i; //class variable
a(int x) //consturctor with one argument
{
i=x;
}
}
class b extends a //sub class of a (creation of inheritance)
{
int j;
b(int x,int y) //constructor with two arguments
{
super(x); // super keyword is used to call x variable from parent class
j=y;
}
}
class c extends b //child class of a & sub class of b
{
int k;
c(int x, int y, int z) //constructor with three arguments
{
super(x,y); //call x & y variables from parent class
k=z;
}

void display() // user defined method with no return & no argument


{
System.out.println("Value of i is "+i);
System.out.println("Value of j is "+j);
System.out.println("Value of k is " +k);
System.out.println("---------------------------");
}
}
class inherit // main class
{
public static void main(String[]s)
{
c obj1=new c(10,12,13);
obj1.display();
c obj2=new c(20,22,26);
obj2.display();
}
}

16 RSCD
Std 12th Java Practical Notes

Output:-
Value of i is 10
Value of j is 12
Value of k is 13
---------------------------
Value of i is 20
Value of j is 22
Value of k is 26
---------------------------

13. (b) Using Inheritance find the ara of a room with height and without height.
(save your file with the name of main class)

class room // parent class//


{
int l,w;
room(int x,int y) //constructor of room class//
{
l=x; w=y;
}
int a()
{
return (l*w);
}
}
class bed extends room
{
int h;
bed(int x,int y,int z)// constructor of bed class//
{
super(x,y); // To call super class variable.
h=z;
}

int b()
{
return (l*w*h);
}
}
class house // Main class
{

public static void main(String[] args)


{
int i,j;
bed b1=new bed(5,4,3);
i=b1.a();
j=b1.b();
System.out.println("Area of room without height is="+i);
System.out.println("Area of room with height is="+j);
}
}

17 RSCD
Std 12th Java Practical Notes

Output:
Area of room without height is=20
Area of room with height is=60

14 (a). Polymorphism: Operator Overloading (save your file with the name of main class)

class simple
{
static void sum(int a,int b) // define sum() method of simple class
{
int c=a+b;
System.out.println("Ans= " +c);
}
static void sum(char ch,char bh) // define sum() method of simple class
{
System.out.println("Characters are= " +ch+ " " +bh);
}
static void sum(String c) // define sum() method of simple class
{
System.out.println("String is="+c);
}
}
class opov // main class
{
public static void main(String[]s)
{
simple.sum(5,10);
simple.sum('c','s');
simple.sum("Computer Department");
}
}

Output
Ans= 15
Characters are= c s
String is=Computer Department

18 RSCD
Std 12th Java Practical Notes

14 (b).Polymorphism: Method Over loading (print line).(save your file with the name of
main class)

class pl
{
static void printline() // define printline () method of pl class
{
for (int i=0; i<40; i++)
System.out.print('=');
System.out.println();
}

static void printline(int n) // define printline () method of pl class


{
for (int i=0; i<n; i++)
System.out.print('#');
System.out.println();
}

static void printline(char ch, int n)// define printline () method of pl class
{
for (int i=0; i<n; i++)
System.out.print(ch);
System.out.println();
}
}
class poly // main class
{
public static void main(String[] s)
{
pl.printline();
pl.printline(30);
pl.printline('+',20);
}
}

Output:
========================================
##############################
++++++++++++++++++++

19 RSCD
Std 12th Java Practical Notes

15(a). Set the radius of a circle also find area of circle with setter method. (default visibility - public)
save your file with the name of main class.
class circle
{
double r;
static double pi=3.14;
void setatt(double ra) //// setter method due to public visibility
{
r=ra;
}
double area()
{
return (pi*r*r);
}
void display()
{
System.out.println("radius of a cirlce :"+r);
}
}
class circlearea //main class
{
public static void main(String[]args)
{
circle c1=new circle();
c1.setatt(4.3);
c1.display();
System.out.println("Area of a circle is :"+c1.area());
}
}

Output:-
radius of a cirlce :4.3
Area of a circle is :58.0586

20 RSCD
Std 12th Java Practical Notes

15(b). find out circumference of cirlce with private visibility & getter method
save your file with the name of main class.
class circle
{
private float r;
static float pi=3.14f; // class variable

float getR() // getter method due to private visibility


{
return r;
}
circle() { } // default constructor

circle(float ra) // parameterized constructor {


r=ra;
}

double cir()
{
return (2*pi*r*r);
}
}

class circum //main class


{
public static void main(String[]s)
{
circle c1= new circle();
System.out.println("Radius of a circle is :"+c1.getR());
System.out.println("Circumference of cirle is :"+c1.cir());

circle c2= new circle(6);


System.out.println("Radius of a circle is :"+c2.getR());
System.out.println("Circumference of cirle is :"+c2.cir());
}
}

Output: -
Radius of a circle is :0.0
Circumference of cirle is :0.0
Radius of a circle is :6.0
Circumference of cirle is :226.0800018310547

21 RSCD
Std 12th Java Practical Notes

15 (C) Example of Getter and setter method :- save your file with the name of main class.
class person
{
private String name;

public String getName() //getter method


{
return name;
}
public void setName(String newname) // setter method
{
this.name=newname;
}
}
class myclass //main class
{
public static void main(String[]s)
{
person obj=new person();
obj.setName("Sonu Shah");
System.out.println(obj.getName());
}
}
Output: -
Sonu Shah

16. Single Array : Compute average of 10 student's marks.


class array
{
public static void main (String [] s)
{
double marks[] = { 10.5, 20.6, 30.8, 15.5, 17.3, 25.5, 27.2,20, 30, 18.5};
int i;
double sum=0, avg;
System.out.println ("List of marks - ");
for (i=0; i<10; i++)
{
System.out.println (marks[i]);
sum=sum+marks[i];
}
avg=sum/10;
System.out.println ("\nAverage of above marks is "+avg);
}
}
Output:
List of marks is -
10.5 27.2
20.6 20.0
30.8 30.0
15.5 18.5
17.3 Average of above marks is 21.59
25.5

22 RSCD
Std 12th Java Practical Notes

17(a). Creating and initializing 1-D array (Integer type) – number of day in February month.

class Array1
{
public static void main(String[]s)
{
int month_days[]={31,28,30,31,30,31,30,31,30,31,30,31};

System.out.println("Feb has " + month_days[1] + " days.");


}
}

Output:-
Feb has 28 days.

OR
class Ex1Array
{
public static void main(String args[] )
{
int month_days [];
month_days = new int [12];
month_days [0] = 31;
month_days [1] = 28;
month_days [2] = 31;
month_days [3] = 30;
month_days [4] = 31;
month_days [5] = 30;
month_days [6] = 31;
month_days [7] = 31;
month_days [8] = 30;
month_days [9] = 31;
month_days [10] = 30;
month_days [11] = 31;
System.out.println("Feb has " + month_days [1] + " days.");
}
}

Output:-
Feb has 28 days.

23 RSCD
Std 12th Java Practical Notes

17 (b) Creating and initializing 2-D array (Integer type)

class a2d
{
public static void main (String[] s)
{
int m1[] [ ]; m1 = new int [ 5] [3];
int m4[] []= {{50, 60, 70},{35, 30, 50},{70, 75, 80}, {80, 85, 90},{50, 50, 55} };
int [] []m5 = {{50, 60, 70}, {35, 30, 50},{70, 75, 80},{80, 85, 90} };
System.out.print("2-D Array of m1\n:");
display(m1,5,3);
System.out.print("2-D Array of m4:\n");
display(m4,5,3);
System.out.print("2-D Array of m5:\n");
display(m5,4,3);
}
static void display(int arr[][], int rows, int cols)
{
for (int i=0; i<rows; i++)
{
for (int j=0; j<cols; j++)
{
System.out.print (arr[i][j] + "\t"); \\ \t for tab space
}
System.out.println();
}
} }

Output:
2-D Array m1 2-D Array m4 2-D Array m5
0 0 0 50 60 70 50 60 70
0 0 0 35 30 50 35 30 50
0 0 0 70 75 80 70 75 80
0 0 0 80 85 90 80 85 90
0 0 0 50 50 55

17(c). Find the Howmany elements in 2D Array. (Character type)

class Array2D_char
{
public static void main(String[]s)
{
char names[] [] = { {'J','a','v','a'},{'C'},{'c','+','+'},{'b','a','s','i','c'}};
System.out.println("Number of elements in 2D arrray :" +names.length);
}
}

Output:-
Number of elements in 2D arrray :4

24 RSCD
Std 12th Java Practical Notes

17(d). Creating and initializing 2-D array (Character type)


class a2dch
{
public static void main (String [] s)
{
char names[] []= {{'J','a','v','a'},{'C'},{'C', '+', '+'},{'B', 'a', 's', 'i', 'c'},{'P','a','s','c', 'a', 'l'} };
System.out.println("Number of elements in 2-D array: " + names.length + "\n");
display(names,5);
}
static void display(char arr[][], int rows)
{
for (int k=0; k<rows; k++)
{
System.out.print ("Row " + k+ " have " + arr[k].length + " character elements: ");
for (int j=0; j<arr[k].length; j++)
{
System.out.print(arr[k] [j] );
}
System.out.println();
}
}
}
Output:
Number of elements in 2-D array: 5 Row 2 have 3 character elements: C++
Row 0 have 4 character elements: Java Row 3 have 5 character elements: Basic
Row 1 have 1 character elements: C Row 4 have 6 character elements: Pascal

25 RSCD
Std 12th Java Practical Notes

18. Sorting and filling elements in 1D array.

import java.util.*;
class as
{
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 indx;
System.out.println("Initial Elements:");
display(list);

Arrays.sort (list, 3, 9); //sort partial array--9th element is not considered


System.out.println ("\nsort partial array: list[3] to list[8]:");
display(list);

Arrays.sort (list); //sort whole array


System.out.println ("\nsort whole array:");
display(list);

Arrays.fill (list,7); //fill whole array


System.out.println ("\nFill whole array:");
display(list);

Arrays.fill (list, 2, 6, 5); //fill partial array from 2 to 5


System.out.println ("\nFill partial array: list[2] to list[5]");
display(list);
} // end main

static void display(double ary[]) // display method


{
for (int i=0; i<ary.length; i++)
{
System.out.print (ary[i] + "\t");
}
System.out.println();
} }
Output:
Initial Elements:
6.4 8.0 7.8 9.8 9.5 6.0 7.0 8.0 8.5 5.9
sort partial array: list[3] to list[8]:
6.4 8.0 7.8 6.0 7.0 8.0 8.5 9.5 9.8 5.9
Sort whole array:
5.9 6.0 6.4 7.0 7.8 8.0 8.0 8.5 9.5 9.8
Fill whole array:
7.0 7.0 7.0 7.0 7.0 7.0 7.0 7.0 7.0 7.0
Fill partial array: list[2] to list[5]
7.0 7.0 5.0 5.0 5.0 5.0 7.0 7.0 7.0 7.0

26 RSCD
Std 12th Java Practical Notes

19(a). String Function

import java.io.*;
class sf
{
public static void main(String args[])
{
String s = "COre Java ";
String s1 = "CORE";
String s2 = "JAVA";
System.out.println("Upper Case- "+s.toUpperCase());
System.out.println("Lower Case- "+s.toLowerCase());
System.out.println("As it is - "+s);
System.out.println("The Starts With() and ends With() METHOD CALLS HERE");
System.out.println("Start result- "+s.startsWith("CO"));
System.out.println("End result- "+s.endsWith("VA"));
String s3=s1.concat(s2);
System.out.println(s3);
System.out.println(s1.compareTo(s2));
System.out.println(s1==s2);
}
}
Output
Upper Case- CORE JAVA
Lower Case- core
As it is- COre Java
The Starts With() and ends With() METHOD CALLS HERE
Start result- true
End result- false
COREJAVA
-7
false

19(b). String Function

class name
{
public static void main(String[] args)
{
String n="Sonu Patel";
String n1=”sonu patel”;
System.out.println("Name is "+n);
System.out.println("Length of name is "+n.length());
System.out.println("Capital letters "+n.toUpperCase());
System.out.println("Small letters "+n.toLowerCase());
System.out.println(“n, n1, strings are equal ?” +(n==n1));
System.out.println(“n, n1, strings are equal ?” +(n.equals(n1)));
System.out.println(“n, n1, strings are equal ?” +(n.compareTo(n1)));
System.out.println(“n, n1, strings are equal ?” +(n.equalsIgnoreCase(n1)));
}
}

27 RSCD
Std 12th Java Practical Notes

Output
Name is Sonu Patel
Length of name is 10
Capital letters SONU PATEL
Small letters sonu patel
n, n1, strings are equal ?false
n, n1, strings are equal ?false
n, n1, strings are equal ?-32
n, n1, strings are equal ?true

20. Date function:-

import java.util.Date;
class date1
{
public static void main(String[] args)
{
Date d1=new Date(); //current date.
System.out.println("current date and time is="+d1);
System.out.println("Elapsed time since Jan 1, 1970 is \n\t "+d1.getTime()+"
milliseconds");
}
}
Output
current date and time is=Sat Oct 03 11:40:03 IST 2015
Elapsed time since Jan 1, 1970 is
1443852603882 milliseconds

21. Calendar functions

import java.util.*;
class cal1
{
public static void main(String[] args)
{
System.out.println("Current Date and time is = "+new Date());
Calendar c1=new GregorianCalendar(2013,10,27,18,12);
System.out.println("Year="+c1.get(Calendar.YEAR));
System.out.println("Month="+c1.get(Calendar.MONTH));
System.out.println("Day="+c1.get(Calendar.DATE));
System.out.println("Hour (12 hours)="+c1.get(Calendar.HOUR));
System.out.println("Hour (24 hours)="+c1.get(Calendar.HOUR_OF_DAY));
System.out.println("Minute="+c1.get(Calendar.MINUTE));
}
}

Output

Current Date and time is = Mon Oct 18 10:46:36 IST 2010


Year=2013
Month=10
Day=27

28 RSCD
Std 12th Java Practical Notes

Hour (12 hours)=6


Hour (24 hours)=18
Minute=12

22(a). Exception Handling : try and catch block.

class Two
{
public static void main(String args[])
{
try
{
int i = 50/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
System.out.println("Rest of the code is Executed.................");
}
}
}

Output:
java.lang.ArithmeticException: / by zero
Rest of the code is Executed.................

22(b). Exception Haindling : try, with multiple catch block.

class Three
{
public static void main(String args[])
{
try
{
int arr[] = new int[5];
arr[5] = 25;
}
catch(ArrayIndexOutOfBoundsException exx)
{
System.out.println("Exception ....."+exx);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Excpetion Occurs.................");
}
} }

Output:
Exception .....java.lang.ArrayIndexOutOfBoundsException: 5

29 RSCD
Std 12th Java Practical Notes

22(c). Exception Handling : try, catch and final block.

class Five
{
public static void main(String args[])
{
try
{
int arr[]=new int[5];
arr[5]=25;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Excpetion Occurs................."+e);
}
finally
{
System.out.println("Finally block executed");
}
System.out.println("Rest of the code will be executed");
}
}

Output:
Finally block executed
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at
.

30 RSCD
Std 12th Java Practical Notes

23. Treminal base Programs (File handling)

To run program. Application – Accessories – Terminal (Note that source file first compile in SciTE and
run in terminal). Command for compile – javac sumS.java
Command for run the program- java sumS
Here javac is the name of the compiler and java is the name of interpreter.

(1) Display Name and Std.

import java.io.*;
public class uname
{
public static void main(String[] args)
{
int c;
String n;
DataInputStream in=new DataInputStream(System.in);
// create an object of DataInputStream
try
{
System.out.println("Enter your name and std-");
n=in.readLine();
c=Integer.parseInt(in.readLine());
// readLine() method is used to reads a single line from keyboard
System.out.println("My name is "+n);
System.out.println("I study in "+c+" class");
}
catch(Exception e) {};

}
}

31 RSCD
Std 12th Java Practical Notes

(2) Sum of 2 numbers


import java.io.*;
class sumS
{
public static void main(String[] args)

{
int a,b,c;

DataInputStream in=new DataInputStream(System.in);


// create an object of DataInputStream
try
{
System.out.println("Enter 2 values-");
// readLine() method is used to reads a single line from keyboard
a=Integer.parseInt(in.readLine());
b=Integer.parseInt(in.readLine());
c=a+b;

System.out.println("Sum is="+c);
}
catch(Exception e){}
}
}

32 RSCD
Std 12th Java Practical Notes

(3)Even – Odd (Ternary Operator)


import java.io.*;
class cond
{
public static void main(String[] args)

{
int a;
String b;
DataInputStream in=new DataInputStream(System.in);
// create an object of DataInputStream
try
{
System.out.println("Enter any value-");
a=Integer.parseInt(in.readLine());
// readLine() method is used to reads a single line from keyboard
b=(a%2==0) ?("Even"):("Odd");
System.out.println("Number " +a+ " is "+b);
}
catch(Exception e){}
}
}
Output
Enter any value-6
Number 6 is Even

4. File handling : File write


import java.io.*;
class fw
{
public static void main(String[] args)
{
FileWriter fo=null;
try
{
fo=new FileWriter("one.txt"); // create an object of FileWriter
// one.txt is a text file to store output.

fo.write("file writing starts....\n"); // write strings to the one.txt file

for(int i=1;i<=10;i++)
fo.write("Line-"+i+"\n");
fo.write("file writing ends\n");
fo.close(); // close the FileWriter
}
catch(Exception e)
{
System.out.println(e);
}
}
}

33 RSCD
Std 12th Java Practical Notes

5. File handling : File read


import java.io.*;
class fr
{
public static void main(String[] args)
{
FileReader fr=null;
try
{
fr=new FileReader("one.txt"); // Create an object of FileReader
int j;
char ch;
while((j=fr.read()) !=-1) // read() is used to read data from one.txt file
{
ch=(char)j; // to change the data type of j (typecasting)
System.out.print(ch);
}
fr.close(); // close the FileWriter
}
catch(Exception e)
{
System.out.println(e);
}
}
}

34 RSCD
Std 12th Java Practical Notes

6. Accpet the characters form user side and find out it is vowel or consonant with the use of
scanner classs.

import java.util.Scanner;
class switch1
{
public static void main (String[]args)
{
char i;
Scanner obj=new Scanner(System.in);
// create an object of scanner class that reads from standard input.
System.out.print("enter start value");
i=obj.next().charAt(0);
// next().charAt(0) is used to read character from console
switch (i)
{
case 'a':
case 'A':
case 'i':
case 'I':
case 'e':
case 'E':
case 'u':
case 'U':
case 'o':
case 'O':
System.out.print(i+"is a vowel");
break;
default:
System.out.print(i+"is a consonant");
break;
}
}
}

35 RSCD
Std 12th Java Practical Notes

7. Program to read username and password with the use of Console class.

// Program to reading passwords


import java.io.Console;
import java.util.Arrays;

public class ConsoleDemo


{

public static void main(String[] args)


{
Console console = System.console(); // create an object of Console class
String username = console.readLine("Username: "); // read the user name from the console
char[] password = console.readPassword("Password: "); // read the password from the console

if (username.equals("admin") && String.valueOf(password).equals("secret"))


// here the user name is admin and password is secret.
{
console.printf("Welcome to Java Application \n");
}
else
{
console.printf("Invalid username or password.\n");
}
}
}

8. Calculate the total sum of two numbers with Scanner class.

import java.io.*;
import java.util.*;
class sc
{
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 : ");
//Read the integer number from console
number1 = kbinput.nextInt();
System.out.println("Enter the second number : ");
//Read the integer number from console
number2 = kbinput.nextInt();
sum = number1 + number2;
System.out.println("Sum is : " + sum);
}

36 RSCD
Std 12th Java Practical Notes

catch(Exception eobj)
{
System.out.println(eobj);
}
}
}

9. Enter the integer, float values and your name from Scanner class.

import java.io.*;
import java.util.*;
class Read_Scanner
{
public static void main( String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a integer no");
int x = sc.nextInt();
System.out.println("Integer is:= " +x);

System.out.println("Enter any real number ");


double d = sc.nextDouble();
System.out.println("Double is := " +d);

System.out.println("Enter your name here");


String str = sc.next();
System.out.println("Your name is:" + str);
}
}

37 RSCD
Std 12th Java Practical Notes

10. Program to calculate the total marks of each student from file “stu” with scanner class.

mport java.io.*;
import java.util.*;
class Read_Scanner
{
public static void main( String args[])
{
Scanner fileinput=null;
int rollno,mark1,mark2,mark3,totalmarks;
String name=null;
try
{
File fobject;
fobject=new File("stu");
fileinput=new Scanner(fobject);

while(fileinput.hasNextInt())
{
rollno=fileinput.nextInt();
name=fileinput.next();
mark1=fileinput.nextInt();
mark2=fileinput.nextInt();
mark3=fileinput.nextInt();
totalmarks=mark1 + mark2 + mark3;
System.out.println("Total marks of Rollno "+rollno+", "+name+"are : "+totalmarks);
}
fileinput.close();
}
catch(Exception eobj)
{
System.out.println(eobj);
}
}
}

38 RSCD

You might also like