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

Piyush

The documents provide code snippets to solve programming problems. The first program accepts a string as a command line argument and prints a welcome message. The second program finds the ASCII code of a character. The third program accepts two integers as input and prints their sum.

Uploaded by

Màńî Råtñam
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Piyush

The documents provide code snippets to solve programming problems. The first program accepts a string as a command line argument and prints a welcome message. The second program finds the ASCII code of a character. The third program accepts two integers as input and prints their sum.

Uploaded by

Màńî Råtñam
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

PROGRAM 1

Aim: Write a program to accept a String as a command-line argument and print a Welcome message as
given “Welcome yourname”.

Theory: The java command-line argument is an argument i.e. passed at the time of running the java
program.
The arguments passed from the console can be received in the java program and it can be used as an input. So,
it provides a convenient way to check the behavior of the program for the different values.

Source Code:

public class WelcomeMessage {


public static void main(String[] args) {
if(args.length == 1) {
String name = args[0];
System.out.println("Welcome " +
name);
}
else {
System.out.println("Please provide your name as a command-line argument");
}
}
}

Output:
PROGRAM 2

Aim: Write a program to find ASCII code of a character.

Theory: ASCII stands for American Standard Code for Information Interchange. ASCII is a standard
data-transmission code that is used by the computer for representing both the textual data and control
characters. ASCII is a 7-bit character set having 128 characters, i.e., from 0 to 127. ASCII represents a
numeric value for each character, such as 65 is a value of A. In our Java program, we need to manipulate
characters that are stored in ASCII. In Java, an ASCII table is a table that defines ASCII values for each
character. It is also a small subset of Unicode because it contains 2 bytes while ASCII requires only one
byte.

Source Code:
import java.util.Scanner;
public class Q2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the character- ");
char x= s.next().charAt(0);
System.out.print("The ASCII code of "+ x +" is- "+ (int)x);
}
}

Output:
PROGRAM 3

Aim: Write a program to accept two integers as inputs and print their sum.

Theory: In Java, finding the sum of two or more numbers is very easy. First, declare and initialize two
variables to be added. Another variable to store the sum of numbers. Apply mathematical operator (+)
between the declared variable and store the result. The following program calculates and prints the sum of
two numbers.

Source Code:
import java.util.Scanner;
public class Q3 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter two integers- ");
int a=s.nextInt();
int b=s.nextInt();
System.out.println("The sum of "+ a +" and "+ b +" is- "+ (a+b));
}
}

Output:
PROGRAM 4

Aim: Write a program for Swapping of two numbers using bitwise operator.

Theory: The bitwise XOR operator(represented by ^) compares corresponding bits of two operands and
returns 1 if they are equal and 0 if they are not equal. Let’s say we have two numbers x and y, so what
actually x^y will do is that it will compare every corresponding bit of x and y, and if they are different, it
will generate 1 as the output of that two bits (one of x and one of y) taken into consideration and if bits
are same, then it will generate 0 as the output of two bits.

Source Code:

import java.util.Scanner;
public class Q4 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the numbers- ");
int a=s.nextInt();
int b=s.nextInt();
System.out.println("Numbers before swapping are a="+ a +" and b="+ b);
a=a^b;
b=a^b;
a=a^b;
System.out.println("Numbers after swapping are a="+ a +" and b="+ b);
}
}

Output:
PROGRAM

Aim: Write a program to initialize two-character variables in a program and display the characters in
alphabetical order.

Theory: Here 2 characters are initialised using the Scanner Class and if statement is used to check whether
a character’s ASCII value is greater than the other. The character with the lower ASCII values falls below
the one’s with the greater ASCII values in alphabetical order. The same is shown in the below program.

Source Code:

import java.util.Scanner;
public class Q5 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the characters- ");
char x=s.next().charAt(0);
char y=s.next().charAt(0);
if (x<y) {
System.out.println("The characters in alphabetical order are- "+ x +" and "+ y);
}
else {
System.out.println("The characters in alphabetical order are- "+ y +" and "+ x);
}
}
}

Output:
PROGRAM

Aim: Write a program to receive a colour code from the user (an Alphabet).

Theory: The program segment given below accepts a character from the keyboard and prints the name of
the corresponding color, e. g., if the user enters character R, it prints Red. However, it handles only 7 colors,
namely, Violet, Indigo, Blue, Green, Yellow, Orange and Red.

Source Code:

import java.util.Scanner;
public class Q6 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("VIBGYOR");
System.out.print("Enter your choice- ");
char x=s.next().charAt(0);
if (x=='V' || x=='v') {
System.out.println("The Colour is Violet");
}
else if (x=='I' || x=='i') {
System.out.println("The Colour is Indigo");
}
else if (x=='B' || x=='b') {
System.out.println("The Colour is Blue");
}
else if (x=='G' || x=='g') {
System.out.println("The Colour is Green");
}
else if (x=='Y' || x=='y') {
System.out.println("The Colour is Yellow");
}
else if (x=='O' || x=='o') {
System.out.println("The Colour is
Orange");
}
else if (x=='R' || x=='r') {
System.out.println("The Colour is Red");
}
else {
System.out.println("Wrong choice!");
}
}
}
Output:
PROGRAM

