[Go to site: main page, start]

0% found this document useful (0 votes)
31 views11 pages

Java Programs for Number Manipulation

The document contains 16 code snippets demonstrating various Java programming concepts including: 1. Reversing an integer and checking if it is odd or even using switch case. 2. Creating an Employee class with getdata() and putdata() methods. 3. Calculating a factorial using a function. 4. Autoboxing and unboxing with wrapper classes. 5. Parameterized constructors. 6. Applying string methods like equals(), compareTo(), etc. 7. Implementing a vector and adding different data types. 8. Applying vector methods like addElement(), elementAt(), etc. 9. Single inheritance with a Student superclass. 10. Creating and importing packages.

Uploaded by

rajeshkhavane441
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views11 pages

Java Programs for Number Manipulation

The document contains 16 code snippets demonstrating various Java programming concepts including: 1. Reversing an integer and checking if it is odd or even using switch case. 2. Creating an Employee class with getdata() and putdata() methods. 3. Calculating a factorial using a function. 4. Autoboxing and unboxing with wrapper classes. 5. Parameterized constructors. 6. Applying string methods like equals(), compareTo(), etc. 7. Implementing a vector and adding different data types. 8. Applying vector methods like addElement(), elementAt(), etc. 9. Single inheritance with a Student superclass. 10. Creating and importing packages.

Uploaded by

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

1.

Write a program in Java to perform reverse of entered number and check


whether entered number is odd or even using switch case.
package [Link];

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

int num = 2344, rev = 0;


[Link]("Entered no: "+num);
while(num != 0){
int digit = num %10;
rev = (rev + digit )*10;
num = num/10;
}
rev=rev/10;
[Link]("Reversed no: "+rev);
int temp = rev % 2;
switch(temp){
case 0:
[Link]("even");
break;
case 1:
[Link]("odd");
break;
}
}
}

2. Write a program in Java to create class Employee with methods getdata() and
putdata() and instantiate its object.
import [Link].*;

class Employee {
int emp_id;
String name;
String Dept;

public void getdata(){


Scanner s = new Scanner([Link]);
[Link]("Enter Employee Id : ");
emp_id = [Link]();
[Link]("Enter Employee Name : ");
name = [Link]();
[Link]("Enter Employee Department : ");
Dept = [Link]();
[Link]();
}

public void putdata(){


[Link]("Employee Id is : "+emp_id);
[Link]("Employee Name is : "+name);
[Link]("Employee Department is : "+Dept);
}

public static void main(String args[])


{
Employee a = new Employee();
[Link]();
[Link]();
}
}

3. Write a program for Factorial using Function.


import [Link];

public class Factorial {

static void fact() {


Scanner s = new Scanner([Link]);
int fact = 1, a;
[Link]("enter no of which you want factorial : ");
a = [Link]();
for (int i = 1; i <= a; i++) {
fact = fact * i;
}
[Link]("FActorial of " + a + " is : " + fact);
[Link]();
}

public static void main(String[] args) {


fact();
}
}

4. Write a program for Wrapper Class.(Autoboxing)


import [Link];

//primitive to object auto boxing

