Basics of CPP Programs

In this post you will learn fundamental C++ programs. These programs for freshers or beginners.

1 .write a cpp program to display hello world message
#include<iostream.h>
int main()
{
count<<"Hello World\n";
//prints Hello World on user screen
return 0;
}

Output:

Hello World

2. cpp program to use cout and cin

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();

int a,b,s;

cout<<"enter first num:";
cin>>a;
cout<<"enter second num:";
cin>>b;

s=a+b;

cout<<"\n sum= ";
cout<<s;

getch();
}

output:
Enter first Num:10
Enter second Num:20
sum=30

3. write a cpp program to use variables

#include<iostream.h>
using namespace std;

int main()
{
//defination of variables
int a,b,c;
float d;

//initialization of variables

a=5;
b=10;
c=a+b;

cout<<c<endl;

d=15.0/4.0;
cout<<d<<endl;

return 0;
}

output:
15
3.75

4 CPP program to swap two numbers using thrid variable

#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();

int a,b,temp;

cout<<"\n enter two numbers :";
cin>>a>>b;

cout<<"\n a="<<a<<",b="<<b;

temp=a;
a=b;
b=temp;

cout<<"\n a=" <<a",b="<<b;

getch();
}
Output:
enter two numbers: 10 20
a=10,b=20
a=20,b=10

5.CPP program to swap two numbers without thrid variable
#include<iostream.h>
#include<conio.h>

void main()
{


int a,b;
clrscr();

cout<<"enter the value of a and b:"<<endl;
cin>>a>>b;

cout<<"before swap:\n"<<"A:"<<a<<"\n B:<<b<<endl;
a=a+b;
b=a-b;
a=a-b;
cout<<"after swap:\n"<<"A:"<<a<<"\n B:<<b<<endl;

getch();
}
Output:
Enter the value of a and b:
10 20
before swap:
A:10
B:20
after swap:
A:20
B:10


Switch case programs using C

In this post you will learn switch case programs using C programming language.The control statement that allows us to make a decision from the number of choices is called a  switch statement.

C program to find day using switch case

#include<stdio.h>
#include<conio.h>
void mian()
{
int day;
clrscr();
printf("enter day number:");
scanf("%d",&day);
switch(day)
{
case 1:

               printf("monday");
               break;
case 2:

               printf("Tuesday");
               break;
case 3:

               printf("Wednesday");
               break;
case 4:

               printf("Thursday");
               break;
case 5:

               printf("Friday");
               break;
case 6:

               printf("Saturday");
               break;
case 7:

               printf("Sunday");
               break;
default:
              printf("invalid day");
             
}
Output:
Enter day number: 4
Thursday

Example 2:

#include<stdio.h>
void main( )
{
    int a, b, c, choice;
    while(choice != 3)
    {
        /* Printing the available options */
        printf("\n 1. Press 1 for addition");
        printf("\n 2. Press 2 for subtraction");
        printf("\n Enter your choice");
        /* Taking users input */
        scanf("%d", &choice);
     
        switch(choice)
        {
            case 1:
                printf("Enter two numbers");
                scanf("%d%d", &a, &b);
                c = a + b;
                printf("%d", c);
                break;
            case 2:
                printf("Enter two numbers");
                scanf("%d%d", &a, &b);
                c = a - b;
                printf("%d", c);
                break;
            default:
                printf("you have passed a wrong key");
                printf("\n press any key to continue");
        }
    }
}
Output:
Enter your choice: 1
Enter two numbers 10 20
30


Example 3:

int main()
{
int i;
printf("enter an integer");
scanf("%d",&i);
switch(i)
{
case 1: printf("one");
            break;
case 2: printf("two");
            break;
case 3: printf("three");
            break;
case 4: printf("four");
             break;
default: printf("invalid number");
}
return 0;
}

Output:
Enter an integer: 3
three






Java Exception Handling programs

A Java Exception is an object that describes the exceptional condition that has occurred in a piece of code. These Exceptions handling is managed by try,catch,throw,throws and finally.In this article,we will learn some exception handling java programs which are frequently asked in the technical written Test  and interview room also. Exception means runtime errors,it is an unexpected unwanted event which disturbs entire flow of the program. If we are not handling exception,the program may terminate abnormally without releasing allocated resource. You must notice one thing about Exception concept, Exception handling means we are not repairing exception we are providing alternative way to continue the program normally.

1) Java Program for NullPointerException:

It is the child class or Runtime Exception and it is unchecked,thrown automatically by the JVM whenever we are performing any operation on null.
 
Program:
class Exception1
{
public static void main(String args[])
{
try{
String s=null;
System.out.println(s.length());
}
catch(NullPointerException e)
{
System.out.println("NullPointerException");
}
}
Output:
javac Exception1.java
java Exception1
NullPointerException

.Program 2: ArrayIndexOutOfBoundsException

class Exception2
{
public static void main(String args[]){
try{
int arr[]=new int[10];//here array has 10 elements only
arr[11]=8;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBoundsException");
}
}
}
Output:

javac Excpetion2.java
java Exception2
ArrayIndexOutOfBoundException

Program 3: StringIndexOutOfBoundException

class StringException
{
public static void main(String args[])
{
try{
String s="hello lucky";
System.out.println(s.length());
char c=s.charAt(0);
c=s.charAt(30);
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e)
{
System.out.println("StringIndexOutOfBoundException");
}
}
}
Output: 
javac StringException.java
java StringException
StringIndexOutOfBoundException

Program 4: NumberFormatException

class NumberFormat
{
public static void main(String args[])
{
try{
int num=Integer.parseInt("abc");
System.out.println(num);
}
catch(NumberFormatException e)
{
System.out.println("NumberFormatException");
}
}
}
Output: 
javac NumberFormat.java
java NumberFormat
NumberFormatException

Program 5:  How to throw an already defined exception using throw keyword 
class Exception5
{
static int sum(int num1, int num2)
{
if(num1==0)
throw new ArithmeticException("First parameter is not valid");
else
System.out.println("both parameters are correct");
return num1+num2;
}
public static void main(String args[])
{
int res=sum(0,16);
System.out.println(res);
}
}
Output:






Program 6: How to throw your own Exception explicitly using throw

class MyOwnException extends Exception
{
public MyOwnException(String msg)
{
super(msg);
}
}
class Exception6
{
static void employeeAge(int age)
throws MyOwnException
{
if(age<0)
throw new MyOwnException("Age can not be less than zero");
else
System.out.println("input is valid");
}
public static void main(String args[])
{
try
{
employeeAge(-3);
}
catch(MyOwnException e)
e.printStackTrace();
}
}
}
Output:




Program 7 : Multiple catch Blocks
class Exception7
{
public static void main(String args[])
{
try{
int a[]=new int[9];
a[4]=20/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e)
{
System.out.println("Warning ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Warning ArrayIndexOutOfBoundsException");
}
catch(Exception e)
{
System.out.println("Warning some other exception");
}
System.out.println("out of try-catch block");
}
}
Output: 




