100% found this document useful (1 vote)
88 views16 pages

Java Programming Examples for Students

The document contains Java programming examples for students in standard 12, covering topics such as basic Java syntax, control structures, classes, objects, arrays, and exception handling. It includes various programs demonstrating calculations, conditional statements, loops, and data structures. Each example is designed to help students understand fundamental programming concepts in Java.

Uploaded by

chhowalavansh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
88 views16 pages

Java Programming Examples for Students

The document contains Java programming examples for students in standard 12, covering topics such as basic Java syntax, control structures, classes, objects, arrays, and exception handling. It includes various programs demonstrating calculations, conditional statements, loops, and data structures. Each example is designed to help students understand fundamental programming concepts in Java.

Uploaded by

chhowalavansh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Shardayatan (EM)

Subject: Computer Studies


STD: 12

Chapter 7 (Java Basics)


(1) Java Program to compute Call Cost and update prepaid balance amount.
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;

[Link]("duration"+d);
[Link]("balance: "+b);
}
}

(2) Java Program to compute Simple Interest.


public class Interest
{
public static void main(String[] args)
{
double p;
double r;
double n;
double m;
double i;

p=1000;
r=9.50;
n=3;

i=(n*p*r)/100;
m=p+i;

[Link]("interest="+ i);
[Link]("Maturity="+ m);
}
}

STD 12 COMPUTER STUDIES


(3) Java program using Block Statement.
class block
{
public static void main(String[] args)
{
int x=10;

blk1:
{
// int x=50;
int y=50;
[Link]("block1:");
[Link]("x: " + x);
[Link]("y: " + y);
}

blk2:
{
int y=20;
[Link]("block2:");
[Link]("x: " + x);
[Link]("y: " + y);
}
[Link]("outside " + x);
}
}

(4) Write a Java program to display whether Integer is even or odd.


class ifif
{
public static void main(String[] args)
{
int x=2;
if( x % 2 == 0)
{
[Link]("even");
}
else
{
[Link]("odd");
}
}
}

(5) Write a Java program to display whether student is pass or fail.


class IfElse
{
public static void main(String[] args)
{
int marks, pm;
pm = 40;
marks=35;

[Link]("Passing marks=40 ");

STD 12 COMPUTER STUDIES


if (marks >= pm)
{
[Link]("Pass");
}

else
{
[Link]("Fail");
}
}
}

(6) Write a Java Program to display month using Switch statement.


class SwitchDemo
{
public static void main(String[] args) {
int month = 8;

switch (month)
{
case 1: [Link]("January"); break;
case 2: [Link]("February"); break;
case 3: [Link]("March"); break;
case 4: [Link]("April"); break;
case 5: [Link]("May"); break;
case 6: [Link]("June"); break;
case 7: [Link]("July"); break;
case 8: [Link]("August"); break;
case 9: [Link]("September"); break;
case 10: [Link]("October"); break;
case 11: [Link]("November"); break;
case 12: [Link]("December"); break;
default: [Link]("Invalid month.");break;
}
}
}

(7) Write a Java program to display the grade based on percentage of marks using switch
statement.
public class Grade
{
public static void main(String[] args)
{
int choice=0;
int marks=200;

if(marks > 499)


choice=1;
else if(marks>400)
choice=2;
else if(marks>300)
choice=3;

switch(choice)
{
STD 12 COMPUTER STUDIES
case 1:
[Link]("Your Grade is A+");
break;
case 2:
[Link]("Your Grade is B+");
break;
case 3:
[Link]("Your Grade is C+");
break;
default:
[Link]("Your Grade is D");
}
}
}

(9) Write a Java Program using Nested Class.


