0% found this document useful (0 votes)
93 views26 pages

WAP To Illustrate The Concept of Type Casting

1. The document contains 7 code examples demonstrating various Java programming concepts like type casting, finding the day of the week for a given date, basic arithmetic operations, bitwise addition, printing prime numbers with prime digit sums, printing patterns, and matrix multiplication. 2. It also includes a code sample for a small quiz program using strings and files to ask multiple choice questions about Java fundamentals. 3. The document provides a set of code snippets covering common Java topics for learning purposes.

Uploaded by

Amanat
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
0% found this document useful (0 votes)
93 views26 pages

WAP To Illustrate The Concept of Type Casting

1. The document contains 7 code examples demonstrating various Java programming concepts like type casting, finding the day of the week for a given date, basic arithmetic operations, bitwise addition, printing prime numbers with prime digit sums, printing patterns, and matrix multiplication. 2. It also includes a code sample for a small quiz program using strings and files to ask multiple choice questions about Java fundamentals. 3. The document provides a set of code snippets covering common Java topics for learning purposes.

Uploaded by

Amanat
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
You are on page 1/ 26

1. WAP to illustrate the concept of type casting.

Widening type conversion


public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}

Narrowing type conversion

public class Test


{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required

System.out.println("Double value "+d);


System.out.println("Long value "+l);
System.out.println("Int value "+i);

2. WAP to find day of week on a given date.

import java.io.*;
class Date_DayMethod1
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int month[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
String
days[]={"","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Satur
day"};
System.out.print("Enter the day : ");
int d=Integer.parseInt(br.readLine());
System.out.print("Enter the month : ");
int m=Integer.parseInt(br.readLine());
System.out.print("Enter the year : ");
int y=Integer.parseInt(br.readLine());
if((y%400==0) || ((y%100!=0)&&(y%4==0)))
{
month[2]=29;
}
if(m<0 || m>12 || d<0 || d>month[m] || y<0 || y>9999) // Performing Date
Validation
{
System.out.println("Invalid Date");
}
else
{
int dn=0;
for(int i=1;i<m;i++)
{
dn=dn+month[i];
}
dn=dn+d;

System.out.print("Enter the Day on 1st January in this year: ");


String s=br.readLine().trim();

//finding the day of the week which corresponds to the given day
name
int x=0;
for(int i=1;i<=7;i++)
{
if (s.equalsIgnoreCase(days[i]))
x=i;
}

// the main calculation of finding the name of the day of the


week of the given date starts here
for(int i=1;i<dn;i++)
{
x++;
if(x==8)
x=1;
}
System.out.print("Output : "+d+"/"+m+"/"+y+" is a "+days[x]);
}
}
}

3. Create a JAVA program to carry out various arithmetic operations


just like a calculator.

public class BasicArithmeticDemo


{

public static void main(String[] args)


{
int number1 = 10;
int number2 = 5;

//calculating number1 + number2;


int sum = number1 + number2;

//calculating number1 - number2;


int difference = number1 - number2;

//calculating number1 * number2;


int product = number1 * number2;

//calculating number1 / number2;


int quot = number1 / number2;

//calculating number1 % number2;


int rem = number1 % number2;

//Displaying the values


System.out.println("number1 : "+number1);
System.out.println("number2 : "+number2);
System.out.println("sum : "+sum);
System.out.println("difference : "+difference);
System.out.println("product : "+product);
System.out.println("quot : "+quot);
System.out.println("rem : "+rem);
}
}

4. WAP to find sum of two integers using bitwise operator.

import java.util.Scanner;

public class Bitwise_Addition


{
static int add(int x, int y)
{
int carry;
while(y!=0)
{
carry = x & y;
x = x ^ y;
y = carry << 1;
}
return x;
}
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the numbers to be added:");
int x = input.nextInt();
int y = input.nextInt();
System.out.println("The Summation is: "+add(x, y));
input.close();
}
}

5. WAP to print only those first 20 prime numbers for which sum of
digits is also prime.

6. Implement the java program to print the following pattern on screen.


1

121

12321

1234321

import java.util.Scanner;

public class MainClass


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);

//Taking noOfRows value from the user

System.out.println("How Many Rows You Want In Your Pyramid?");

int noOfRows = sc.nextInt();

//Initializing rowCount with 1

int rowCount = 1;

System.out.println("Here Is Your Pyramid");

//Implementing the logic

for (int i = noOfRows; i > 0; i--)


{
//Printing i*2 spaces at the beginning of each row

for (int j = 1; j <= i*2; j++)


{
System.out.print(" ");
}

//Printing j value where j value will be from 1 to rowCount

for (int j = 1; j <= rowCount; j++)


{
System.out.print(j+" ");
}

//Printing j value where j value will be from rowCount-1 to 1

for (int j = rowCount-1; j >= 1; j--)


{
System.out.print(j+" ");
}

System.out.println();

//Incrementing the rowCount

rowCount++;
}
}
}

7. WAP to perform multiplication of two matrices.

import java.util.Scanner;

public class MatixMultiplication


{
public static void main(String args[])
{
int n;
Scanner input = new Scanner(System.in);
System.out.println("Enter the base of squared matrices");
n = input.nextInt();
int[][] a = new int[n][n];
int[][] b = new int[n][n];
int[][] c = new int[n][n];
System.out.println("Enter the elements of 1st martix row wise \n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
a[i][j] = input.nextInt();
}
}
System.out.println("Enter the elements of 2nd martix row wise \n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
b[i][j] = input.nextInt();
}
}
System.out.println("Multiplying the matrices...");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < n; k++)
{
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
System.out.println("The product is:");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(c[i][j] + " ");
}
System.out.println();
}
input.close();
}
}

8. WAP to conduct a small quiz using strings and files.

import java.util.*;

public class Quiz{

String quizQuestions, quizOptions, answer, enter;

char ch;

int i, correct=0;

Quiz[] quiz=new Quiz[61];


public void initialise(){

for(i=0; i<61; i++) {

quiz[i]=new Quiz();

public void quizQuestions(){

try{

quiz[0].quizQuestions="Who Developed Java?";

quiz[1].quizQuestions="What was the original name of Java?";

quiz[2].quizQuestions="What is the full form of JDK?";

quiz[3].quizQuestions="What is an class in Java?";

quiz[4].quizQuestions="What is Abstraction in Java?";

quiz[5].quizQuestions="What is Encapsulation in Java?";

quiz[6].quizQuestions="What is an Method?";

quiz[7].quizQuestions="What is the other name of Method?";

quiz[8].quizQuestions="What is an Object?";

quiz[9].quizQuestions="What is Message Passing?";

quiz[10].quizQuestions="What is an Object Factory?";

catch(ArrayIndexOutOfBoundsException e){

System.err.println("Error Occur!\n"+e.getMessage());

System.exit(0);

public void quizOptions(){

try{

quiz[0].quizOptions="A: Charles Babbage\nB: Lady Ada Lovelace\nC: Tim Berners-Lee\nD: James Gosling";
quiz[1].quizOptions="A: C++\nB: Groovey\nC: Oak\nD: HTML";

quiz[2].quizOptions="A: Java Developing Kit\nB: Java Development Kit\nC: Java Developed Kit\nD: Java Disk
Kit";

quiz[3].quizOptions="A: It is an representation of a set of objects\nB: It is nothing more than a keyword\nC:


An identifiable entity with some characteristics and behaviour\nD: Datatype";

quiz[4].quizOptions="A: Representation for the specific behaviour of an object\nB: Wrapping up of data into
a single unit\nC: Type of an Java Program\nD: Act of Representing essential features only without any background
details";

quiz[5].quizOptions="A: Wrapping up of data into a single unit\nB: Keyword\nC: Use to declaire an


Object\nD: One of the Characteristics of Java";

quiz[6].quizOptions="A: The number and types of Arguments\nB: Collection of similar datatype\nC: A


sequence of statements that carry out specific task(s)\nD: Throwable Exception";

quiz[7].quizOptions="A: Function\nB: Array\nC: Exception\nD: Class";

quiz[8].quizOptions="A: Blue print of an Program\nB: Identifiable entity with some Characteristics and
Behaviour\nC: Visibility mode of an Java statement\nD: Type of a Stream used in Java";

quiz[9].quizOptions="A: A way of sending/receiving information to/from another class\nB: A way of


sending/receiving information to/from another package\nC: A way of sending/receiving information to/from
another instance of class\nD: A way to implement data abstraction in Java";

quiz[10].quizOptions="A: A producer of method\nB: A producer of class\nC: A producer of memory


location\nD: A producer of instance of a class";

catch(ArrayIndexOutOfBoundsException e){

System.err.println("Error Occur!\n"+e.getMessage());

System.exit(0);

public void quizAnswers(){

quiz[0].answer="D";

quiz[1].answer="C";

quiz[2].answer="B";

quiz[3].answer="A";

quiz[4].answer="D";

quiz[5].answer="A";
quiz[6].answer="C";

quiz[7].answer="A";

quiz[8].answer="B";

quiz[9].answer="C";

quiz[10].answer="B";

public void play(){

try{

Scanner scan=new Scanner(System.in);

String temp="";

Collections.shuffle(Arrays.asList(quiz));

Collections.shuffle(Arrays.asList(quiz));

for(i=0; i<10; i++){

System.out.println("Question "+(i+1)+": "+quiz[i].quizQuestions+"\nOptions:-\n"+quiz[i].quizOptions);

System.out.printf("Your Answer (A/B/C/D): ");

temp=scan.next();

ch=temp.charAt(0);

temp=Character.toString(ch);

System.out.println("\n\n");

if(temp.equalsIgnoreCase(quiz[i].answer)){

System.out.println("* * * Correct! * * *");

correct++;

else{

System.out.println("* * * Incorrect! * * *");

System.out.println("Answer: "+quiz[i].answer);

System.out.println("\n\n");
}

catch(ArrayIndexOutOfBoundsException e){

System.err.println("Error Occur!\n"+e.getMessage());

System.exit(0);

catch(InputMismatchException e){

System.err.println("Error Occur!\n"+e.getMessage());

System.exit(0);

public void result(){

System.out.println("Your Final Result:- ");

System.out.println("You answered 10 questions out of which you answered "+correct+" correct and "+(10-
correct)+" incorrect!");

if(correct<=5)

System.out.println("Better Luck Next Time!");

else if(correct<10 && correct>5)

System.out.println("You played nice. But more affort is needed!");

else if(correct==10)

System.out.println("You did a Marvelous job!");

public static void main(String[] args){

Quiz obj=new Quiz();

obj.initialise();

obj.quizQuestions();

obj.quizOptions();

obj.quizAnswers();
obj.play();

obj.result();

9. WAP to sort elements of an integer array using bubble sort and


quick sort algorithm.

Bubble sort
public class MyBubbleSort {

// logic to sort the elements


public static void bubble_srt(int array[]) {
int n = array.length;
int k;
for (int m = n; m >= 0; m--) {
for (int i = 0; i < n - 1; i++) {
k = i + 1;
if (array[i] > array[k]) {
swapNumbers(i, k, array);
}
}
printNumbers(array);
}
}

private static void swapNumbers(int i, int j, int[] array) {

int temp;
temp = array[i];
array[i] = array[j];
array[j] = temp;
}

private static void printNumbers(int[] input) {

for (int i = 0; i < input.length; i++) {


System.out.print(input[i] + ", ");
}
System.out.println("\n");
}

public static void main(String[] args) {


int[] input = { 4, 2, 9, 6, 23, 12, 34, 0, 1 };
bubble_srt(input);

}
}

Output:
2, 4, 6, 9, 12, 23, 0, 1, 34,

2, 4, 6, 9, 12, 0, 1, 23, 34,

2, 4, 6, 9, 0, 1, 12, 23, 34,

2, 4, 6, 0, 1, 9, 12, 23, 34,

2, 4, 0, 1, 6, 9, 12, 23, 34,

2, 0, 1, 4, 6, 9, 12, 23, 34,

0, 1, 2, 4, 6, 9, 12, 23, 34,

0, 1, 2, 4, 6, 9, 12, 23, 34,

0, 1, 2, 4, 6, 9, 12, 23, 34,

0, 1, 2, 4, 6, 9, 12, 23, 34,

Quick sort

public class MyQuickSort {

private int array[];


private int length;

public void sort(int[] inputArr) {

if (inputArr == null || inputArr.length == 0) {


return;
}
this.array = inputArr;
length = inputArr.length;
quickSort(0, length - 1);
}

private void quickSort(int lowerIndex, int higherIndex) {

int i = lowerIndex;
int j = higherIndex;
// calculate pivot number, I am taking pivot as middle index number
int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2];
// Divide into two arrays
while (i <= j) {
while (array[i] < pivot) {
i++;
}
while (array[j] > pivot) {
j--;
}
if (i <= j) {
exchangeNumbers(i, j);
//move index to next position on both sides
i++;
j--;
}
}
// call quickSort() method recursively
if (lowerIndex < j)
quickSort(lowerIndex, j);
if (i < higherIndex)
quickSort(i, higherIndex);
}

private void exchangeNumbers(int i, int j) {


int temp = array[i];
array[i] = array[j];
array[j] = temp;
}

public static void main(String a[]){

MyQuickSort sorter = new MyQuickSort();


int[] input = {24,2,45,20,56,75,2,56,99,53,12};
sorter.sort(input);
for(int i:input){
System.out.print(i);
System.out.print(" ");
}
}
}

10. Implement Java program that checks for given strings whether
they are anagrams or not.

import java.util.Scanner;

public class JavaProgram


{
public static void main(String[] input)
{
String str1, str2;
int len, len1, len2, i, j, found=0, not_found=0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter First String : ");
str1 = scan.nextLine();
System.out.print("Enter Second String : ");
str2 = scan.nextLine();

len1 = str1.length();
len2 = str2.length();

if(len1 == len2)
{
len = len1;
for(i=0; i<len; i++)
{
found = 0;
for(j=0; j<len; j++)
{
if(str1.charAt(i) == str2.charAt(j))
{
found = 1;
break;
}
}
if(found == 0)
{
not_found = 1;
break;
}
}
if(not_found == 1)
{
System.out.print("Strings are not Anagram to Each
Other..!!");
}
else
{
System.out.print("Strings are Anagram");
}
}
else
{
System.out.print("Both Strings Must have the same number of
Character to be an Anagram");
}
}
}

11. Implement a java program to check whether a given number or


string is a palindrome or not.
Number

1. class PalindromeExample{
2. public static void main(String args[]){
3. int r,sum=0,temp;
4. int n=454;//It is the number variable to be checked for palindrome
5.
6. temp=n;
7. while(n>0){
8. r=n%10; //getting remainder
9. sum=(sum*10)+r;
10. n=n/10;
11. }
12. if(temp==sum)
13. System.out.println("palindrome number ");
14. else
15. System.out.println("not palindrome");
16. }
17. }

String
import java.util.*;

class Palindrome
{
public static void main(String args[])
{
String inputString;
Scanner in = new Scanner(System.in);

System.out.println("Input a string");
inputString = in.nextLine();

int length = inputString.length();


int i, begin, end, middle;

begin = 0;
end = length - 1;
middle = (begin + end)/2;

for (i = begin; i <= middle; i++) {


if (inputString.charAt(begin) == inputString.charAt(end)) {
begin++;
end--;
}
else {
break;
}
}
if (i == middle + 1) {
System.out.println("Palindrome");
}
else {
System.out.println("Not a palindrome");
}
}
}

12. WAP to print first 20 terms of Fibonacci series using recursion.

import java.util.Scanner;

class calc
{
int fibo(int n)
{
if(n==0)
return 0;
if(n==1)
return 1;
else
return fibo(n-1)+fibo(n-2);
}
}

public class Fibonacci


{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter fibonacci Term :");
int n=sc.nextInt();
System.out.println("Fibonacci Series is :\n");
calc c=new calc();
for(int i=0;i<n;i++)
{
System.out.print(" "+c.fibo(i));
}
}
}
13. WAP to illustrate the concept of Method Overloading, Constructor
Overloading and copy constructor, also make the use of this
keyword.

class box

int l,w,h;

static int count = 0;

box()

l=w=h=10;

box(int x)

l=w=h=x;

box(int x,int y,int z)

l=x;

w=y;

h=z;

box(box B)

l=B.l;

w=B.w;

h=B.h;

}
void duplicatebox(box b)

this.l=b.l;

this.w=b.w;

this.h=b.h;

void disp()

count++;

System.out.println(" ");

System.out.println("Length = "+l);

System.out.println("Width = "+w);

System.out.println("Height = "+h);

System.out.println("Number of times display is called = "+count);

class colorbox extends box

String color;

colorbox()

super();

color = "white";

colorbox(int x,String c)

super(x);
color = c;

colorbox(int x,int y,int z,String c)

super(x,y,z);

color = c;

colorbox(box b,String c)

super(b);

color = c;

void disp()

super.disp();

System.out.println("Color = "+color);

class testbox

public static void main (String [] args)

int i;

box b1=new box();

box b2=new box(10);

System.out.println("displaying Box 1");

b1.disp();

System.out.println("displaying Box 2");


b2.disp();

14. Create a class height in java program in order to store height in


feet and inches for various objects, to add height for various objects,
also make use of static data members and member functions in the
class.

class Height {
private int feet;
private int inches;

public Height(int feet, int inches) {


this.feet = feet;
this.inches = inches;
}

public static Height fromInches(int inches) {


//Convert to feet and inches.
return new Height(inches / 12, inches % 12);
}

public int toInches(){


return feet * 12 + inches;
}

public Height addTo(Height another){


//1. Convert both the heights to inches
//2. Do simple addition of inches
//3. Convert it back to Height using Height.fromInches, and return it
// or, in other words (behold your eyes):

return Height.fromInches(this.toInches() + another.toInches());


}

//Bonus
public String toString() {
return String.format("%s'%s\"", feet, inches);
}
}
15. WAP to illustrate the concept of inheritance by making the use of
public, private, protected and default Classes and Methods.

class Teacher {
private String designation = "Teacher";
private String collegeName = "Beginnersbook";
default final int salary = 200;
public String getDesignation() {
return designation;
}
protected void setDesignation(String designation) {
this.designation = designation;
}
protected String getCollegeName() {
return collegeName;
}
protected void setCollegeName(String collegeName) {
this.collegeName = collegeName;
}
void does(){
System.out.println("Teaching");
}
}

public class JavaExample extends Teacher{


String mainSubject = "Physics";
public static void main(String args[]){
JavaExample obj = new JavaExample();
System.out.println(obj.getCollegeName());
System.out.println(obj.getDesignation());
System.out.println(obj.mainSubject);
obj.does();
System.out.println(Salary = + obj.salary);
}
}

16. WAP to illustrate the concept of Method Overriding. Also show the
use of final keyword.

class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}

Use of final keyword.


class FinalKeywordTest
{
final int a=10;
public static void main(String args[])
{
System.out.println(value of a is + a);
}
}
Output: value of a is 10

17. WAP to show the use of super keyword.

class Person
{
void message()
{
System.out.println("This is person class");
}
}

/* Subclass Student */
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}

// Note that display() is only in Student class


void display()
{
// will invoke or call current class message() method
message();

// will invoke or call parent class message() method


super.message();
}
}

/* Driver program to test */


class Test
{
public static void main(String args[])
{
Student s = new Student();

// calling display() of Student


s.display();
}
}

18. Implement a java program to explain the concept of inbuilt


packages by using any 4 packages and their methods.

package relational;

public class Compare {

public int getMax(int x, int y) {

if ( x > y ) {

return x;

else {

return y;

}
import java.lang.Math;

public class ImportDemo {

public static void main(String args[]) {

double val = 64.0;

double sqroot = Math.sqrt(val); // Access sqrt() method using classname

System.out.println("Sq. root of " + val + " is " + sqroot);

import java.util.scanner;

public class demo {

public static void main (String[]args) {

int x;

Scanner sc = new Scanner(System.in);

x=sc.nextInt();

System.out.println(x);

} }

19. Create your own package and use it to perform some meaningful
task.

package letmecalculate;

public class Calculator {


public int add(int a, int b){
return a+b;
}
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(10, 20));
}
}

import letmecalculate.Calculator;

public class Demo{


public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(100, 200));
}
}

20. WAP to explain the concept of interfaces in JAVA.

1. interface Bank{
2. float rateOfInterest();
3. }
4. class SBI implements Bank{
5. public float rateOfInterest(){return 9.15f;}
6. }
7. class PNB implements Bank{
8. public float rateOfInterest(){return 9.7f;}
9. }
10. class TestInterface2{
11. public static void main(String[] args){
12. Bank b=new SBI();
13. System.out.println("ROI: "+b.rateOfInterest());
14. }}

21. WAP to illustrate the concept of Exception handling in java.

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

int a, b, result;

Scanner input = new Scanner(System.in);


System.out.println("Input two integers");

a = input.nextInt();
b = input.nextInt();

// try block
try {
result = a / b;
System.out.println("Result = " + result);
}

// catch block

catch (ArithmeticException e) {
System.out.println("Exception caught: Division by zero.");
}
}
}

22. WAP to create your own exceptions in Java.

class MyException extends Exception {


private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}
}
}

You might also like