Program 8: Java finally block
class FinallyDemo
{
public static void main(String args[])
{
System.out.println(FinallyDemo.m());
}
public static int m()
{
try
{
return 99;
}
fianlly
{
System.out.println("this is finally block");
System.out.println("finally block ran even after return statement");
}
}
}

Output:




Program 9: Nested try block
class NestedTry
{
public static void main(String args[])
{
//parent try block
try{
//child try block1
try{
System.out.println("inside block1");
int a=55/0;
System.out.println(a);
}
catch(ArithmeticException e1)
{
System.out.println("Excepiton: e1");
}
//child try block2
try
{
System.out.println("inside block2");
int a=55/0;
System.out.println(a);
}
catch(ArrayIndexOutOfBoundsException e2)
{
System.out.println("Excepiton: e2");
}
System.out.println("other statement");
}
catch(ArithmeticException e3)
{
System.out.println("ArithmeticException");
System.out.println("inside parent try catch block");
}
catch(ArrayIndexOutOfBoundsException e4)
{
System.out.println("ArrayIndexOutOfBoundsExcepton");
System.out.println("insdie parent try catch block");
}
catch(Exception e5)
{
System.out.println("Exception");
System.out.println("inside parent try catch block");
}
System.out.println("next statement");
}
}


Output:






Program 10: How to handle run time exceptions

class NeverCaught
{
static void m()
{
throw new RuntimeException("from m()");
}
static void n()
{
m();
}
public static void main(String args[])
{
n();
}
}
Output:

JavaScript program for Password Validation

In this post you will learn how to check Password validation using JavaScript.This type of code usually use for every Register form.

<html>
<head>
<title> javascript for password validation</title>
<script>
function password_valid()
{
var password=document.myform.password.value;
if(password==null||password=="")
{
alert("password can not be blank");
return false;
}
else if(password.length<8)
{
alert("password must be at least 8 characters long");
return false;
}
}
</script>
<body>
<form name="myform"method="post"action="#"onsubmit="return password_valid()">
Enter password:<input type="password"name="password">
                          <input type="submit"value="submit">
</form>
</body>
</html>
Output:


java program to find fibonacci series

In this post you will learn what is Fibonacci series and how to write code for that using java programming.

Fibonacci:

Fibonacci series is the series of numbers where each number is obtained by adding two previous numbers. The first two numbers in the Fibonacci series are either 1 and 1 or 0 and 1.

Example: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89……..

Program1:

class Fibonacci{
public static void main(String args[])
{
int prev, next, sum, n;
prev=next=1;
for(n=1;n<=10;n++){
System.out.println(prev);
sum=prev+next;
prev=next;
next=sum;
}
}
}
OUTPUT:
javac Fibonacci.java
java Fibonacci
1 1 2 3 5 8  13 21 34 55

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 Number :");
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));
}
}
}

OUTPUT:
javac Fibonacci.java
java Fibonacci
Enter fibonacci Number:
10
0 1 1 2 3 5 8 13 21 34

Java Program to find String is Palindrome or not

In this post you will learn to find String is Palindrome or not. Frequently asking in technical interview about programming logic.
Definition 1 : If Reverse of String is same as Original One then it is called as String Palindrome.
Definition 2: If String Reads the same backward and forward then it is called String palindrome.

Example: Original String="MADAM"

                   Palindrome String="MADAM" //string is palindrome

                   Original String="lucky"

                   Palindrome String="ykcul"// This is NOT String palindrome


Program 1: This Program is developed using String API.

import java.io.*;

class Palindrome
{
public static void main(String args[]) throws IOException
{
String str;
System.out.println("Enter a string");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
str=br.readLine();
StringBuffer sb=new StringBuffer(str);
String revstr=new String(sb.reverse());
if(revstr.equalsIgnoreCase(str))
System.out.println("String is palindrome");
else
System.out.println("Not a Palindrome String!");
}
}

Output:
Enter a String : MADAM
String is Palindrome;


Program 2: Java Program to find Whether the String is Palindrome or not Using Recursion method.

import java.util.*;

class StringPalindrome{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a String:");
String st=sc.next();
StringPalindrome sp=new StringPalindrome();
String reverseString=sp.reverse(st);
if(st.equalsIgnoreCase(reverseString))
{
System.out.printf("The string is palindrome",st);
}
else
{
System.out.printf("the String is not Palindrome",st);
}
}
//method to return the reverse of string
public String reverse(String str)
{
StringBuilder revStr=new StringBuilder();
for(int i=str.length()-1;i>=0;i--)
{
revStr.append(str.charAt(i));
}
return revStr.toString();
}
}

Output:
Enter a String:   lucky
The String is not Palindrome

Java Program to Multiply 2 matrices

In this program we will take three level nested loop is used to perform the multiplication.First, you have to ask the user to enter the number of rows and columns of the first matrix and then ask to enter the first matrix elements.Again ask the same for the second matrix. Then multiply two matrices and store the multiplication result inside the any variable say res and then print all the matrices as a result


Example:


import java.util.Scanner;
class MatrixExample
{
int m,n,p,q;
int[][] a;
int[][]b;
int[][]c;
public void readData()
{
int i,j;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the order of the matrix A");
m=sc.nextInt();
n=sc.nextInt();
System.out.println("Enter the order of the matrix B");
p=sc.nextInt();
q=sc.nextInt();
if(n!=p)
{
System.out.println("matrix order mismatch for multiplication");
System.exit(0);
}
a=new int[m][n];
b=new int[p][q];
c=new int[m][q];
System.out.println("enter the elements of Matrix A");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
System.out.printf("a[%d][%d]=",i,j);
a[i][j]=sc.nextInt();
System.out.println("\n");
}
System.out.println("enter the elements of Matrix B");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
{
System.out.printf("b[%d][%d]=",i,j);
b[i][j]=sc.nextInt();
System.out.println("\n");
}
}
public void multiply()
{
for(int i=0;i<m;i++)
for(int j=0;j<q;j++)
{
c[i][j]=0;
for(int k=0;k<n;k++)
c[i][j]+=a[i][k]*b[k][j];
}
}
public void printMatrix()
{
for(int i=0;i<m;i++)
{
for(int j=0;j<q;j++)
System.out.printf("%d\t",c[i][j]);
System.out.println("\n");
}
}
public static void main(String []args)
{
MatrixExample obj=new MatrixExample();
obj.readData();
obj.multiply();
System.out.println("The result of multiplication is ");
obj.printMatrix();
}
}
Output:









Java Program to Print Prime Numbers

A Prime Number is a natural number  or positive integer  greater than 1 that has no positive divisors other than 1 and itself.

Examples: 2,3,5,7,11,13,15,17...

Program:


class primeNumber
{
public static void main(String args[]){
int i,s,j;
for(i=2;i<100;i++)
{
s=0;
for(j=2;j<i;j++)
{
if(i%j==0)
{
s=1;
break;
}
}
if(s==0)
{
System.out.println(i);
}
}
}
}                         

Output:
















Explanation:

The logic behind to the above program is all about to divide the number which you want to check whether it is prime or not by the number less than itself continuously and if the reminder of any of these division is zero then that entered number is not a prime.












How to upload Image by using JSP

In this post you will learn how to upload image using JSP and display it on the browser.