public class J_10 {


public static void main(String[] args) {
Vector v = new Vector<>(5, 2);
int a = 2;
double b = 3.32456789;
float c = 4.65f;
// [Link](a);
Integer x = new Integer(a);
Double y = new Double(b);
Float z = new Float(c);
[Link](x);
[Link](y);
[Link](z);
[Link](v);

5. Write a program for Wrapper Class.(Unboxing)


//object to primitive unboxing

public class J_11 {


public static void main(String[] args) {

Integer x = new Integer(100);


Double y = new Double(5.765455);
Float z = new Float(9.324f);

int p = [Link](x);
double q = [Link](y);
float r = [Link](z);
[Link](p);
[Link](q);
[Link](r);
}
}

6. Write a program for Parameterised Constructor


//Parameterized constructor.

class J_3 {
int id;
String name;

J_3(int i, String n) {
id = i;
name = n;
}

void display() {
[Link](id + " " + name);
}

public static void main(String args[]) {

J_3 s1 = new J_3(111, "Karan");


J_3 s2 = new J_3(222, "Aryan");

[Link]();
[Link]();
}
}

7. Write a program in Java to apply string methods : equals(), compareTo(),


charAt(), toUpperCase() over entered strings from user.
//String methods

public class j_12 {


public static void main(String[] args) {
String s = "sujal";

//equal
[Link]([Link]("sujal"));//returns true or false

//compare
[Link]([Link]("suja"));// returns zero if equal,1(size) if
less size,-1(size) if big size

//charat
[Link]([Link](3));

//uppercase
[Link]([Link]());
}
}

8. Write a program in Java to apply String methods : equalsIgnoreCase(),


compareTo(), indexOf(), toLowerCase() over entered strings from user.
//String methods

public class j_12 {


public static void main(String[] args) {
String s = "sujal";

//equal
[Link]([Link]("sujal"));//returns true or false

//compare
[Link]([Link]("suja"));// returns zero if equal,1(size) if
less size,-1(size) if big size

//charat
[Link]([Link](3));

//uppercase
[Link]([Link]());

//compare
[Link]([Link]("Prasad"));// returns zero if equal,1(size)
if less size,-1(size) if big size

//charat
[Link]([Link](3));

//uppercase
[Link]([Link]());

//equalegnorcase
[Link]([Link]("Prasad"));

//indexof
[Link]([Link]("P"));

//tolowercase
[Link]([Link]());
}
}

9. Write a program in Java to implement a vector and add five elements of type
Integer, Character, Boolean, Long, Float into that vector. Also display vector
elements.
import [Link];
public class J_10 {
public static void main(String[] args) {
Vector v = new Vector<>(5, 2);
int a = 2;
double b = 3.32456789;
float c = 4.65f;
char d = 'a';
long e = 2312414;
// [Link](a);
Integer t = new Integer(a);
Double w = new Double(b);
Float x = new Float(c);
Character y = new Character(d);
Long z = new Long(e);
[Link](t);
[Link](w);
[Link](x);
[Link](y);
[Link](z);
[Link](v);

10. Write a program in Java to apply Vector methods : addElement(), elementAt(),


firstElement(), removeElementAt() over vector v.
import [Link];

public class J_13 {


public static void main(String[] args) {
Vector v = new Vector<>(5, 2);
int a = 2;
double b = 3.32456789;
float c = 4.65f;
// [Link](a);
Integer x = new Integer(a);
Double y = new Double(b);
Float z = new Float(c);
String V = "Sujal";
[Link](x);
[Link](y);
[Link](z);
[Link](V);
[Link](v);

//add element
[Link]("ThisWillBeAdded");

//element at
[Link]([Link](3));

//first element
[Link]([Link]());

//remove element at
[Link](1);
[Link](v);
}
}

11. Write a program in Java to implement single inheritance with super class
Student and sub class Marks.

 class Student {
String name="Abhinav Ingle";

}
class Displayname extends Student
{
void display(){
String name="Rupesh Bhadane";
[Link](name);
[Link]([Link]);
}
}
class Tester extends Student
{
public static void main(String args[])
{
Displayname D = new Displayname();
[Link]();
}
}

12. Write a program in Java to create package with class student. Write another
program to import created package(class and methods).

13. Write a program in Java to handle Arithmetic Exception.


import [Link].*;
import [Link].*;
public class DivideException {
public static void main(String args[]){
int a,b,c;
Scanner s = new Scanner([Link]);
[Link]("Enter first no: ");
a = [Link]();
[Link]("Enter Second no: ");
b = [Link]();
try{
c = a/b;
[Link]("Division is"+c);
}catch(ArithmeticException obj){
[Link](obj);
[Link]("Invalid Input");
}
}
}

14. Write a program in Java to throw user defined exception if entered number is
Negative.
import [Link].*;
import [Link].*;
class NegativeException extends Exception{
NegativeException(String str)
{
super(str);
}
}
public class Negexc {
public static void main(String args[])
{
int num;
Scanner s = new Scanner([Link]);
[Link]("Enter a Number: ");
num = [Link]();
try{
if(num<0)
{
throw new NegativeException("Number is Negative");
}
else
{
[Link]("Number is Positive");
}
}catch(NegativeException N)
{
[Link](N);
}
}
}

15. Write a program in Java to create two threads: one will print even numbers
and other odd number from 1 to 20.
import [Link].*;
class Even extends Thread
{
public void run()
{
for(int i=2;i<=20;i=i+2)
{
[Link]("\t Even thread :"+i);
}
}
}

class Odd extends Thread


{
public void run()
{
for(int i=1;i<20;i=i+2)
{
[Link]("\t Odd thread :"+i);
}
}
}
class EvenOdd
{
public static void main(String args[])
{
new Even().start();
new Odd().start();
}
}

16. Write a program in Java to draw smiley shape using applet.


import [Link];
import [Link];
import [Link];

public class Smiley extends Applet {


@Override
public void paint(Graphics g) {
[Link]([Link]);
[Link](50, 100, 100,100);
[Link]([Link]);
[Link](65, 120, 20, 20);
[Link](115, 120, 20, 20);
[Link](75, 145, 50, 40, 0, -180);
}
}

// <Applet code = "Smiley" width = "480" height = "300"></Applet>

17. Write a program in java to draw three concentric circle.


import [Link].*;
import [Link].*;
public class ConcentricCircle extends Applet{
public void paint(Graphics g)
{
[Link]([Link]);
[Link](50, 100, 400, 400);
[Link]([Link]);
[Link](100, 150, 300, 300);
[Link]([Link]);
[Link](150, 200, 200, 200);
}
}

18. Write a program to copy contents of one File into another using Byte stream.
1. import [Link].*;
2. import [Link].*;
3. class Copyfile {
4. public static void main(String arg[]) throws Exception {
5. Scanner sc = new Scanner([Link]);
6. [Link]("Provide source file name :");
7. String sfile = [Link]();
8. [Link]("Provide destination file name :");
9. String dfile = [Link]();
10. FileReader fin = new FileReader(sfile);
11. FileWriter fout = new FileWriter(dfile, true);
12. int c;
13. while ((c = [Link]()) != -1) {
14. [Link](c);
15. }
16. [Link]("Copy finish...");
17. [Link]();
18. [Link]();
19. }
20. }

19. Write a program in Java to create class Student with methods getdata() and
putdata() and instantiate its object.
import [Link].*;
public class StudentEx {
String name;
int rollno;
String Class;
Scanner s = new Scanner([Link]);
void getdata()
{
[Link]("Enter Name of Student: ");
name = [Link]();
[Link]("Enter Class Of Student: ");
Class = [Link]();
[Link]("Enter Roll No of Student: ");
rollno = [Link]();

}
void putdata()
{
[Link]("Name of Student: "+name);
[Link]("Roll No of Student: "+rollno);
[Link]("Class Of Student: "+Class);
}
public static void main(String args[])
{
StudentEx obj = new StudentEx();
[Link]();
[Link]();
}
}

20. Write a program in Java to create two threads: one will print numbers 1 to 20
and other reverse number from 20 to 1.
import [Link].*;
import [Link].*;
class Orginal extends Thread{
public void run(){
for(int i=1; i<=20;i++)
{
[Link](i);
}
}
}
class Reverse extends Thread{
public void run(){
for(int i=20; i>=1;i--)
{
[Link](i);
}
}
}
class RevThread {
public static void main(String args[])
{
new Orginal().start();
new Reverse().start();
}
}

21. Write a program in Java to perform reverse of entered number and check
whether entered number is positive or negative using switch case.
import [Link];
class Poscheck{
public static int positive(int num){
if(num>0){
return 1;
}
else if(num<0){
return 0;
}
else{
return -1;
}
}
public static void main(String args[]){
int rev=0;
int n;
Scanner scan=new Scanner([Link]); //create a scanner object for input
[Link]("\nEnter the integer number: ");
int num=[Link]();//get input from the user for num
int result=positive(num);
switch(result){
case 0://check num is negative
[Link](num+" is negative"+"\n");
break;
case 1://check num is positive
[Link](num+" is positive"+"\n");
break;
default:
[Link]("the given number is zero");
break;

while(num!=0)
{
n = num%10;
rev = rev *10+n;
num = num/10;
}
[Link]("Reverse Number is:"+rev);
}
}

22. Write a program in Java to implement a vector and add five elements of type
Integer, Character, Boolean, Long, Float into that vector. Also display vector
elements.
import [Link].*;
import [Link].*;
public class VectorOP {
public static void main(String args[])
{
Vector V = new Vector();
Integer a = new Integer("10");
Character b = new Character('j');
Boolean c = new Boolean("True");
Long d = new Long("1223456");
Float e = new Float("23.22");
[Link](a);
[Link](b);
[Link](c);
[Link](d);
[Link](e);
[Link](V);

}
}

[Link] a program to implement following interface with multiple


inheritance.

Common questions

Powered by AI

The single inheritance demonstrated with Student and Displayname classes, along with the use of the super keyword, provides a clear structure for code reusability and modularity . The benefit is that it allows easy access to a superclass's fields and methods, promoting code reuse. However, drawbacks include potential tight coupling between the superclass and subclass, leading to less flexibility in design alterations and possible difficulties in debugging if superclass modifications are required. The limited single inheritance model in Java can also restrict the ability to consolidate functionality from multiple hierarchies without additional interfaces or design patterns.

Java's Vector class is used for managing collections of objects dynamically, with automatic resizing and a variety of methods for element manipulation, such as addElement() and removeElementAt(). While providing synchronized access to data, it ensures thread safety, though at the cost of performance due to synchronization overhead. Alternatives like ArrayList provide better performance due to lack of synchronization, serving as more efficient options for use cases where thread safety isn't critical, offering just-in-time storage expansions and automatic management of indexing.

Java's Applet class provides a framework for creating graphical applications that can be embedded in web pages or run as standalone applications. It's used for rendering graphics through drawing shapes, applying colors, and handling basic animations . The smiley face drawing program leverages this by overriding the paint() method to draw shapes using graphical contexts and methods like fillOval() for circles and drawArc() for curved lines to depict facial features, showcasing interactive and visually engaging components of GUI design.

The Factorial class in the given Java program uses iteration through a for loop to calculate the factorial of a number input by the user . Utilizing iteration in this context, as opposed to recursion, can be beneficial because it avoids the overhead associated with recursive method calls and can prevent potential stack overflow errors in cases of large numbers, offering increased efficiency and simpler memory management.

The Even and Odd threads example demonstrates multithreading by separately managing two independent tasks—printing even and odd numbers between 1 to 20—in parallel . This allows for efficient CPU usage by employing concurrent execution, helping software to remain responsive and improving performance, especially in applications requiring simultaneous operations. Benefits include improved application throughput and responsiveness, though it requires careful management to avoid race conditions or deadlocks. The code illustrates thread instantiation and execution, showcasing parallel processing concepts.

The NegativeException class exemplifies effective error management by providing a means to define and handle specific error conditions logically related to application context, in this case, detecting negative numbers . User-defined exceptions like NegativeException offer tailored exception handling tailored to the problem domain, improving code clarity and functionality. However, excessive use or complexity in custom exceptions can lead to convoluted catch blocks and reduced code readability if not carefully structured alongside standard exceptions.

In the Java program, switch statements are used to decide whether the reversed number is odd or even by checking the remainder when the number is divided by 2 . This approach allows for a clear and concise structure to control the program flow based on discrete conditions. However, potential limitations include its inability to handle complex and compound conditions without becoming cumbersome, and switch statements are only suitable when working with discrete, fixed data types like integers or enumerated types, not for more complicated logic or data structures.

File input/output operations in Java, exemplified by the program copying file contents, involve reading from and writing to files using classes like FileReader and FileWriter . This process provides programs with the capability to persist data, transfer information, and bridge interactions with external systems. However, file handling must be carefully managed to prevent resource leaks via streams and handle exceptions efficiently, as file operations can result in IOExceptions if files are not found or accessed improperly. Considerations for file permissions and proper closing of streams are crucial to maintain system stability and security.

The Java program demonstrates autoboxing by converting primitive types (int, double, float) to their corresponding wrapper class objects (Integer, Double, Float) when elements are added to a collection like a Vector . Conversely, unboxing is illustrated by converting wrapper class objects back to their respective primitive types using methods like Integer.valueOf(), Double.valueOf(), and Float.valueOf(). This showcases Java's ability to seamlessly convert between primitive types and their wrapper objects to facilitate operations in collections and provide object methods.

The design of Employee and Student classes with methods like getdata() and putdata() reflects the principle of encapsulation in object-oriented programming, where the method controls access to the class fields . This separation between the class's data and functionality allows you to hide the inner workings and maintain control over how data is accessed and modified. It also demonstrates the use of abstraction by providing a method to interact with the complex data of a class object, rather than directly interfacing with the attributes.

You might also like