Aim: Write a program to print even numbers between 23 and 57. Each number should be printed in a
separate row.

Theory: Here the even numbers are printed using for loop starting with 23. A condition is used i.e. if
number modulus 2 is equal to zero, then the number is printed else the loop is continued till the end point 57.
The implementation of the program is shown below.

Source Code:
import java.util.Scanner;
public class Q7 {
public static void main(String[] args) {
for (int i=23;i<=57;i++) {
if (i%2==0) {
System.out.println(i);
}
}
}
}

Output:
PROGRAM

Aim: Write a program to print * in Floyd’s format (using for and while loop).

Theory: Floyd’s Triangle is a triangle with first natural numbers. It is the right arrangement of the
numbers/values or patterns. Basically, it is a left to right arrangement of natural numbers in a right-angled
triangle. So here in this program instead of natural numbers a star(*) pattern is printed in floyd’s format.

Source Code:

Using for loop:


import java.util.Scanner;

public class Q8a {


public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the number of lines- ");
int n=s.nextInt();
for (int i=0;i<n;i++) {
for (int j=i+1;j>0;j--) {
System.out.print("* ");
}
System.out.println();
}
}
}

Using while loop:


import java.util.Scanner;

public class Q8b {


public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the number of lines- ");
int n=s.nextInt();
int i=0,j=1;
while(i<n) {
while(j>0) {
System.out.print("* ");
j--;
}
System.out.println();
i++;
j=i+1;
}
}
}

Output:
PROGRAM

Aim: Write a program to find if the given number is palindrome or not.

Theory: A palindrome number is a number that is same after reverse. For example 545, 151, 34543, 343,
171, 48984 are the palindrome numbers.

Source Code:

import java.util.Scanner;

public class Q9 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the number- ");
long n1=s.nextLong();
long temp=n1;
long n2=0;
while(n1>0) {
n2=(n1%10)+n2*10;
n1=n1/10;
}
if (temp==n2) {
System.out.println(temp +" is a palindrome number");
}
else {
System.out.println(temp +" is not a palindrome number");
}
}
}

Output:
PROGRAM

Aim: Initialize an integer array with ASCII values and print the corresponding character values in a single
row.

Theory: ASCII stands for American Standard Code for Information Interchange. ASCII is a standard
data-transmission code that is used by the computer for representing both the textual data and control
characters. ASCII is a 7-bit character set having 128 characters, i.e., from 0 to 127. ASCII represents a
numeric value for each character, such as 65 is a value of A. In our Java program, we need to manipulate
characters that are stored in ASCII. In Java, an ASCII table is a table that defines ASCII values for each
character. It is also a small subset of Unicode because it contains 2 bytes while ASCII requires only one
byte.

Source Code:
class ASCIIToChar {
public static void main(String[] args) {
int[] asciiValues = {65, 66, 67, 68, 69};
for (int i = 0; i < asciiValues.length; i++)
{
System.out.print((char) asciiValues[i] + " ");
}
}
}

Output:
PROGRAM

Aim: Write a program to reverse the elements of a given 2*2 array. Four integer numbers need to be
passed as Command-Line arguments

Theory: The java command-line argument is an argument i.e. passed at the time of running the java
program. The arguments passed from the console can be received in the java program and it can be used
as an input. So, it provides a convenient way to check the behavior of the program for the different values.

Source Code:
class ReverseArray {
public static void main(String[] args) {
int[][] arr = new int[2][2]; // initialize 2x2 array
int index = 0;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
arr[i][j] = Integer.parseInt(args[index]); // get integer values from command-line
arguments
index++;
}
}
System.out.println("Original Array:");
printArray(arr); // print original array
reverseArray(arr); // reverse the array
System.out.println("Reversed Array:");
printArray(arr); // print reversed array
}

// method to reverse the elements of a 2x2 array


public static void reverseArray(int[][] arr) {
int temp = arr[0][0];
arr[0][0] = arr[1][1];
arr[1][1] = temp;
temp = arr[0][1];
arr[0][1] = arr[1][0];
arr[1][0] = temp;
}

// method to print the elements of a 2x2 array


public static void printArray(int[][] arr) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}

Output:
PROGRAM 12

Aim: Create a java program to implement stack and queue concept.

Theory: Stack is a container of objects that are inserted and removed according to the last-in first-out
(LIFO) principle. Queue is a container of objects (a linear collection) that are inserted and removed
according to the first-in first-out (FIFO) principle.

Source Code:
import java.util.LinkedList;

public class StackAndQueue {


public static void main(String[] args) {
LinkedList<Integer> stack = new LinkedList<Integer>();
LinkedList<Integer> queue = new LinkedList<Integer>();

// push elements onto the stack


stack.push(1);
stack.push(2);
stack.push(3);

// add elements to the queue


queue.add(1);
queue.add(2);
queue.add(3);

// print stack and queue


System.out.println("Stack: " + stack);
System.out.println("Queue: " + queue);

// pop an element from the stack


int poppedFromStack = stack.pop();
System.out.println("Popped from stack: " +
poppedFromStack);

// remove an element from the queue


int removedFromQueue = queue.remove();
System.out.println("Removed from queue: " + removedFromQueue);

// print updated stack and queue


System.out.println("Updated stack: " + stack);
System.out.println("Updated queue: " + queue);
}
}
Output:
PROGRAM