first we will create page.jsp

page.jsp:

<%@ page language="java" %>
<HTML>
<HEAD><TITLE>Display file upload form to the user</TITLE></HEAD>
<BODY> <FORM ENCTYPE="multipart/form-data" ACTION="upload.jsp" METHOD=POST>
<br><br><br>
<table border="0" bgcolor=#ccFDDEE>
<tr>
<td colspan="2" align="center"><B>UPLOAD THE FILE</B><center></td>
</tr>
<tr>
<td colspan="2" align="center"> </td>
</tr>
<tr>
<td><b>Choose the file To Upload:</b></td>
<td><INPUT NAME="file" TYPE="file"></td>
</tr>
<tr>
<td colspan="2" align="center"> </td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Send File"> </td>
</tr>
<table>
</FORM>
</BODY>
</HTML>

Now we will develop upload file using jsp:

upload.jsp:

<%@ page import="java.io.*" %>
<%@ page import="java.sql.*" %>
<%!
private byte[] getImage(String filename) {
byte[] result = null;
String fileLocation = filename;
File f = new File(fileLocation);
result = new byte[(int)f.length()];
try {
FileInputStream in = new FileInputStream(fileLocation);
in.read(result);
}
catch(Exception ex) {
System.out.println("GET IMAGE PROBLEM :: "+ex);
ex.printStackTrace();
}
return result;
}
%>
<%
String saveFile="";
String contentType = request.getContentType();
if((contentType != null)&&(contentType.indexOf("multipart/form-data") >= 0)){
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while(totalBytesRead < formDataLength){
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
File ff = new File(saveFile);
FileOutputStream fileOut = new FileOutputStream(ff);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();

response.reset();
response.setHeader("Content-Disposition", "inline");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Expires", "0");
response.setContentType("image/jpg");
byte[] image = getImage(saveFile);
OutputStream outputStream = response.getOutputStream();
outputStream.write(image);
outputStream.close();
}
%>

How to create a table by using loop in java

In this post you will learn how to print a table using while loop. As we know looping statements are used to repeat a statement until the specified the condition becomes false.

Now we will see the the example of this program;

class  Table{
public static void main(String[] args) {
int a=10, b=1;
System.out.println("the table of "+a+"= ");
while(b<=10){
int c = a*b;
System.out.println(c);
b = b+1;
}
}
}

Output:
javac Table.java
java Table
the table of 10=
10*1=10
10*2=20
10*3=30
10*4=40
10*5=50
10*6=60
10*7=70
10*8=80
10*9=90
10*10=100

Java Array programs

In this post you will learn some basic and advanced Array programs.These programs will helpful while attend the Technical written Test and Technical Interviews in IT industry.

1. Java Program to read array from keyboard

import java.util.*;
class ArrayList
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int i;
int a[]=new int[5];
for(i=0;i<5;i++)
{
System.out.println("enter value:");
a[i]=sc.nextInt();
}
System.out.println("\n array elements are:");
for(i=0;i<5;i++)
{
System.out.println(" "+a[i]);
}
}
}
Output:
enter value: 10
enter value:20
enter value:30
enter value:40
enter value:50
array elements are:
10 20 30 40 50

2. Java Program sum elements of array

class SumeOfArray
{
public static void main(String args[])
{
int a[]=new int[5];
int i,sum=0;
a[0]=2;
a[1]=3;
a[2]=4;
a[3]=4;
a[4]=3;
for(i=0;i<a.length;i++)
{
sum=sum+a[i];
}
System.out.println("sum is:"+sum);
}
}
Output:
Sum is: 18

3.Java Program to sort elements of Array

import java.util.Arrays;
import java.util.Comparator;
class ArraysSortDemo
{
public static void main(String args[])
{
int [] a={10,5,20,11,6};
System.out.println("primitive array before sorting:");
for(int a1:a)
{
System.out.println(a1);
}
Arrays.sort(a);
System.out.prinltn("primitive array after sorting");
for(int a1:a)
{
System.out.println(a1);
}
String[] s={"A","Z","B"};
System.out.println("object array before sorting");
for(String a2:s)
{
System.out.println(a2);
}
Arrays.sort(s);
System.out.println("object array after sorting");
for(String a1:s)
{
System.out.println(a1);
}
Arrays.sort(s,new MyComparator());
System.out.println("object array after sorting by comparator:");
for(String a1:s)
{
System.out.println(a1);
}
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=o1.toString();
String s2=o2.toString();
return s2.compareTo(s1);
}
}
Output: 
10
5
20
11
6
Primitive array after sorting
5
6
10
11
20
Object array before sorting
A
Z
B
Object array after sorting
A
B
Z
Object array after sorting by comparator
Z
B
A

4.Java Program To Search Elements of List

import java.util.*;
class CollectionSearchDemo
{
public static void main(String [] args)
{
ArraysList al=new ArrayList();
al.add("apple");
al.add("mango");
al.add("banana");
al.add("grape");
System.out.println(al);
//Collections.sort(al);
System.out.println(al);
System.out.println(Collections.birnarySearch(al,"apple"));
System.out.println(Collections.birnarySearch(al,"mango"));
}
}
Output:
javac CollectionSearchDemo.java
java CollectionSearchDemo
[apple,mango,banana,grape]
[apple,mango,banana,grape]
0
1

5.Java Program to Reverse Elements of List

import java.util.*;
class CollectionReverseDemo
{
public static void main(String args[])
{
ArrayList al=new ArrayList();
al.add(15);
al.add(0);
al.add(45);
al.add(10);
System.out.println(al);
Collections.reverse(al);
System.out.println(al);
}
}

Output
javac CollectionReverseDemo.java
java CollectionReverseDemo
[11,5,6,7]
[7,6,5,11]


6.Java Program to find minimum element from array
class MinimumOfArray
{
public static void main(String args[])
{
int i,min;
int a[]={30,34,2,6,45};
min=a[0];
for(i=0;i<5;i++)
{
if(min>a[i])
{
min=a[i];
}
}
System.out.println("Minimum:"+min)
}
}
Output:
Minimum: 2

7.Java Program to find maximum element from array
class MinimumOfArray
{
public static void main(String args[])
{
int i,max=0;
int a[]={30,34,2,6,45};
min=a[0];
for(i=0;i<5;i++)
{
if(a[i]>max)
{
max=a[i];
}
}
System.out.println("Maximum:"+max)
}
}
Output:
Maximum:45

8. Java Program to explain jagged array

class JaggedArray
{
public static void main(String args[])
int a[]][]=new int[4][];
a[0]=new int[1];
a[1]=new int[2];
a[2]=new int[3];
a[3]=new int[4];
int i,j,x=1;
for(i=0;i<a.length;i++)
{
for(j=0;j<a[i].length;j++)
a[i][j]=x;
x++;
}
}
for(i=0;i<a.length;i++)
{
for(j=0;J<a[i].length;j++)
{
System.out.println(a[i][j])+" ");
}
System.out.println();
}
}
}
Output:
1
2 3
4 5 6
7 8 9 10
for(i=0;i<a.length;


Simple Java Program

In this post, we will learn how to write simple and first java program.Before writing a simple hello java program easily we have to install JDK. Firstly, understand the Requirements to

create a simple java program:For executing any java program you need to install the JDK if you don not have installed it.


1) set path of  the JDK/BIN directory if you do not know how to set path then see it i was already posted how to set path.

2) create the java program

3)compile and run the java program


Creating Simple Java Program:

class Simple{
pubic static void main(String args[])
{
System.out.println("WELCOME TO coding2world");
}
}

After writing first java program either in Note pad or IDE tool then save this file as Simple.java
To compile and Run Program :

To compile and Run the Java program you need to install Java Development Kit(JDK) and optionally Integrated Development Environment(IDE). To download Java SE for latest version fallow the link: Java 8 software download

Once you installed the JDK, then open command prompt in Windows Environment then type

to compile program:  javac Simple.java and to run the java program java simple

Here javac means java compiler,this command compiles the java source code into an intermediate representation,called byte codes and saves them in class files. The java command launches a virtual machine that loads the class files and executes the byte codes. Once compiled,byte code can run on any java virtual machine.

The following is the output for the preceding program. 

WELCOME TO coding2world


Now we will Understand First java program Step by Step :

class: A class  code starts with a { and ends with }. We know that a class or an object contains variables and methods. A class can define what an Object can do. Generally in java, all code defined inside a class. In the above program we made up a single class called Simple

Now we will discuss about public static void main(String[] args)

main:
main is a method name,which is declared inside a class. This is the first method that is called when the program runs.

public:
 
In the main() method signature the first one that is public keyword is an access specifier,which allows the programmer to control  visibility of the class members.That means it is called by JVM from any where. So, must be declare main() method as public,because it must be called by code outside of its class.

static:

main method declared as static that means the method does not operate on any objects. The main advantage of static method is that there is no need to create object to invoke the static method.The main method is executed by the JVM, so it doesn't require to create object to invoke the main method. So it saves memory.

void:
void is the return type of the method, it means it doesn't return any value.

String[] args:
It is used for command line argument.

System.out.println:

This statement is used to print the result.



Login form using HTML5 and CSS

In this post you will learn Login form page source code using HTML5 and CSS. This is simple Login form Source code you can add more feature but now i have developed simple login form using HTML5 and CSS

<!DOCTYPE html>
<!--[if lt IE 7]> <html class="lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]> <html class="lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]> <html class="lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html lang="en"> <!--<![endif]-->
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>Login Form</title>
  <link rel="stylesheet" href="css/style.css">
  <!--[if lt IE 9]><script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
</head>
<body>
  <section class="container">
    <div class="login">
      <h1>Home Page</h1>
      <form method="post" action="index.html">
        <p> User Name:<input type="text" name="login" value="" placeholder="Username or Email"></p>
        <p>password :<input type="password" name="password" value="" placeholder="Password"></p>
        <p class="remember_me">
          <label>
            <input type="checkbox" name="remember_me" id="remember_me">
            Remember me on this computer
          </label>
        </p>
        <p class="submit"><input type="submit" name="commit" value="Login"></p>
      </form>
    </div>

    <div class="login-help">
      <p>Forgot your password? <a href="index.html">Click here to reset it</a>.</p>
    </div>
  </section>

  </body>
</html>

Java Multithread Programs

In previous post we were learned some of String programs,in this post you will learn multithread programs.

1. Java Program to find the name of the thread

class Test extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
display();
}
}
public void display()
{
Thread t=Thread.currentThread();
String name=t.getName();
System.out.println("name="+name);
}
public static void main(String args[])
{
Test t1=new Test();
t1.start();
for(int i=0;i<10;i++)
{
t1.display();
}
}
}

Output:

Javac Test.java
java Test
name=main
name=main
name=main
name=main
name=main
name=Thread-0
name=main
name=Thread-0
name=main
name=Thread-0
name=main
name=Thread-0
name=main
name=Thread-0
name=Thread-0
name=Thread-0

2) Java Program to set priority of a Thread?
class MyThread extends Thread
{
public void run()
{
for (int i=0; i< 10 ; i++ )
{
System.out.println("Child Thread");
}
}
}
class ThreadPriorityDemo
{
public static void main(String arg[])
{
MyThread t = new MyThread();
System.out.println(t.getPriority());
t.setPriority(10);
t.start();
for(int i =0;i<10;i++)
{
System.out.println("Main Thread");
}
}
}
Output:
javac ThreadPriorityDemo.java
java ThreadPriorityDemo

5
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread

3) Java Program to prevent a thread from execution using yield() method

class MyThread extends Thread
{
public void run()
{
for (int i=0; i< 10 ; i++ )
{
System.out.println("Child Thread");
Thread.yield();
}
}
}
class YieldDemo
{
public static void main(String arg[])
{
MyThread t = new MyThread();
t.start();
for(int i =0;i<10;i++)
{
System.out.println("Main Thread");
}
}
}

Output:
javac YiedldDemo.java
java YieldDemo
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
 
4) Java Program to prevent a Thread from execution using sleep()

class MyThread extends Thread
{
public void run()
{
try
{
for (int i = 0;i<10;i++)
{
System.out.println("This is Lazy Method");
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(e);
}
}
}
class SleepDemo
{
public static void main(String arg[])throws InterruptedException
{
MyThread t = new MyThread();
t.start();
System.out.println("Main Thread");
}
}
Output:
javac SleepDemo.java
java SleepDemo
Main Thread
This is Lazy Method
This is Lazy Method
This is Lazy Method
This is Lazy Method
This is Lazy Method
This is Lazy Method
This is Lazy Method
This is Lazy Method
This is Lazy Method
This is Lazy Method

5) How can you interrupt a sleep() method of thread class

class MyThread extends Thread
{
public void run()
{
try
{
for (int i = 0;i<10;i++)
{
System.out.println("This is Lazy Method");
Thread.sleep(3000);
}
}
catch (InterruptedException e)
{
System.out.println(e);
}
}
}
class InterruptDemo
{
public static void main(String arg[])throws InterruptedException
{
MyThread t = new MyThread();
t.start();
t.interrupt();
System.out.println("Main Thread");
}
}

Output:
javac InterruptDemo.java
java InterruptDemo

Main Thread
This is Lazy Method
java.lang.InterruptedException:sleep interrupted


6)  Every object has unique lock but a thread can acquire more than one lock at a time. Explain it?
class Printmsg
{
public synchronized void wish(String name)
{
for(int i =0;i<10;i++)
{
System.out.print("Hi....");
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
}
System.out.println(name);
}
}
}
class MyThread extends Thread
{
Printmsg p;
String name;
MyThread(Printmsg p,String name)
{
this.p = p;
this.name = name;
}
public void run()
{
p.wish(name);
}
}
class SynchronizedTest
{
public static void main(String arg[])
{
Printmsg p = new Printmsg();
MyThread t1 = new MyThread(p,"lucky");
MyThread t2 = new MyThread(p,"good morning");
t1.start();
t2.start();
}
}

Output:
 javac SynchronizedTest.java
java SynchronizedTest
Hi....good morning
Hi....good morning
Hi....good morning
Hi....good morning
Hi....good morning
Hi....good morning
Hi....good morning
Hi....good morning
Hi....good morning
Hi....good morning
Hi....lucky
Hi....lucky
Hi....lucky
Hi....lucky
Hi....lucky
Hi....lucky
Hi....lucky
Hi....lucky
Hi....lucky
Hi....lucky

 7) Is daemon() thread will start early or main()method?


we can not change the daemon() nature of main()thread because it has started already before main() method only. All daemon() threads terminated automatically when ever lost non-daemon threads.

class MyThread extends Thread
{
public void run()
{
for(int i = 0;i<10;i++)
{
System.out.println("Child Thread");
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
}
}
}
}
class DaemonThreadDemo
{
public static void main(String arg[])
{
MyThread t = new MyThread();
t.setDaemon(true);
t.start();
System.out.println("The end of main");
}
}

Output:
javac DaemonThreadDemo.java
java DaemonThreadDemo
The end of main
child Thread

If  you comment setDaemon(true) then both child and main threads are non-daemon,if we are not comment then child thread is daemon thread and hence it will terminate automatically when ever main() thread terminates.

Note: Deamon thread means the threads which are running in the background to provide support for user defined threads are called Deamon threads


8) How to display thread status?
class myThread extends Thread
{
boolean waiting=true;
boolean ready=false;
myThread()
{
}
public void run()
{
String threadName=Thread.currentThread().getName();
System.out.println(threadName+"starting");
while(waiting)
System.out.println("waiting:"+waiting);
startWait();
try{
Thread.sleep(2000);
}
catch(Exception e)
{
System.out.println(threadName+"inerrupted");
}
System.out.println(threadName+"terminating");
}
synchronized void startWait()
{
try
{
while(!ready)
wait();
}
catch(InterruptedException ie)
{
System.out.println("wait() interrupted()");
}
}
synchronized void notice()
{
ready=true;
notify();
}
}
public class Demo
{
public static void main(String args[])throws Exception
{
myThread mt=new myThread();
mt.setName("My Thread 1");
showThreadStatus(mt);
mt.start();
Thread.sleep(100);
showThreadStatus(mt);
mt.waiting=false;
Thread.sleep(100);
showThreadStatus(mt);
mt.notice();
Thread.sleep(100);
showThreadStatus(mt);
while(mt.isAlive())
System.out.println("alive");
showThreadStatus(mt);
}
static void showThreadStatus(Thread mt)
{
System.out.println(mt.getName()+"alive:"+mt.isAlive()+"state"+mt.getState());
}
}

Output:

Javac Demo.java
java Demo

alive
alive
alive
alive
alive
alive
alive
alive
alive
alive
alive
alive
My Thread 1terminating
alive
alive
alive
My Thread 1alive:falsestateTERMINATED

Java String Programs

As so far we were learned fundamental Java Programs, java inheritance programs etc.. in this post you will learn String programs in Java. These programs will ask in written Test and Technical round also. Before go to the Test you should brush up the following String Examples to get more confident.

1. Java Program to reverse a String

import java.util.Scanner;
public class StrRev{
    public static void main(String[] args){
    Scanner in=new Scanner(System.in);
    System.out.println("Enter the string to reverse: ");
    String str=in.nextLine();
    String reverse = new StringBuffer(str).reverse().toString();
    System.out.println("String after reverse:"+reverse);
    }
}
Output:

Javac StrRev.java
java StrRev
Enter the string to reverse: lucky
String after reverse: ykcul

2. Java Program to make first alphabet capital in each word of given String

import java.util.Scanner;
public class MakeCapitalFirstWordInLine
{
public static void main(String[] args)
{
// create object of scanner class.
Scanner in = new Scanner(System.in);
// enter sentence here
System.out.print("Enter sentence here : ");
String line = in.nextLine();
String upper_case_line = "";
// this is for the new line which is generated after conversion.
Scanner lineScan = new Scanner(line);
while(lineScan.hasNext())
{
String word = lineScan.next();
upper_case_line += Character.toUpperCase(word.charAt(0)) + word.substring(1) + " ";
}
// print original line with output.
System.out.println("Original sentence is : " +line);
System.out.println("Sentence after convert : " +upper_case_line.trim());
}
}

Output:
Enter Sentence here: welcome to coding2world
Original Sentence here: welcome to coding2world
Sentence after convert: Welcome To Coding2world

3.Java Program to String comparison 

import java.util.Scanner;

class StringComparison{
public static void main(String args[]){
String str1, str2;
Scanner in = new Scanner(System.in);
System.out.println("Enter first string");
str1 = in.nextLine();
System.out.println("Enter second string");
str2 = in.nextLine();
if ( str1.compareTo(str2) > 0 ){
System.out.println("First string is greater");
}
else if ( str1.compareTo(str2) < 0 ){
System.out.println("First string is smaller");
}
else{
System.out.println("The strings are equal");// Strings are compared based on the length of the strings.
}
}
}
Output:

Enter first string
javacoding
Enter second string
java
First string is greater

4. Java Program to convert String to Array

import java.util.*;
  class StringToArrayList  { 
public static void main(String[] args)  { 
String[] words = {"hai", "ram", "hello", "lakshman", "anji"}; 
List list = Arrays.asList(words); 
System.out.println("As a list:");
for (String e : list) 

System.out.println(""+e); 


}
Output:
As a list:
hai
ram
hello
lakshman
anji

5. Java Program to find the Occurrence of each character
import java.io.*;
import java.util.Scanner;
public class FindDuplicateChar
{
public static void main(String[] args) throws IOException
{
// create object of the string.
String S;
Scanner scan = new Scanner (System.in);
// enter your statement here.
System.out.print("Enter the Statement : ");
// will read statement and store it in "S" for further process.
S = scan.nextLine();
int count=0,len=0;
do

try
{
// this loop will identify character and find how many times it occurs.
char name[]=S.toCharArray();
len=name.length;
count=0;
for(int j=0;j<len;j++)
{
// use ASCII codes for searching.
if((name[0]==name[j])&&((name[0]>=65&&name[0]<=91)||(name[0]>=97&&name[0]<=123)))
count++;
}
if(count!=0){
// print all the repeated characters.
System.out.println(name[0]+" "+count+" Times");
}
S=S.replace(""+name[0],"");         
}
catch(Exception e)
{
System.out.println(e);
}
}
while(len!=1);
}
}

Output:
First run:
Enter the statement: I love coding
i 1 times
l 2 times
o 3 times
v 4 times
e 5 times
c 6 times
o 7 times
v 8 times
e 9 times
 Second run:
Enter the statement: miss you
m 1 times
i  2 times
s  3 times
s  4 times
y  5 times
o 6  times
u  7 times

6. Java program to count the no of words in given String

import java.util.Scanner;

public class CountWordsInString {
   
    /**
     * Method to count no. of words in provided String
     * @param inputString
     * @return
     */
 static int countWords(String inputString){
 String[] strarray = inputString.split(" ");  // Spilt String by Space
 StringBuilder sb = new StringBuilder();
 int count=0;
 for(String s:strarray){
 if(!s.equals("")){
 count++;
 }   
 }
 return  count;
 }
 public static void main(String[] args) {
 Scanner sc = new Scanner(System.in);
 System.out.println("Enter String : ");
 String str = sc.nextLine();
 System.out.println("No. of Words in String : "+countWords(str));
}
}
Output:
Enter String: welcome to coding2world
no of words in String: 4

 7.Java Program to check the given String Palindrome or not

import java.util.Scanner;
public class PalindromString {
static boolean isPalindromString(String inputStr){
StringBuilder sb  = new StringBuilder(inputStr);
String reverseStr = sb.reverse().toString();
return (inputStr.equalsIgnoreCase(reverseStr));             
}
   
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter String : ");
String inString = sc.next();
if(isPalindromString(inString)){
System.out.println(inString +" is a Palindrom String");
}
else{
System.out.println(inString +" is not a Palindrom String");
}
}
}
Output:
Enter String: lucky
lucky is not a palindrom string

Enter String: madam
madam is a palindrom String

8. Java Program to reverse a String without using StringBuffer.reverse() method

import java.util.*;
class ReverseString
{
public static void main(String args[])
{
//declaring string objects
String str="",revStr="";
Scanner in = new Scanner(System.in);
//input string
System.out.print("Enter a string :");
str= in.nextLine();
//get length of the input string
int len= str.length();
//code to reverse string
for ( int i = len- 1 ; i >= 0 ; i-- )
revStr= revStr+ str.charAt(i);
//print reversed string
System.out.println("Reverse String is: "+revStr);
}
}
Output:
Enter a String: program
Reverse String is:margorp

9. Java SubString Example

public class JavaSubstringExample{
public static void main(String args[]){
String name="Hello World";
System.out.println(name.substring(0,5));
}
}

OUTPUT:
World
Hello









Java Inheritance Programs

In this post we will learn inheritance programs in java for freshers and students. These inheritance programs makes you confident when you attending technical interview and written test. Let's see some of the most important inheritance programs.

1.Java simple Inheritance Example

class A
{
int i,j;
void show();
{
System.out.println("i and j:"+i+ " " +j);
}
class B extends A
{
int k;
void display()
{
System.out.println("k:"+k);
}
void sum()
{
System.out.println("i+j+k:"+(i+j+k));
}
class InheritanceExample
{
public static void main(String args[])
{
A sup=new A();
B sub=new B();
sup.i=10;
sup.j=20;
sup.show();
sub.i=7;
sub.j=8;
sub.k=9;
sub.show();
sub.display();
sub.sum();
}
}
Output:
i and j: 10 20
i and j: 7 8
k: 9
i+j+k=24

2. Java Program of method overloading

class Calculation { 
void sum(int a,int b){
System.out.println(a+b);

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



Output:
30
40 

3. Java Program of Method Overriding

class Bank{ 
int getRateOfInterest(){
return 0;} 

class SBI extends Bank{ 
int getRateOfInterest()
{
 return 7;} 

class ICICI extends Bank{ 
int getRateOfInterest(){
return 8;} 

class AXIS extends Bank{ 
int getRateOfInterest(){
return 9;} 

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: 7
ICICI Rate of Interest: 8
AXIS Rate of Interest:9

4. Java Program using super keyword at method level

class Test
{
void print()
{
System.out.println(" WELCOME");
}
}
class Demo extends Test
{
void print()
{
System.out.println("WELCOME TO JAVA");
}
void display()
{
print();//it invoke sub class print() method
super.print();//it invoke super class print() method
}
public static void main(String args[])
{
Demo d=new Demo();
d.display();
}
}

Output:
Javac Demo.java
java Demo
WELCOME TO JAVA
WELCOME

5.java program super at constructor level

class Test
{
Test()
{
System.out.println("this is default constructor");
}
}
class Demo extends Test
{
Demo()
{
System.out.println("this is parameterized constuctor");
}
}
class SuperConstructor
{
public static void main(String args[])
{
Demo d=new Demo();
}
}

Output:
 javac SuperConstructor.java
java SuperConstructor 

this is default constructor
this is parameterized constructor

6 Java program parameterized constructor 

class Test
{
int a;
Test(int a)
{
this.a=a;
}
}
class Demo extends Test
{
int a;
Demo(int i,int j)
{
super(i);
i=j;
}
void display()
{
System.out.println("sub class="+a);
System.out.println("sub class a="+super.a);
}
}
class SuperDemo
{
public static void main(String args[])
{
Demo d=new Demo(10,20);
d.display();
}
}

Output:
javac SuperDemo.java
java SuperDemo
sub class=20
sub class a=10 

7. Java Program for Polymorphism

class Shape
{
 void draw()
{
System.out.println("Drawing  Shape");
}
}
class Rectangle extends Shape
{
void draw()
{
System.out.println("Drawing Rectangle");
}
}
class Triangle extends Shape
{
void draw()
{
System.out.println("Drawing Triangle");
}
}
class Poly
{
public static void main(String args[])
{
Shape s=new Shape();
s.draw();
Rectangle r=new Rectangle();
s=r;
s.draw();
Triangle t=new Triangle();
s=t;
s.draw();
}
}
Output:
Drawing Shape
Drawing Rectangle
Drawing Triangle


8. Java Program for Abstract Example

abstract class Shape
{
 abstract void draw();
}
class Rectangle extends Shape
{
void draw()
{
System.out.println("Drawing Rectangle");
}
}
class Triangle extends Shape
{
void draw()
{
System.out.println("Drawing Triangle");
}
}
class Poly2
{
public static void main(String args[])
{
Shape s;
Rectangle r=new Rectangle();
s=r;
s.draw();
Triangle t=new Triangle();
s=t;
s.draw();

Output:
Drawing Rectangle
Drawing Triangle

9. Java Program for final class example

final class A
{
void display()
{
System.out.println("A display()");
}
}
class B
{
void display()
{
System.out.println("B display()");
}
}
class FinalClassTest
{
public static void main(String args[])
{
A a=new A();
B b=new B();
a.display();
b.display();
}
}
Output:
A display()
B display()

10 Java Program for final method example

class A
{
final void display()
{
System.out.println(" A display()");
}
}
class B extends A
{
void show()
{
System.out.println("B display()");
}
}
class FinalMethod
{
public static void main(String args[])
{
B b=new B();
b.display();
b.show();
}
}
Output;
A display()
B display()

java conversions programs

In this post we will learn some of basic java programs which converting Binary to Decimal,Binary to Octal,Decimal to Octal etc... These programs are for freshers and  students those are new to programming language. Let's see the following examples.

1. Java program to convert Binary to Decimal

import java.util.*;
public class BinToDec
{
public static void main(String args[])
{
String binstr;
int decNum;
System.out.print("Enter Binary String(0-1):");
binstr=new Scanner (System.in).nextLine();
decNum=bintodec(binstr);
if(decNum==-1)
{
System.out.print("invalid string");
}
else
{
System.out.print("Decimal Number:"+decNum);
}
}
public static int bintodec(String binaryString)
{
int dnum=0;
int i=0;
int n;
int len=binaryString.length();
while(i<len)
{
n=binaryString.charAt(i)-48;//covert char '0' or '1' into integer 0 or 1
/* check for 0 and 1*/
if(n!=0&&n!=1)
{
return -1;//invalid string
}
dnum=(dnum*2)+n;
i++;
}
return(dnum);
}
}
Output:
Enter binary String(0-1): 110011
Decimal number:51

2.Java Program to covert Binary to Octal

import java.util.*;
public class BinToOct
{
public static void main(String args[])
{
int binary;
int remainder;
int decimal=0;
int octal=0;
int i=1;
System.out.print("Enter Binary number");
binary=new Scanner (System.in).nextInt();
/*convert Binary to Decimal number first */
while(binary!=0){
remainder=binary%10;
decimal=decimal+(remainder*i);
binary=binary/10;
i=i*2;
}
/*now convert to Decimal to octal number */
i=1;
while(decimal!=0)
{
remainder=decimal%8;
octal=octal+(remainder*i);
decimal=decimal/8;
i=i*10;
System.out.print("Octal Number:"+octal);
}
}
output:
enter Binary number: 1010
Octal number : 12

 3 Java program to convert Binary to HexaDecimal

import java.util.*;
public class BinToHex
{
public static void main(String args[])
{
int[] hexadeci=new int[100];
int dec=0;
int binary;
int i=1;
int j;
int rem;
System.out.print("Enter a Binary number:");
binary=new Scanner(System.in).nextInt();
/*binary to decimal*/
while(binary>0)
{
rem=binary%2;
dec=dec+(rem*i);
binary=binary/10;
i=i*2;
}
/*now decimal to HexaDecimal*/
i=0;
while(dec!=0)
{
hexadeci[i]=dec%16;
dec=dec/16;
i++;
}
System.out.print("Hexadecimal value:");
for(j=i-1;j>=0;j--)
{
if(hexadeci[j]>9)
{
System.out.print((char)(hexadeci[j]+55));
}
else
{
System.out.print(hexadeci[j]);
}
}
}
}

4. Java Program to convert Decimal to Binary
import java.util.*;
public class DecToBin
{
public static void main(String args[])
{
int i=0;
int j;
int dNum;
int[]bArr=new int[20];
System.out.print("Enter Decimal no:");
dNum=new Scanner(System.in).nextInt();
if(dNum==0)
{
System.out.print("Binary String is 0");
System.exit(0);
}
while(dNum>0)
{
bArr[i]=dNum%2;
dNum=dNum/2;
i++;
}
System.out.print("Binary String is");
for(j=i-1;j>=0)j--)
{
System.out.print(bArr[j]);
}
}
}
Output:
Enter Decimal no: 55
Binary String is 110111

5. Java  Program to covert Decimal to Octal

import java.util.*:
public class DecToOct
{
public static void main(String args[])
{
int decimal;
int remainder;
int octal=0;
int i=1;
System.out.print("enter a decimal number");
decimal=new Scanner(System.in).nextInt();
while(decimal!=0)
{
remainder=decimal%8;
octal=octal+(remainder*i);
decimal=decimal/8;
i=i*10;
}
System.out.print("octal number:"+octal);
}
}
Output:
Enter a decimal number: 100
octal number:144

6. Java program to convert Octal to Binary

import java.util.*;
public class OctToBin
{
public static void main(String args[])
{
int i=0;
System.out.print("enter any octal number:");
String octalNumber=new Scanner(System.in).nextLine();
int len=octalNumber.length();
System.out.print("Binary value:");
for(i=0;i<len;i++)
{
switch(octalNumber.charAt(i))
{
case '0':
              System.out.print("000");
               break;
case '1':
            System.out.print("001");
            break;
case '2':
            System.out.print("010");
            break;
case '3':
             System.out.print("011");
             break;
case '4':
            System.out.print("100");
            break;
case '5':
            System.out.print("101");
            break;
case '6':
            System.out.print("101");
            break;
case '7':
            System.out.print("111");
            break;
default:
           System.out.print("\n Invalid octal digit"+octalNumber.charAt(i));
return;
}// end of switch
}//end of loop
}
}
Output:
Enter any octal number: 12
Binary value: 001010

7. Java Program to convert Octal to Decimal

import java.util.*;
public class OctToDec
{
public static void main(String args[])
{
int octNumber;
int deciNumber=0;
int remainder;
int i=1;
System.out.print("enter an octal number:");
octNumber=new Scanner(System.in).nextInt();
while(octNumber!=0)
{
remainder=octNumber%10;
deciNumber+=remainder*i;
octNumber/=10;
i=i*8;
}
System.out.print("Decimal Number:"+decinumber);
}
}
Output:
Enter any octal number:256
Decimal number: 174

Fundmental Java Programs

In this post we will learn frequently asked Basic Java Programs for freshers. As a fresher all these programs should be aware before attend the interview. Let's Look at the following examples.


1) Java program to find whether the given number  is Even or Odd?

Ans:
import java.util.Scanner;
class EvenOrOdd{
public static void main(String[] args){
int a;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a value:");
a=sc.nextInt();
if(a%2==0)
{
System.out.print("Given number is Even");
}
else
{
System.out.print("Given number is Odd");
}
}

Output:




javac EvenOrOdd.java
java EvenOrOdd
Enter a value: 6
Given number is Even

2) Java Program to find Factorial of the Given number?
Ans:
import java.util.Scanner;
class FactorialDemo
{
public static void main(String[] args)
{
 int n,fact=1;
Scanner sc=new Scanner(System.in);
System.out.print("Enter n value");
n=sc.nextInt();
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.print("factorial of "+n"is"fact);
}
}

Output: 

javac FactorialDemo.java
java FactorialDemo
Enter n value 5
Factorial of 5 is 120

3) Java program to check the given number is perfect or not?
 

Ans:
import java.util.Scanner;
class PerfectTest{
public static void main(String[] args)
{
int n;
int i=1;
int sum=0;
Scanner sc=new Scanner(System.in);
System.out.print("enter a number");
n=sc.nextInt();
while(i<n)
{
if(n%i==0){
sum=sum+i;
}
i++;
}
if(sum==n)
{
System.out.print(i+"is a perfect number");
}
else{
System.out.print(i+"is not a perfect number");
}
} 

Output:
javac PerfectTest.java
java PerfectTest
enter a number
1
1 is not a perfect number
enter a number
6
6 is a perfect number

4) Java Program to Count the Digit in a Number?
 

ANS:
import java.util.Scanner;
class Number{
public static void main(String[] args)
{
int num;
int count=0;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number");
num=sc.nextInt();
while(num!=0)
{
num=num/10;
count++;
}
System.out.print("total digits are:"+count);
}
}
Output:
javac Number.java
java Number
enter a number
567
total digits are: 3


5) Java Program to reverse a number?

Ans:

import java.util.Scanner;
class Reverse{
public static void main(String[] args)
{
int a,b;
int c=0;
Scanner sc=new Scanner(System.in);
System.out.print("Enter any number:");
a=sc.nextInt();
while(a>0)
{
b=a%10;
a=a/10;
c=(c*10)+b;
}
System.out.print("reverse number is:"+c)
}
}

Output:


javac Reverse.java
java Reverse
Enter any number: 234
reverse number is: 432

6) Program to find duplicate String elements using HashSet
 

import java.util.*;
class FindDuplicate{
public static void main(String args[])
{
String [] strArray={"lucky","abc","lucky","reddy","pqr"};
HashSet<String> hs=new HashSet<String>();
for(String arryElement:strArray)
{
if(!hs.add(arryElement))
{
System.out.print("duplicate element is"+arryElement);
}
}
}
}

Output:
duplicate element is lucky

7)Java program to find out the given number is prime or not
class primeNumber
{
public static void main(String args[]){
int n,i,a=0;
n=Integer.parseInt(args[0]);for(i=1;i<=n;i++)
if(n%i==0)
a++;
if(a==2)
{
System.out.print("the given number is prime");
}
else
System.out.print("the given number is not prime");
}
}

Output:
java primeNumber 5
the given number is prime
java primeNumber 6
the given number is not prime


8) Program for swaping the two numbers

class swap{
public static void main(String args[])
{
int a,b,temp;
a=20;
b=10;
temp=a;
a=b;
b=temp;
System.out.print("A="+a);
System.out.print("B="+b);
}
}

output:

A=10
B=20

9) program to find out whether the given number is palindrome or not

import java.util.*;
class PalindromeDemo{
public static void main (String args[])
{
int reverse=0,rem;
int number=Integer.parseInt(args[0]);
int n=number;//here we are using n variable to check  last time to check
while(number>0)
{
rem=number%10;
reverse=reverse*10+rem;
number=number/10;
}
if(reverse==n)
{
System.out.print("The given number is palindrome");
}
else{
System.out.print("The given number is not palindrome");
}
}
}

Output:

javac PalindromeDemo.java
java Palindrome 121
the given number is palindrome
java Palindrome 123
The given number is not palindrome


10)program to find the whether the given number is Armstrong or not

import java.io.*;
class Armstrong{
public static void main(String[] args) {
int num=Integer.parseInt(args[0]);
int n=num;
int check=0,remainder;
while(num>0){
remainder=num%10;
check=check+(int)Math.pow(remainder,3);
num=num/10;
}
if(check==n)
System.out.print("given number is armstrong");
else
System.out.print("given number is not armstrong");
}
} 
Output:

javac Armstrong.java
java Armstrong 7
given number is not armstrong
java Armstrong 153
given number is armstrong


Basic Java Programs

In this Post we will learn fundamental Java Programs for Beginners and final year students,these programs will improve your programming skills. Let's start now

1. Java program to display a message

// Hello World example

class FirstProgram
{
public static void main(String args[])
{
System.out.print("Hello coding4world");

}
}

Output:

Hello coding4world

2. Java Program to find area of circle

class circle
{
public static void main("String args[])
{
double rad;
final double PI=3.1415;
rad=10.0;
double area=PI*rad*rad;
System.out.print("Area of circle is="+area);
}
}

Output:
Area of circle is= 314.15

3. Java Program to find area of triangle

class Triangle
{
public static void main(String args[])
{
double area,p,q,r,s;

p=3;
q=4;
r=5;
s=(p+q+r)/2;
area=Math.sqrt(s*(s-p)*(s-q)*(s-r));
System.out.print("Area of triangle is=+area);
}
}

output:

Area of trianlge is=6.0

4. Java Program to find Area of  Rectangle

import java.util.Scanner;
class AreaOfRectangle
{
public static void main(String args[])
{
int length;
int breadth;
int area;
scanner sc=new Scanner(System.in);
System.out.print("Enter the length of Rectangle");
length=sc.nextInt();
System.out.print("\nEnter the Breadth of Rectangle");
breadth=sc.nextInt();
 area=length*breadth;
System.out.print("\n Area of Rectangle:"+area);
}
}

Output:
Enter the length of Rectangle: 5
Enter the breadth of Rectangle: 6
Area of Rectangle : 30

5. Java program to find the volume of Spehere

import java.util.Scanner;
class Spehere
{
public static void main(String args[]);

{
float radius;

float volume;
Scanner sc= new Scanner(System.in);
System.out.print("enter radius of the sphere");
radius=sc.nextFloat();
volume=(float)((4*3.14*radius*radius* radius)/3;
System.out.print(\n valume of sphere is: +volume);
}
}

Output:

Enter radius of the sphere 2
Volume of sphere is: 33.493

6. Java program to covert Celsius To Fahrenheit

import java.util.Scanner;
class CelsiusToFahrenheit
{
public static void main(String args[])
{

float c;
float f;
Scanner sc=new Scanner(System.in);
System.out.print("Enter temp in centigrade:");
c=sc.nextFloat();
f=(float)((1.8*c)+32.0);
System.out.print("Temperature in Fahrenheit="+f);
}
}


Output:
Enter temp in centigrade: 100
Temperature in Fahrenheit=212

7. Java Program to find LCM

import java.util.Scanner;
class LCM
{
public static void main(String args[])

{
int a,b;
int big,small;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the value of a and b");
a=sc.nextInt();
b=sc.nextInt();
if(a>b)
{
big=a;

small=b;
}
else

{
big=b;
small=a;
}
for(int i=1;i<=big;i++)
{
if(((big*i)%small)==0)
{
int lcm=big*i;

System.out.print("The LCM is"+(lcm));
break;
}
}

}
}

Output:
Enter the value of a and b:
10
15
The LCM is 30

8. Java Program to find Hexagon

import java.util.Scanner;
class Hexagon
{
public static void main(String args[])
{
int side;

float area;
Scanner sc=new Scanner(System.in);
System.out.print("enter the Length of side:");
side=sc.nextInt();
area=(float)(3*Math.squre(3)*side*side)/2;
System.out.print("\n Area of Regular Hexagon:"+area);
}
}
Output:
Enter the length of side: 3
Area of Regular Hexagon: 23.38

9.Java Program to find Volume of Hemisphere

import java.util.Scanner;
class Hemisphere
{
public static void main(String args[]);

{
float radius;

float volume;
System.out.print("\n enter radius of the hemisphere");
radius=sc.nextFloat();
volume=(float)((2*3.14*radius)/3);
System.out.print("\n volume of hemisphere is:"+volume);
}
}
Output:
Enter radius of the hemisphere: 6

Volume of hemispere is: 12.64

10. Java program to find Volume of cone

import java.util.Scanner;
class Cone
{
public static void main(String args[])

{
float r;

float h;
float volume;
Scanner sc=new Scanner(System.in);
System.out.print("Enter radius of the cone:");
r=sc.nextFloat();
System.out.print("enter height of the Cone:");
h=sc.nextFloat();
volume=(float)((3.14*r*r*h)/3);
System.out.print("\n volume of cone is:"+volume);
}
}

Output:
Enter radius of the cone: 5

Enter height of the cone: 8
Volume of the cone is: 209.33






Basics of CPP Programs

In this post you will learn fundamental C++ programs. These programs for freshers or beginners. 1 .write a cpp program to display hello w...