class Nested
{
public static void main(String[] args) {
int age = 29;

if (age < 13)


{
[Link]("child!");
}

else if (age < 19)


{
[Link]("teenager.");
}

else if (age < 65)


{
[Link]("adult!");
}
else
{
[Link]("senior");
}
}

(10) Write a Java program to display Star pattern.


class Stars
{
public static void main(String[] args)
{
int row, ns;
for (row = 1; row <= 10; row++)
{
for(ns = 1; ns <= row; ns++)
{
[Link]("*");
}
STD 12 COMPUTER STUDIES
[Link]();
}
}
}

(11) Write a program that determines the price of a movie ticket based on customer’s age
and the time of the show (normal or matinee). The normal show and matinee show ticket
price for adult is Rs. 100 and Rs. 50 respectively. Adults are those over 13 years. The
children’s ticket price is Rs. 60 and Rs. 40 for normal show and matinee show respectively.
Declare variables of suitable data types for age and show time, assign the values to these
variables and print age, show time and the ticket price. (Textbook pgNo- 157 Q2)
class Ticket
{
public static void main(String[] args)
{
int age=15;
int ticket=0;
float showtime=10;

if((age>=13))
{
if((showtime>=10))
{
ticket=100;
}
else
{
ticket=50;
}
}

else if((age<13))
{
if((showtime>=10))
{
ticket=60;
}
else
{
ticket=40;
}
}
[Link]("Customer Age:"+ age);
[Link]("Show Time:" + showtime);
[Link]("Ticket:"+ ticket);
}
}

(12) During a sale at a store, a 10% discount is applied to purchases 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. (Textbook pgNo- 156 Q1)
public class valtar

STD 12 COMPUTER STUDIES


{
public static void main(String[] args)
{
double p=5000;
double v;
double r=10;
double np=0;

if(p>=5000)
{
v=p*0.10;
np=p-v;
}
[Link]("purchase " + p);
[Link]("Net Purchase" + np);
}
}

(13) Write a Java program that prints square root of integer numbers starting from 5 till the square
root is at 50 or less. (Textbook pgNo- 157 Q5)
public class SquareRoot
{
public static void main(String[] args)
{
int j=6;

for(int i=5; i< j; i++)


{
if([Link](i) < 50)
{
[Link]("SquareRoot of" + i + "is :" + [Link](i));
}
else
{
break;
}
j++;
}
}
}

Chapter 8 (Classes and Objects in JAVA)


(1) Write a Java Program to display length, width, height, No of windows of Room using two
classes.
class R
{
float length, width, height;
byte nWindows;
void setAttr(float l, float w, float h, byte n)
{

length=l; width=w; height=h;


nWindows=n;
}

STD 12 COMPUTER STUDIES


double area()
{
return(length*width);
}

void display()
{

[Link]("\n Length:" + length);


[Link]("\n Width:" + width);
[Link]("\n Height:" + height);
[Link]("\n Number of Windows:" + nWindows);
}
}

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

R r1;
r1=new R();
R r2=new R();
[Link]();
[Link]();
[Link](18,12.5f, 10,(byte)2);
[Link](14,11,10, (byte)1);
[Link]();
[Link]();

[Link]("\n Area of room with length" + [Link] + "width" + [Link] +


"is"+ [Link]());
[Link]("\n Area of room with length" + [Link] + "width" + [Link] +
"is"+ [Link]());
}
}

(2) Write a Java program to display polymorphism: method printline.


class PrintLine
{
static void printline()
{
for(int i=0; i<40; i++)
[Link]('=');
[Link]();
}
static void printline(int n)
{
for(int i=0; i<n; i++)
[Link]('#');
[Link]();
}
static void printline(char ch, int n)
{
for(int i=0; i<n; i++)
STD 12 COMPUTER STUDIES
[Link](ch);
[Link]();
}
}

public class polyDemo


{
public static void main(String[] s)
{
[Link]();
[Link](30);
[Link]('+', 20);
}
}

(3) Write a Java Program to display Prime Number between 3 to 100.


class Prime
{
static boolean isPrime(int n)
{

int i, last;

if(n<=1) return false;

if(n<4) return true;


last=(int) [Link](n);
i=3;

do
{
if(n%i==0)return false;
i=i+2;
}
while(i<last);
return true;
}
}

class primeClassMethod
{
public static void main(String[] s)
{

int i, n;
[Link]("Prime number between 3 and 100:");

for(n=3; n<100; n=n+2)


{

if([Link](n)) [Link](n);
}
}
}

STD 12 COMPUTER STUDIES


Chapter 9 (Working with Array and String)

(1) Array object with its elements initialized by default values.


class Array1
{
public static void main(String[] s)
{
int marks[];
marks=new int[30];
for(int i=0; i<30; i++) //storing values in an array
{
marks[i]=i;
}
for(int i=0; i<30; i++) // retrieving values from the array
{
[Link]("marks ["+i+"] is " + marks[i]);
}
}
}

