[Go to site: main page, start]

0% found this document useful (0 votes)
19 views18 pages

Java Programs: Basic Constructs and Examples

The document contains 13 code examples demonstrating various Java programming concepts like checking if a number is prime, counting even numbers, temperature conversion, checking if a number is Armstrong, bitwise operators, finding numbers divisible by 7, checking if a number is even/odd, calculating factorials, using Math functions, checking if a number is palindrome, calculating sum of digits, reversing a number, calculating percentage and total marks. The code examples are grouped under two chapters - basic syntactical constructs and derived syntactical constructs, with the latter including examples of constructors and command line arguments.

Uploaded by

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

Java Programs: Basic Constructs and Examples

The document contains 13 code examples demonstrating various Java programming concepts like checking if a number is prime, counting even numbers, temperature conversion, checking if a number is Armstrong, bitwise operators, finding numbers divisible by 7, checking if a number is even/odd, calculating factorials, using Math functions, checking if a number is palindrome, calculating sum of digits, reversing a number, calculating percentage and total marks. The code examples are grouped under two chapters - basic syntactical constructs and derived syntactical constructs, with the latter including examples of constructors and command line arguments.

Uploaded by

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

JAVA PROGRAMS

Chap-1 Basic Systactical Construct in Java


1)WAP to check Whether No. is Prime Or Not.
Code:
import [Link].*;
class prime{
public static void main(String arg[]) {
int no,m,flag=0;
Scanner s=new Scanner([Link]);
[Link]("\nEnter Any No.=");
no=[Link]();
m=no/2;
for(int i=2;i<=m;i++) {
if(no%i==0) {
[Link](+no+" is Not Prime");
flag=1;
break;
}
}
if(flag==0) {
[Link](+no+" is Prime"); }
}
}
Output:

2)WAP to To Claculate Even No. from Larg Integer No.


Code:
import [Link].*;
class CountEveno {
public static void main(String arg[]) {
int no,rem,count=0;
Scanner s=new Scanner([Link]);
[Link]("\nEnter Any No.=");
no=[Link]();
while(no!=0) {
rem=no%10;
if(rem%2==0) {
++count;
}
no=no/10;

}
[Link]("The Total Even No. Present in "+no+" is="+count);
}
}
Output:

3)WAP to Convert FaCelcius Temp into Faherheit using Formula(F= (C * 1.8) +32).
Code:
import [Link].*;
class ConvertTemp{
public static void main(String arg[]) {
int cel;
float fah;
Scanner s=new Scanner([Link]);
[Link]("\nEnter Celsius Tempreture=");
cel=[Link]();
fah=(float)(cel*1.8)+32;
[Link]("After Converting Fahreheit="+fah+"'F");
}
}
Output:
4)WAP To Check Whether No. is Armstrom Or Not.
Code:
import [Link].*;
class aram1 {
public static void main(String arg[]) {
int n,sum=0,rem,temp;
[Link]("Enter no:");
Scanner s=new Scanner([Link]);
n=[Link]();
temp=n;
while(n!=0) {
rem=n%10;
sum=sum+(rem*rem*rem);
n=n/10;
}
if(temp==sum) {
[Link]("no is Armastrong:");
}
else {
[Link]("no is not Armastrong:");
}
}
}
Output:

5)WAP to Perform Bitwise Oprator.


Code:
import [Link].*;
class bitwise1 {
public static void main(String arg[]) {
int a=60;
int b=13;
int c=0;
c=a&b;
[Link]("\n a&b="+c);
c=a^b;
[Link]("\n a^b="+c);
c=~a;
[Link]("\n ~a="+c);
c=a<<2;
[Link]("\n a<<2="+c);
c=a>>>2;
[Link]("\n a>>>2="+c);
}
}
Output:

6)WAP to Print No. Divisible By 7 100 To 200.


Code: import [Link].*;
class NoDivBy7
{
public static void main(String abc[])
{
int i=7;
for(i=100;i<=200;i++)
{
if(i%7==0)
{
[Link](+i);
}
}
}
}
Output:

7)WAP To Check Whether No. is Even Or Odd.


Code:
//import [Link].*;
class EvenOdd {
public static void main(String abc[])
{
int a;
Scanner s=new Scanner([Link]);
[Link]("Enter any Number :");
a=[Link]();
if(a%2==0)
{
[Link]("Number is even!!");
}
else
{
[Link]("Number is odd!!");
}

}
}
Output:
8)WAP to Calculate Factorial of No.
import [Link].*;
class fact
{
public static void main(String abc[])
{
int no,i,fact=1;
Scanner s=new Scanner([Link]);
[Link]("Enter any number :");
no=[Link]();
for(i=1;i<=no;i++)
{
fact=fact*i;
}
[Link]("Factorial :"+fact);
}
}
Output:

9)WAP Implement Math Function.


Code:class MathFunction{
public static void main(String arr[]) {
double a=10,b=16;
double z=1.8,x=-90;
double l=[Link](a,b);
double q=[Link](a,b);
double p=[Link](b);
double r=[Link](z);
double o=[Link](x);
double m=[Link](a);
double v=[Link](a);
[Link]("MIN()="+l);
[Link]("MAX()="+q);
[Link]("SQRT()="+p);
[Link]("ROUND()="+r);
[Link]("ABS()="+o);
[Link]("EXP()="+m);
[Link]("ASIN()="+v);
}
}
Output:

10)WAP To Check Whether No. is Palindrom Or Not.


Code: import [Link].*;
class palindrome {
public static void main(String arg[]) {
int n,rev=0,rem,temp;
[Link]("Enter no:");
Scanner s=new Scanner([Link]);
n=[Link]();
temp=n;
while(n!=0) {
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
if(temp==rev) {
[Link]("no is palindrome!!"+rev);
}
Else {
[Link]("no is not palindrome!!"+rev);
}
}
}
Output:

11)WAP to Calculate Sum of Digit.


Code:
import [Link].*;
class Sum_of_Digit
{
public static void main(String abc[])
{
int no,rem,sum=0;
[Link]("Enter any Number :");
Scanner s=new Scanner([Link]);
no=nextInt();
while(no!=0)
{
rem=no%10;
sum=sum+rem;
no=no/10;
}
[Link]("Sum="+sum);
}
}
Output:

12)WAP To Reverse the entred No.


Code:
import [Link].*;
class Reverse1
{
public static void main(String abc[])
{
int no,rem,sum=0;
[Link]("Enter any Number :");
Scanner s=new Scanner([Link]);
no=[Link]();
while(no!=0)
{
rem=no%10;
sum=sum*10+rem;
no=no/10;
}
[Link]("Reverse="+sum);
}
}
Output:

13)WAP to Calculate Percentage & Total Marks.


Code:
import [Link].*;
class student {
public static void main(String args[]) {
int s1,s2,s3,s4,s5,total;
float avg;
Scanner sc=new Scanner([Link]);
[Link]("Enter the english marks:");
s1=[Link]();
[Link]("Enter the maths marks :");
s2=[Link]();
[Link]("Enter the scince marks :");
s3=[Link]();
[Link]("Enetre the physcice marks:");
s4=[Link]();
[Link]("Enetr the Java marks:");
s5=[Link]();
total=(s1+s2+s3+s4+s5);
avg=(float)total/5;
[Link]("*****************************");
[Link]("********STUDENT INFO*********");
[Link]("******************************");
[Link]("English :"+s1);
[Link]("Maths :"+s2);
[Link]("science :"+s3);
[Link]("Physcice :"+s4);
[Link]("Java :"+s5);
[Link]("=================================");
[Link]("show totale="+total);
[Link]("show Average="+avg+"%");

}
}
Output:

Chap-2 Derived Syntatical Constructor in Java.


1)WAP to Implement Constructor in Java.
Code:
import [Link].*;
class demo1 {
int a,b,c;
demo1() {
Scanner sc=new Scanner([Link]);
[Link]("\nEnter 2 No.=");
a=[Link]();
b=[Link]();

}
void display() {
c=a+b;
[Link]("\nAddition="+c);
}
}
class Constuctor {
public static void main(String arg[]) {
demo1 d=new demo1();
[Link](); }
}
Output:

2)WAP to Show Overloading of Constructor.


Code:
class demo1 {
int a,b,c;
demo1() {
a=100;
b=200;
c=a+b;
}
demo1(int x) {

a=x;
b=100;
c=a+b;

}
demo1(int x,int y) {

a=x;
b=y;
c=a+b;
}

void display() {
c=a+b;
[Link]("\nAddition="+c);
}

public static void main(String arg[]) {


demo1 d=new demo1();
demo1 d1=new demo1(100);
demo1 d2=new demo1(500,700);

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

}
}
Output:

3)WAP to get Command line argument & perform addition


Code:
class command_line

{
public static void main(String arg[])
{
String s1=arg[0];
String s2=arg[1];
int a=[Link](s1); //int a=[Link](arg[0]);
int b=[Link](s2); // int b=[Link](arg[1]);
int c;
c=a+b;
[Link]("\nAddition ="+c);
}
}
Output:

4)WAP to accept No. from Command line & check No. is Prime Or Not.
Code:
class Prime
{
public static void main(String arg[]) {
int a=[Link](arg[0]);
int m,flag=0;
m=a/2;
for(int i=2;i<=m;i++) {
if(a%2==0)
{
[Link]("\n"+a+" No. is Not Prime");
flag=1;
break;
}
}
if(flag==0)
[Link]("\n"+a+" No. is Prime");

}
}
Output:
5)) “this” Keyword
1)WAP to Show Use of “this” keyword as hiding instance variable .
Code: class This_demo1 {
int a,b,c;
This_demo1(int a,int b) {
this.a=a;
this.b=b;
c=a+b;
}
void display() {
c=a+b;
[Link]("\nAddition="+c);
}
public static void main(String arg[]) {

This_demo1 d2=new This_demo1(500,700);


[Link]();
}
}

2) WAP to Show Use of “this” keyword as Calling Constructor using another Constructor.
Code: class This_demo2 {
int a,b,c;
This_demo2 () {
a=100;
b=200;
c=a+b;
}
This_demo2(int z) {
a=z;
b=100;
c=a+b;
}
This_demo2(int x,int y,int z) {
this(z);
a=x;
b=y;
c=a+b;
}
void display() {
c=a+b;
[Link]("\nAddition="+c);
}
public static void main(String arg[]) {
demo1 d=new demo1();
demo1 d1=new demo1(1000);
demo1 d2=new demo1(500,700);
[Link]();
[Link]();
[Link]();
}
}
Output:

3) WAP to demonstreat Outer & Inner Class.


Code:
class outerinnerclass{
class inner{
void show(){
[Link]("Inner Class");
}

}
void display(){
[Link]("Outer Class");
inner i=new inner();
[Link]();
}
public static void main(String arg[]){
outerinnerclass o=new outerinnerclass();
[Link]();
}
}
output:

4)WAP to
demonstreat Outer & Inner Class(Outside the class).
code:
class outerinnerclass1{
static class inner{
void show(){
[Link]("Inner Class");
}

}
void display(){
[Link]("Outer Class");
}
}
class demo{
public static void main(String arg[])
{
outerinnerclass1 o=new outerinnerclass1();
[Link]();
[Link] i=new [Link]();
[Link]();
}
}
output:

5)

Common questions

Powered by AI

In Java, bitwise shifting involves moving bits across positions. The left shift ('<<') moves bits to the left, inserting zeros on the right, effectively multiplying the number by 2 for each shift. The unsigned right shift ('>>>') moves bits to the right, inserting zeros on the left, effectively dividing the number by powers of 2. From Source 1, 'a<<2' multiplies 'a' (60) by 4 resulting in 240, and 'a>>>2' divides it by 4 yielding 15. These operations are efficient for binary computations like graphics processing or cryptography requiring bit-level control .

Constructor overloading in Java allows a class to have multiple constructors with different parameters, enabling flexible object initialization. From Source 2, the 'demo1' class exemplifies this with three constructors: one with no parameters, one with a single parameter, and one with two parameters. This is beneficial when objects require diverse initial states. For example, in a practical payroll system, such constructor overloading allows initialization of an employee object with default values, values based on partial data (e.g., just ID), or complete data (ID and initial salary), enhancing code flexibility and reuse .

Inner classes in Java enable logically grouping classes that are only used in one place, increasing encapsulation and readability. According to the examples in Source 3, the 'inner' class is used to demonstrate functionality within the 'outerinnerclass'. A real-world application scenario could be a graphical user interface with nested classes representing components like panels and buttons, encapsulating event handling within the component class itself, thus reducing inter-class dependencies and improving maintainability .

The approach to check for an Armstrong number involves calculating the sum of the cubes of its digits and comparing it with the original number. The implementation in Source 1 uses a while loop to achieve this. To optimize, one could pre-calculate powers of digits to avoid repeated calculations within the loop, thus improving performance for large numbers. Additionally, using an integer array to store digits might also streamline operations, making the check not only computationally less expensive but also clearer in intent and execution .

In Java, the 'this' keyword is used to refer to the current instance of a class, helping to resolve variable scope issues. Specifically, in constructors, it differentiates between instance variables and parameters with the same name. For example, in the constructor 'This_demo1(int a, int b)' found in Source 2, 'this.a = a;' and 'this.b = b;' assign the parameter values to instance variables distinctly, preventing ambiguity .

When checking if a number is prime from the command line in Java, potential mistakes include incorrect parsing of command line arguments and logical errors in the prime-checking algorithm. The code snippet from Source 2 mistakenly checks 'if (a%2==0)' instead of checking divisibility by all integers up to 'm' (half of 'a'), which leads to incorrect prime identification . Ensuring correct parsing using Integer.parseInt and correcting the logic to 'if (a%i==0)' could mitigate such mistakes.

Using incorrect logical statements in bitwise operations can lead to unintended behavior and incorrect results. In Java, bitwise operators perform operations on individual bits of integer types. For instance, using AND ('&') ensures both bits must be 1 for the result to be 1. From Source 1, the example 'c = a & b;' correctly demonstrates AND operation resulting in 'a&b=12' for 'a=60' and 'b=13', whereas a mistake in logic would yield incorrect results or errors during execution. Such precision is crucial in logical AND operations where intended binary manipulation is required .

The use of command line arguments allows programs to receive input directly when executed, enabling dynamic execution without code modification. The Java programs provided use such arguments for prime checking and addition, as seen in Source 2. This enhances functionality by allowing users to supply varying inputs easily, making the program versatile for tasks like batch processing or parameterized testing. Additionally, it facilitates automating scripts within operating systems that pass arguments to execute with different data sets .

Error handling in Java is crucial to ensure robustness, especially when dealing with user inputs. In the provided programs, user input is handled using Scanners without apparent error handling. This can lead to issues like InputMismatchException if a non-integer is entered where an integer is expected . Implementing try-catch blocks can capture and manage such errors, prompting users for correct input formats and maintaining program flow without abrupt termination. Thus, error handling enhances the user interface and stability of applications.

Not handling I/O exceptions in Java can lead to program crashes and user inconvenience, especially when dealing with inputs and outputs. The programs provided lack explicit error handling, risking runtime exceptions such as FileNotFoundException or IOException . Mitigating such risks involves incorporating try-catch blocks to catch these exceptions, providing meaningful error messages, or attempting corrective measures. This approach not only ensures program stability but also improves user experience by guiding users through proper input methods and recovering from errors seamlessly.

You might also like