Aim: Write a java program to produce the tokens from given long string.

Theory: The string tokenizer class allows an application to break a string into tokens. The tokenization
method is much simpler than the one used by the StreamTokenizer class. The StringTokenizer methods do
not distinguish among identifiers, numbers, and quoted strings, nor do they recognize and skip comments.

Source Code:
import java.util.StringTokenizer;

public class TokenizerExample {


public static void main(String[] args) {
String longString = "This is a long string with many words and spaces";

// create a StringTokenizer object with the long string and space delimiter
StringTokenizer st = new StringTokenizer(longString, " ");

// print the tokens


while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}

Output:
PROGRAM

Aim: Using the concept of method overloading Write method for calculating the area of triangle, circle and
rectangle.

Theory: Method Overloading allows different methods to have the same name, but different signatures
where the signature can differ by the number of input parameters or type of input parameters, or a mixture of
both.

Source Code:

public class AreaCalculator {


public static void main(String[] args) {
double triangleArea = area(5, 8);
System.out.println("Area of triangle: " + triangleArea);

double circleArea = area(4.5);


System.out.println("Area of circle: " + circleArea);

float rectangleArea = (float) area(9.0, 9.0);


System.out.println("Area of rectangle: " +
rectangleArea);
}

// method to calculate the area of a triangle


public static float area(float base, float height) {
float a = (float) (0.5 * base * height);
return a;
}

// method to calculate the area of a circle


public static double area(double radius) {
return Math.PI * radius * radius;
}

// method to calculate the area of a rectangle


public static double area(double length, double width) {
return length * width;
}
}
Output:
PROGRAM 15

Aim: Create a class Box that uses a parameterized constructor to initialize the dimensions of a box. The
dimensions of the Box are width, height, depth. The class should have a method that can return the volume
of the box. Create an object of the Box class and test the functionalities.

Theory: Parameterized constructors in java are the programmer written constructors in a class which have
one or more than one arguments. Parameterized constructors are used to create user instances of objects
with user defined states. There can be more than one parameterized constructor in a class.23-Sept-2022

Source Code:

public class Box {


private double width;
private double height;
private double depth;

// parameterized constructor to initialize the dimensions of the box


public Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}

// method to calculate and return the volume of the box


public double getVolume() {
return width * height * depth;
}

public static void main(String[] args) {


// create an object of the Box class with dimensions 5, 6, 7
Box box = new Box(5, 6, 7);

// calculate and print the volume of the box


double volume = box.getVolume();
System.out.println("Volume of box: " + volume);
}
}
Output:
PROGRAM

Aim: WAP to display the use of this keyword.

Theory: The this keyword refers to the current object in a method or constructor. The most common use of
the this keyword is to eliminate the confusion between class attributes and parameters with the same name
(because a class attribute is shadowed by a method or constructor parameter).

Source Code:

public class Person {


private String name;
private int age;

public Person(String name, int age) {


this.name = name;
this.age = age;
}

public void printInfo() {


System.out.println("Name: " + this.name);
System.out.println("Age: " + this.age);
}

public static void main(String[] args) {


Person person = new Person("Sachita", 25);
person.printInfo();
}
}

Output:
PROGRAM

Aim: Write a program that can count the number of instances created for the class.

Theory: In Java, the number of instances refers to the number of objects created from a class. Each time
you create a new object from a class, you are creating a new instance of that class.

Source Code:

public class MyClass {


private static int count = 0;

public MyClass() {
count++;
}

public static int getCount() {


return count;
}

public static void main(String[] args) {


MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
MyClass obj3 = new MyClass();
System.out.println("Number of instances created: " + MyClass.getCount());
}
}

Output:
PROGRAM

Aim: Java Program to get the cube of a given number using the static method.

Theory: What is a Static Method in Java? A static method is a method that belongs to a class rather than an
instance of a class. This means you can call a static method without creating an object of the class. Static
methods are sometimes called class methods.

Source Code:

public class Cube {


public static int getCube(int num) {
return num * num * num;
}

public static void main(String[] args) {


int number = 5;
int cube = Cube.getCube(number);
System.out.println("Cube of " + number + " is " + cube); // output: Cube of 5 is 125
}
}

Output:
PROGRAM

Aim: Write a program that implements method overriding

Theory: If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in Java. In other words, If a subclass provides the specific implementation of the method
that has been declared by one of its parent class, it is known as method overriding.

Source Code:
class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}

class Cat extends Animal {


@Override
public void makeSound() {
System.out.println("Meow!");
}
}

class Main {
public static void main(String[] args) {
Animal animal = new Animal();
Cat cat = new Cat();

animal.makeSound();
cat.makeSound();
}
}

Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy