Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
48 views

Java Prog

The document contains 10 code snippets demonstrating various Java programming concepts like arithmetic operators, control flow statements, methods, classes, arrays, inheritance, polymorphism etc. Each code snippet is followed by its sample output. The concepts covered include if-else conditional statements, for loops, constructors, method overloading, single inheritance, exception handling, abstract classes, interfaces etc.

Uploaded by

Mallari Sudha
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Java Prog

The document contains 10 code snippets demonstrating various Java programming concepts like arithmetic operators, control flow statements, methods, classes, arrays, inheritance, polymorphism etc. Each code snippet is followed by its sample output. The concepts covered include if-else conditional statements, for loops, constructors, method overloading, single inheritance, exception handling, abstract classes, interfaces etc.

Uploaded by

Mallari Sudha
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 42

/****Write a java program on Arithemetic Operators ********/

public class OperatorExample{  

public static void main(String args[]){  

int a=10;  

int b=5;  

System.out.println(a+b);//15  

System.out.println(a-b);//5  

System.out.println(a*b);//50  

System.out.println(a/b);//2  

System.out.println(a%b);//0  

Output:

15
5
50
2
0
/*** Write a java program to check whether the given year is leap or not ******/

import java.util.Scanner;
public class LeapYear {
public static void main(String[] args){
int year;
System.out.println("Enter an Year :: ");
Scanner sc = new Scanner(System.in);
year = sc.nextInt();

if (((year % 4 == 0) && (year % 100!= 0)) || (year%400 == 0))


System.out.println("Specified year is a leap year");
else
System.out.println("Specified year is not a leap year");
}
}

Output:

Enter an Year ::

2020

Specified year is a leap year


/*** Write a java program to find the largest of three numbers *****/

public class JavaExample{


public static void main(String[] args) {
int num1 = 10, num2 = 20, num3 = 7;
if( num1 >= num2 && num1 >= num3)
System.out.println(num1+" is the largest Number");

else if (num2 >= num1 && num2 >= num3)


System.out.println(num2+" is the largest Number");

else
System.out.println(num3+" is the largest Number");
}
}

Output:
20 is the largest Number
/*** Write a java program to find the reverse of a given number ****/

class ReverseNumberDemo

public static void main(String args[])

int num=123456789;

int reversenum =0;

while( num != 0 )

reversenum = reversenum * 10;

reversenum = reversenum + num%10;

num = num/10;

System.out.println("Reverse of specified number is: "+reversenum);

Output:

Reverse of specified number is: 987654321


/*** Write a java program to check whether the given number is prime or not ***/

public class PrimeExample{    

 public static void main(String args[]){    

  int i,m=0,flag=0;      

  int n=3;//it is the number to be checked    

  m=n/2;      

  if(n==0||n==1){  

   System.out.println(n+" is not prime number");      

  }else{  

   for(i=2;i<=m;i++){      

    if(n%i==0){      

     System.out.println(n+" is not prime number");      

     flag=1;      

     break;      

    }      

   }      

   if(flag==0)  { System.out.println(n+" is prime number"); }  

  }//end of else  

}    

Output:

3 is prime number
/*** Write a java program to print Fibonacci Series ********/

class FibonacciExample1{  

public static void main(String args[])  

{    

 int n1=0,n2=1,n3,i,count=10;    

 System.out.print(n1+" "+n2);//printing 0 and 1    

    

 for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed    

 {    

  n3=n1+n2;    

  System.out.print(" "+n3);    

  n1=n2;    

  n2=n3;    

 }    

  

Output:

0 1 1 2 3 5 8 13 21 34 
/*** Write a java program to check whether the given number is palindrome or
not ****/

class PalindromeExample{

public static void main(String args[]){

int r,sum=0,temp;

int n=454;//It is the number variable to be checked for palindrome

temp=n;

while(n>0){

r=n%10; //getting remainder

sum=(sum*10)+r;

n=n/10;

if(temp==sum)

System.out.println("palindrome number ");

else

System.out.println("not palindrome");

Output:

palindrome number
/*** Write a java program on switch case to display month*******/

public class SwitchMonthExample {


public static void main(String[] args) {
//Specifying month number
int month=7;
String monthString="";
//Switch statement
switch(month){
//case statements within the switch block
case 1: monthString="1 - January";
break;
case 2: monthString="2 - February";
break;
case 3: monthString="3 - March";
break;
case 4: monthString="4 - April";
break;
case 5: monthString="5 - May";
break;
case 6: monthString="6 - June";
break;
case 7: monthString="7 - July";
break;
case 8: monthString="8 - August";
break;
case 9: monthString="9 - September";
break;
case 10: monthString="10 - October";
break;
case 11: monthString="11 - November";
break;
case 12: monthString="12 - December";
break;
default:System.out.println("Invalid Month!");
}
//Printing month of the given number
System.out.println(monthString);
}
}

Output:

7 - July
/*** Write a java program to print the elements of a given array *****/

public class PrintArray {

public static void main(String[] args) {

//Initialize array

int [] arr = new int [] {1, 2, 3, 4, 5};

System.out.println("Elements of given array: ");

//Loop through the array by incrementing value of i

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

System.out.print(arr[i] + " ");

Output:

Elements of given array:

1 2 3 4 5
/*** Write a java program to find the sum of elements in the given array ****/

public class SumOfArray {

public static void main(String[] args) {

//Initialize array

int [] arr = new int [] {1, 2, 3, 4, 5};

int sum = 0;

//Loop through the array to calculate sum of elements

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

sum = sum + arr[i];

System.out.println("Sum of all the elements of an array: " + sum);

Output:

Sum of all the elements of an array: 15


/*** Write a java program to sort the elements in the given array *****/
public class SortAsc {
public static void main(String[] args) {

//Initialize array
int [] arr = new int [] {5, 2, 8, 7, 1};
int temp = 0;

//Displaying elements of original array


System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}

//Sort the array in ascending order


for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

System.out.println();
//Displaying elements of array after sorting
System.out.println("Elements of array sorted in ascending order: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
Output:

Elements of original array:

52871

Elements of array sorted in ascending order:

12578
/*** Write a java program on matrix addition *******/

public class MatrixAdditionExample{

public static void main(String args[]){

//creating two matrices

int a[][]={{1,3,4},{2,4,3},{3,4,5}};

int b[][]={{1,3,4},{2,4,3},{1,2,4}};

//creating another matrix to store the sum of two matrices

int c[][]=new int[3][3]; //3 rows and 3 columns

//adding and printing addition of 2 matrices

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

for(int j=0;j<3;j++){

c[i][j]=a[i][j]+b[i][j]; //use - for subtraction

System.out.print(c[i][j]+" ");

System.out.println();//new line

}}

Output:

268

486

469
/*** Write a java program on matrix multiplication *********/

public class MatrixMultiplicationExample{

public static void main(String args[]){

//creating two matrices

int a[][]={{1,1,1},{2,2,2},{3,3,3}};

int b[][]={{1,1,1},{2,2,2},{3,3,3}};

//creating another matrix to store the multiplication of two matrices

int c[][]=new int[3][3]; //3 rows and 3 columns

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

for(int j=0;j<3;j++){

c[i][j]=0;

for(int k=0;k<3;k++)

c[i][j]+=a[i][k]*b[k][j];

System.out.print(c[i][j]+" ");

System.out.println();//new line

}}

Output:

666

12 12 12

18 18 18
/*** Write a java program to read the data from the keyboard ******/

import java.util.Scanner;

public class ReadNumberExample1

public static void main(String[] args)

//object of the Scanner class

Scanner sc=new Scanner(System.in);

System.out.print("Enter a number: ");

//invoking nextInt() method that reads an integer input by keyboard

//storing the input number in a variable num

int num = sc.nextInt();

//closing the Scanner after use

sc.close();

//prints the number

System.out.println("The number entered by the user is: "+num);

Output:

Enter a number: 89

The number entered by the user is: 89


/*** Write a java program to illustrate the usage of command line arguments ***/

class A{

public static void main(String args[]){

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

System.out.println(args[i]);

compile by > javac A.java

run by > java A sonoo jaiswal 1 3 abc

Output: sonoo

jaiswal

abc
/*** Write a java program on Constructors ********/

class Student4{

int id;

String name;

//creating a parameterized constructor

Student4(int i,String n){

id = i;

name = n;

//method to display the values

void display(){System.out.println(id+" "+name);}

public static void main(String args[]){

//creating objects and passing values

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

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

//calling method to display the values of object

s1.display();

s2.display();

Output:

111 Karan

222 Aryan
/*** Write a java program on method Overloading *******/

class Adder{

static int add(int a,int b){return a+b;}

static int add(int a,int b,int c){return a+b+c;}

class TestOverloading1{

public static void main(String[] args){

System.out.println(Adder.add(11,11));

System.out.println(Adder.add(11,11,11));

}}

Output:

22

33
/*** Write a java program on single inheritance ********/

class Employee{

float salary=40000;

class Programmer extends Employee{

int bonus=10000;

public static void main(String args[]){

Programmer p=new Programmer();

System.out.println("Programmer salary is:"+p.salary);

System.out.println("Bonus of Programmer is:"+p.bonus);

output:

Programmer salary is:40000.0

Bonus of programmer is:10000


/*** Write a java program on multilevel inheritance ********/

class Shape {

public void display() {

System.out.println("Inside display");

class Rectangle extends Shape {

public void area() {

System.out.println("Inside area");

class Cube extends Rectangle {

public void volume() {

System.out.println("Inside volume");

public class Tester {

public static void main(String[] arguments) {

Cube cube = new Cube();

cube.display();

cube.area();

cube.volume();

Output:

Inside display
Inside area
Inside volume
/*** Write a java program on Hierarchical inheritance ********/

class Animal{

void eat(){System.out.println("eating...");}

class Dog extends Animal{

void bark(){System.out.println("barking...");}

class Cat extends Animal{

void meow(){System.out.println("meowing...");}

class TestInheritance3{

public static void main(String args[]){

Cat c=new Cat();

c.meow();

c.eat();

//c.bark();//C.T.Error

}}

Output:

meowing...

eating...
/*** Write a java program on Multiple inheritance ********/

interface Printable{

void print();

interface Showable{

void print();

class TestInterface3 implements Printable, Showable{

public void print(){System.out.println("Hello");}

public static void main(String args[]){

TestInterface3 obj = new TestInterface3();

obj.print();

Output:

Hello
/*** Write a java program on Hybrid inheritance ********/

interface read
{
public void reading();
}

interface work
{
public void working();
}

class Employee implements read,work


{
String firstName,lastName;
int age;

public void reading()


{
System.out.println("Employee is reading !!");
}

public void working()


{
System.out.println("Employee is working !!");
}

class HourlyEmployee extends Employee


{
int salary = 5000, hoursWorked;

public int comuptePay()


{
return salary*hoursWorked;
}

public class hybrid


{
public static void main(String[] args)
{
HourlyEmployee emp = new HourlyEmployee();

emp.hoursWorked = 12;
emp.firstName = "John";
emp.lastName = "Smith";
emp.age = 27;

System.out.println(emp.comuptePay());

}
}
Output:

60000
/*** Write a java program on method overriding********/

class Bank{

int getRateOfInterest(){return 0;}

//Creating child classes.

class SBI extends Bank{

int getRateOfInterest(){return 8;}

class ICICI extends Bank{

int getRateOfInterest(){return 7;}

class AXIS extends Bank{

int getRateOfInterest(){return 9;}

//Test class to create objects and call the methods

class Test2{

public static void main(String args[]){

SBI s=new SBI();

ICICI i=new ICICI();

AXIS a=new AXIS();

System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());

System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());

System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());

Output:

SBI Rate of Interest: 8

ICICI Rate of Interest: 7

AXIS Rate of Interest: 9


/*** Write a java program on user defined package ********/

//save as Simple.java

package mypack;

public class Simple{

public static void main(String args[]){

System.out.println("Welcome to package");

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:

Welcome to package
/*** Write a java program on exception handling *********/

public class JavaExceptionExample{

public static void main(String args[]){

try{

//code that may raise exception

int data=100/0;

}catch(ArithmeticException e){System.out.println(e);}

//rest code of the program

System.out.println("rest of the code...");

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero

rest of the code...


/*** Write a java program on exception handling using multiple catch

statements **/

public class MultipleCatchBlock1 {

public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

Output:

Arithmetic Exception occurs

rest of the code


/*** Write a java program to create a thread by extending Thread class ***/

class Multi extends Thread{

public void run(){

System.out.println("thread is running...");

public static void main(String args[]){

Multi t1=new Multi();

t1.start();

Output:

thread is running...
/*** Write a java program to create a thread by implementing Runnable interface
***/

class Multi3 implements Runnable{

public void run(){

System.out.println("thread is running...");

public static void main(String args[]){

Multi3 m1=new Multi3();

Thread t1 =new Thread(m1);

t1.start();

Output:

thread is running...
/*** Write a java program on thread Priorities *******/

class TestMultiPriority1 extends Thread{

public void run(){

System.out.println("running thread name is:"+Thread.currentThread().getName());

System.out.println("running thread priority is:"+Thread.currentThread().getPriority());

public static void main(String args[]){

TestMultiPriority1 m1=new TestMultiPriority1();

TestMultiPriority1 m2=new TestMultiPriority1();

m1.setPriority(Thread.MIN_PRIORITY);

m2.setPriority(Thread.MAX_PRIORITY);

m1.start();

m2.start();

Output:

running thread name is:Thread-0

running thread priority is:10

running thread name is:Thread-1

running thread priority is:1


/*** Write a java program on inter thread communication *****/

class Customer{
int amount=10000;

synchronized void withdraw(int amount){


System.out.println("going to withdraw...");

if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}

synchronized void deposit(int amount){


System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}

class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();

}
}

Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
/*** Write a java program on JDBC *********/

import java.sql.*;

class OracleCon{

public static void main(String args[]){

try{

//step1 load the driver class

Class.forName("oracle.jdbc.driver.OracleDriver");

//step2 create the connection object

Connection con=DriverManager.getConnection(

"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

//step3 create the statement object

Statement stmt=con.createStatement();

//step4 execute query

ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next())

System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

//step5 close the connection object

con.close();

}catch(Exception e){ System.out.println(e);}

You might also like