(2) Different ways to create and initialize array object


class array2
{
public static void main(String[] s)
{
int marks1[];
marks1=new int[3];
int marks2[]=new int[3];
int[] marks3=new int[3];
int marks4[]={50,60,70};
int[] marks5={70,80,90};

[Link]("Array mark1:\t");
display(marks1,3);
[Link]("Array mark2:\t");
display(marks2,3);
[Link]("Array mark3:\t");
display(marks3,3);
[Link]("Array mark4:\t");
display(marks4,3);
[Link]("Array mark5:\t");
display(marks5,3);
}
static void display(int arr[], int size)
{
for(int i=0; i<size; i++)
{
[Link](arr[i] + "\t");
}
[Link]();
}
}

(3) 2-D array : characters stored in bytes using corresponding integer value.
class Array2Dbyte
STD 12 COMPUTER STUDIES
{
public static void main(String[] s)
{
byte name[] [] =
{
{'J','a','v','a'},
{'C'},
{'C','+','+'},
{'B','a','c','i','c'},
{'P','a','s','c','a','i'},
};
[Link]("Fives names stored in 2-D array of characters : \n");
display(name, 5);
}

static void display(byte arr[][], int rows)


{
for (int i=0; i<rows; i++)
{

for(int j=0; j<arr[i].length; j++)


{
[Link](arr[i] [j] + "\t");
}
[Link]();
}
}
}

(4) Program using 2-D array with variable number of columns.


class Array2Dchar
{
public static void main(String[] s)
{

char name[][]=
{
{'J','a','v','a'},
{'C'},
{'C','+','+'},
{'B','a','c','i','c'},
{'P','a','s','c','a','i'},
};

[Link]("Number of elements in 2-D array:" + [Link] + "\n");


[Link]("Five names stored in 2-D Array of characters:\n");
display(name, 5);
}
static void display(char arr[][], int rows)
{
for(int i=0; i<rows; i++)
{
[Link]("Row " + i + " have" + arr[i].length+"character elements:");
for(int j=0; j<arr[i].length; j++)
{
STD 12 COMPUTER STUDIES
[Link]( arr[i][j]);
}
[Link]();
}
}
}

(5) Program to Compute average of 10 numbers using 1-D Array and loop.
class ArrayAvg
{
public static void main(String[] s)
{
double numbers[]={10.5,20.6,30.8,15.5,17.3,25.5,27.2,20,30,18.5};
byte ctr;
double sum=0, avg;
[Link]("list of number is");

for(ctr=0; ctr<10; ctr++)


{
[Link](numbers[ctr]);
sum=sum+numbers[ctr];
}
avg=sum/10;
[Link]("\n Average of above number is" + avg);
}
}

(6) Linear Search


class LinearSrch
{
public static void main(String[] s)
{

double list[]={6,5,9,9.5,6.5,7.5,8};
int indx;
[Link]("Given Array Element are:");
display(list);
indx=search(list, 8);
if(indx < 0)
[Link]("\n Element 8 is not found in array:");
else
[Link]("\n Element 8 is found at position" + indx);
indx=search(list,5.5);
if(indx<0)
[Link]("\n Element 5.5 is not found in array");
else
[Link]("\n Element 5.5 is found at position" + indx);
}
static void display(double ary[])
{
for(int i=0; i<[Link]; i++)
{
[Link](ary[i]);
STD 12 COMPUTER STUDIES
}
[Link]();
}
static int search(double ary[], double x)
{
for(int i=0; i<[Link]; i++)
{
if(ary[i]==x) return i;
}
return -1;
}
}

Chapter 10 (Exception Handling in JAVA)

(1) Program to display the content of element of citylist array that does not exist.(Try...Catch)
import [Link];
class TryCatchDemo
{
public static void main(String args[])
{
String citylist[] = {"Ahmedabad","Baroda","Rajkot","Surat"};
[Link]("Statement to be executed before try");
try
{
[Link]("Statement to be executed within try block, before displaying the
fifth element.");
[Link](citylist[5]);
[Link]("Statement to be executed within try block, before displaying the
fifth element.");
}
catch(ArrayIndexOutOfBoundsException eobj)
{
[Link]("Within Catch Block");
[Link]("Caught Exception object of type :" + eobj);
}
finally
{
[Link]("Statement to be executed compulsorily");
}
[Link]("Statement to be executed after try..... catch");
}
}

(2) A program which uses throws keyword to throw an exception from any method.

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

try
{
performDivision();
STD 12 COMPUTER STUDIES
}
catch(ArithmeticException eobj)
{
[Link]("Exception caught:" +eobj);

}
}
public static void performDivision() throws ArithmeticException
{

int ans;
ans=15/0;
}

}
Chapter 11 (File Handling)

(1) Reading from a file using character stream.


import [Link].*;
class FileRead
{
public static void main(String args[])
{
FileReader frobject = null;
try
{
frobject = new FileReader("[Link]");
int i;
char ch;

while((i = [Link]())!= -1)


{
ch=(char) i;
[Link](ch);
}
[Link]("\n");
}

catch(Exception eobj)
{
[Link](eobj);
}

finally
{

try
{
[Link]();
}
catch(Exception eobj)
{
[Link](eobj);
}
}
STD 12 COMPUTER STUDIES
}
}

(2) Write to a file using character stream.


import [Link].*;
class FileWrite
{
public static void main(String args [])
{
FileWriter fwobject = null;
try
{
//create an object of FileWrite
fwobject = new FileWriter("[Link]");
//write strings to the file
[Link]("Start writing in file.......");
for(int i=1; i<11; i++)
{
[Link]("\nLine : " + i);
}
[Link]("End of writing file........");
}

catch(Exception eobj)
{
[Link](eobj);
}

finally
{

try
{
[Link]();
}

catch(Exception eobj)
{
[Link](eobj);
}
}
}
}

(3) Write a java program to perform read and write operation to a binary file.
import [Link].*;
class BinaryFile
{
public static void main(String args[])
{
FileOutputStream fos = null;
FileInputStream fis = null;
String cities = "Rajkot \n Ahmedabad \n Vadodara \n Vapi \n";
byte citiesarray[] = [Link]();

STD 12 COMPUTER STUDIES


try
{
fos = new FileOutputStream("[Link]");
[Link](citiesarray);
[Link]();
fis = new FileInputStream("[Link]");
int i;
while((i=[Link]())!= -1)
{
[Link]((char)i);
}
[Link]();
}

catch(Exception eobj)
{
[Link](eobj);
}
}
}

(4) Write a java program to add two numbers taken as input from the user.
import [Link].*;
import [Link].*;
class ScannerInput
{
public static void main(String args[])
{
Scanner kbinput = null;
int num1;
int num2;
int sum=0;

try
{
kbinput = new Scanner([Link]);
[Link]("\nEnter first number : ");
num1 = [Link]();
[Link]("\nEnter second number : ");
num2 = [Link]();
sum = num1 + num2;
[Link]("\nSum is : " + sum);
}

catch(Exception eobj)
{
[Link](eobj);
}

finally
{
try
{
[Link]();
}
STD 12 COMPUTER STUDIES
catch(Exception eobj)
{
[Link](eobj);
}
}
}

(5) Write a java program to calculate total marks of each student that are taken as input from a
file.
import [Link].*;
import [Link].*;

class ScannerFile
{
public static void main(String args[])
{
Scanner fileinput = null;
int rollno,m1,m2,m3,totalmarks;
String name= null;
File fobject;

try
{
fobject = new File("[Link]");
fileinput = new Scanner(fobject);
[Link]("Default delimeter is :" + [Link]() + "\n");

while([Link]())
{
rollno = [Link]();
name = [Link]();
m1 = [Link]();
m2 = [Link]();
m3 = [Link]();
totalmarks = m1 + m2 + m3;
[Link]("Total marks of student " + rollno + "," + name + " are : "
+ totalmarks);
}
[Link]();
}

catch(Exception eobj)
{
[Link](eobj);
}
}
}

STD 12 COMPUTER STUDIES

Common questions

Powered by AI

File handling in Java is implemented using different types of I/O streams for character and binary data. For character streams, classes such as FileReader and FileWriter are used, which enable reading from and writing to text files. For instance, FileReader reads data from a file 'Charfile1.txt' character by character, while FileWriter writes strings to the file . On the other hand, FileOutputStream and FileInputStream are used for binary file operations, allowing byte-level input and output. In the case of binary data, a FileOutputStream writes a byte array representation of strings to 'Binaryfile.dat', and FileInputStream reads and displays the content . These methods underline Java's robust file handling capabilities for both character and binary data forms.

The Java program demonstrates an effective use of object-oriented principles through its structure, employing classes and methods to encapsulate data and behavior for calculating room area. The class 'R' initializes instance variables for dimensions and windows and provides methods for setting attributes and calculating area. The method area() multiplies length by width, encapsulating this logic within an object. The display() method outputs the room's properties. This structure leverages encapsulation, separating the initialization, calculation, and display functionality into distinct methods, promoting reusability and maintainability . This design effectively models real-world entities in programmatic form, standardizing room management operations.

The Java program handles inputs by using try-catch blocks to capture and manage exceptions that might occur during runtime inputs from users or files. When reading integers using a Scanner object, there is potential for InputMismatchException if the input doesn't match the expected data type. Wrapping input operations in try-catch blocks ensures that such runtime errors don't crash the application, enabling the program to catch and handle exceptions effectively, thus maintaining robustness. This practice of exception handling is essential to manage unpredictability in user input and to ensure smooth, uninterrupted application flow .

The Java program determines whether an integer is even or odd using conditional logic based on the modulus operator. In the provided example, the integer 'x' is evaluated using the condition 'x % 2 == 0'. If true, the number is even, otherwise it is odd. This simple conditional logic is effective for both integers and bytes, as the modulus operation checks whether there's a remainder when dividing by two . Such operations are fundamental in programming logic to evaluate numerical conditions effectively.

Switch statements in the Java programs are used to manage control flow based on integer values effectively. In the program that displays the month name, switch statements use the integer representation of months to print the respective month names as output . Similarly, the program that assigns grades based on marks uses a switch statement to determine and print the grade by setting an integer choice variable based on the conditions for marks . Both programs demonstrate using switch statements to simplify the decision-making process based on integer values that represent distinct categories or conditions.

The Java program for calculating simple interest employs straightforward logic and arithmetic expressions to derive the interest and maturity amounts. It initializes the principal amount (p), rate of interest (r), and the number of years (n). The interest is computed using the formula i = (n * p * r) / 100, which correctly multiplies the principal by the rate and duration, and subsequently divides by 100 to obtain interest as a percentage of the principal . The maturity amount is calculated by adding the interest to the initial principal. Overall, the methodology is sound, applying standard formulas in a clear and efficient manner.

The Java program uses a try-catch block to handle exceptions. Specifically, an ArrayIndexOutOfBoundsException is caught when trying to access an element of the citylist array that does not exist. The catch block prints a message indicating that an exception of type ArrayIndexOutOfBoundsException has been caught. This prevents the program from crashing and executes the finally block which prints a compulsory statement .

Polymorphism in the Java program is demonstrated through method overloading in the PrintLine class. The class defines three overloaded versions of the method printline(). The first method takes no arguments and prints a line of 40 equal signs. The second method takes an integer n and prints n hash symbols. The third method takes a character and an integer n, printing the character n times. These overloaded methods share the same name but differ in parameter types and counts, illustrating polymorphism .

Nested block statements in Java influence variable scope significantly. In the provided Java program, the variable 'x' is first declared outside any block, making it accessible both inside the blocks and outside if it isn't re-declared within a block. The attempted re-declaration of 'x' inside blk1 is commented out, as it would have caused a compile-time error due to a conflict in variable scope. Variables declared inside a block (like 'y' in blk1 and blk2) are limited to the scope of that block, making them inaccessible outside . This demonstrates the principle that a variable's scope is confined to the block in which it is declared.

Arrays in Java provide a structured way to store and manipulate data, which is effectively utilized in executing operations like linear searches and computing averages. For linear searches, an array allows iteration over elements, comparing each to a target value, and returning the index if found, demonstrating a straightforward implementation of search algorithms . For computing averages, arrays store sequences of numbers which can be easily traversed to calculate the sum and subsequently, the mean. This approach takes advantage of fixed-size data structures for efficient access and manipulation . While effective, one must be mindful of array size limitations and possible performance issues with large datasets, where alternative data structures like lists may be more appropriate.

You might also like