Sunday, June 25, 2017

A very usefull java code to read the data from file and showing the details of files data along with file content

import java.io.FileInputStream;
import java.util.Scanner;

public class InputFromFile {
public static void main(String[] args) throws Exception // here i am not handling the 
// error, instead i am just declaring it 


{

// scanner object to take input from keyboard
Scanner sc = new Scanner(System.in);

System.out.print("enter a file name with full path: ");

// here i am using nextLine method, since file path may have spaces
String filePath=sc.nextLine();

// now open a file in read mode using FileInputStream class
FileInputStream fis=new FileInputStream(filePath);

// get no of bytes those can be read by read method using available method
int bytes=fis.available();

// take some variable to store the file size, no of alphabets, numeric values
// spaces and line etc
int alphaUpper=0, alphaLower=0, numeric=0, space=0, line=1;

System.out.println("showing file data ->");
// start an infinite loop
while(true)
{
// read a byte from file using read method and store byte inside a variable
int var=fis.read();

// check for end of file, as we know read method will return -1 to denote end of data
if(var==-1) { // if var has -1
break; // go out of loop
}
// check for alphabets 
if(var>='A' && var<='Z') {
alphaUpper++;
}
else if(var>='a' && var<='z') {
alphaLower++;
}
// check for numerics 
else if(var>='0' && var<='9') {
numeric++;
}
// check for spaces 
else if(var==' ') {
space++;
}
// check for lines 
else if(var=='\n') {
line++;
}
// convert the byte into ASCII character and show it on console
System.out.print((char)var);
}
System.out.println("\n---------------------------------------------");
// show the report
System.out.println("Details of file "+filePath+"->");
System.out.println("Alphabets in uppercase: "+alphaUpper);
System.out.println("Alphabets in lowercase: "+alphaLower);
System.out.println("Total Alphabets: "+(alphaLower+alphaUpper));
System.out.println("Numerics: "+numeric);
System.out.println("Spaces: "+space);
System.out.println("Lines: "+line);
System.out.println("file size: "+bytes+" bytes");
System.out.println("---------------------------------------------");

// close the file [it is a very good practice]
fis.close();

}
}

Thursday, June 22, 2017

Some basic differences between c and java

1. Unlike c we can declare variables anywhere in program

2. Java does not support pointers, structure, union, header files, and garbage values

3. Java does not support macros also.

4. We can declare a variable inside for loop, but we can access it inside that loop only

5. There is no register, extern storage classes are in java

6. Java does not have clrscr() equivalent method to clear screen since java is used for implementing web applications and for that we use HTML as an user interface

Best definition of object in software engineering

Object (also known as instance) is a memory allocated during runtime in ram.

Note: every object has an address which can be stored inside a variable known as pointer to object (in java this variable is called as reference variable or object name)

Tuesday, June 20, 2017

Code to show the use and benefits of very usefull instanceof operartor in java

This program is to show the application of instanceof operator

import java.util.Scanner;

class Car {
void info() {
}
}

/*
 * the info() method of Car has been overridden by its all the subclasses
 */
class Maruti extends Car {
void info() {
}
}

class Alto extends Maruti {
void info() {
System.out.println("alto");
}
}

class Swift extends Maruti {
void info() {
System.out.println("swift");
}
}

class Ciaz extends Maruti {
void info() {
System.out.println("ciaz");
}
}

class WagonR extends Maruti {
void info() {
System.out.println("wagonR");
}
}

class Hundai extends Car {
void info() {
}
}

class I10 extends Hundai {
void info() {
System.out.println("i10");
}
}

class Creta extends Hundai {
void info() {
System.out.println("creta");
}
}

class Verna extends Hundai {
void info() {
System.out.println("verna");
}
}

class Tata extends Car {
void info() {
}
}

class Nano extends Tata {
void info() {
System.out.println("nano");
}
}

class Tiago extends Tata {
void info() {
System.out.println("tiago");
}
}

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

/*
* here we are creating an array of Car class 
* which can store object of any subclass of Car
*/
Car[] cars=new Car[12];
/*
* lets store some objects of subclasses inside this array
* one by one
*/
cars[0]=new Maruti();
cars[1]=new Hundai();
cars[2]=new Tata();
cars[3]=new Alto();
cars[4]=new Swift();
cars[5]=new WagonR();
cars[6]=new I10();
cars[7]=new Verna();
cars[8]=new Nano();
cars[9]=new Tiago();
cars[10]=new Creta();
cars[11]=new Ciaz();

/*
* scanner to take input
*/
Scanner sc=new Scanner(System.in);
System.out.println("please type....\n1=to show all the cars");
System.out.println("2=to show all maruti cars");
System.out.println("3=to show all hundai cars");
System.out.print("4=to show all tata cars: ");
int choice=sc.nextInt();

String message="";

if(choice==1) {
message="showing all the cars";
}
else if(choice==2) {
message="showing all the maruti cars";
}
else if(choice==3) {
message="showing all the hundai cars";
}
else if(choice==4) {
message="showing all the tata cars";
}
else {
message="invalid choice";
}
System.out.println("####"+message+"####");

/*
* fetch the objects from the array of Car class using for loop
*/
for (int i = 0; i < cars.length; i++) {
if(choice==1) {
cars[i].info();
}
else if(choice==2) {
/*
* as we know the instanceof is an relational operator that checks whether 
* an object belongs to a class or not
* we know that an object belongs to itself and to its superclasses
*/
if(cars[i] instanceof Maruti) { // test for objects those are Maruti type
cars[i].info();
}
}
else if(choice==3) {
if(cars[i] instanceof Hundai) { // test for objects those are Hundai type
cars[i].info();
}
}
else if(choice==4) {
if(cars[i] instanceof Tata) { // test for objects those are Tata type
cars[i].info();
}
}
}
System.out.println("####thank you####");


}
}

This is the solution for the today assignment of batch 4 to 6

import java.util.Scanner;

public class Student {

// lets take some non static data members
int roll;
String name;
int physics;
int maths;
int chemistry;

// lets define main method [since we know every java application starts from main method]
public static void main(String[] args) {

// lets create object of student class [object name is 's']
Student s=new Student();
// lets create object of scanner class to take input from keyboard
Scanner sc=new Scanner(System.in);

System.out.println("please provide student info->");

// read data from keyboard and store that data inside non-static data members
// [note: non-static data members must be used using objectname
System.out.print("enter roll: ");
s.roll=sc.nextInt();

System.out.print("enter name: ");
s.name=sc.next();

System.out.print("enter marks in physics: ");
s.physics=sc.nextInt();

System.out.print("enter marks in chemistry: ");
s.chemistry=sc.nextInt();

System.out.print("enter marks in maths: ");
s.maths=sc.nextInt();

// calculate total obtained marks and store that inside a local variable 'total'
int total=s.physics+s.chemistry+s.maths;

// calculate average and store it inside a local variable 'avg'
double avg=total/3;

// lets take two local variables to store grade and remarks
// currently both variable have an empty string as a value
String grade="";
String remark="";

// decide the grade and remarks on the basis of average
if(avg<33.0) {
grade="fail";
remark="you need to word hard";
}
else if(avg>=34.0 && avg<45.0) {
grade="3rd division";
remark="you need to word hard to get 2nd division";
}
else if(avg>=45.0 && avg<60.0) {
grade="2nd division";
remark="you need to word hard to get 1st division";
}
else if(avg>=60.0 && avg<75.0) {
grade="1st division";
remark="you need to word hard to get distinction";
}
else if(avg>=75.0) {
grade="distinction";
remark="you are awesome, just keep it up";
}

// lets print the report card
System.out.println("####Report-Card####");
System.out.println("roll: "+s.roll); // roll is non static variable
System.out.println("name: "+s.name); // name is non static variable
System.out.println("physics: "+s.physics); // physics is non static variable
System.out.println("chemistry: "+s.chemistry); // chemistry is non static variable
System.out.println("maths: "+s.maths); // maths is non static variable
System.out.println("total marks: "+total+"/300"); // total is local variable
System.out.println("percent: "+avg+"%"); // avg is local variable
System.out.println("grade: "+grade); // grade is local variable
System.out.println("remarks: "+remark); // remark is local variable
System.out.println("####End of report####");

}
}

Friday, June 16, 2017

A program to show the use of array of class, i mean how to use array of classes in java

This program is implemented by Sahil Btech(CSE) from JP University, Noida


import java.util.Scanner;

class Employee 
{

// non static data members of employee
String name;
String desig;
double salary;
String city;

// non static method to store data of employee
void set_employee_info()
{
// scanner to get input from keyboard`
Scanner sc=new Scanner(System.in);

System.out.print("Enter name: ");
name=sc.next(); // get string from keyboard
System.out.print("Enter Designation: ");
desig=sc.next(); // get string from keyboard
System.out.print("Enter Salary: ");
salary=sc.nextDouble(); // get a double type value from keyboard
System.out.print("Enter City: ");
city=sc.next(); // get string from keyboard
}

// non static method to store data of employee
void show_emp_info()
{
System.out.println("Name: "+name);
System.out.println("Designation: "+desig);
System.out.println("Salary: "+salary);
System.out.println("City: "+city);
}

public static void main(String[] args) {

// scanner to get input from keyboard
Scanner sc=new Scanner(System.in);
System.out.print("How many employees do you want: ");
int num=sc.nextInt(); // get int value from keyboard

// create array of employee to store multiple employee object
Employee[] emp=new Employee[num];
System.out.println("array of employee of size "+num+" has been created");

for(int i=0;i<num;i++)
{
System.out.println("enter Record number "+(i+1));

// create object of employee
Employee e=new Employee();

// store data inside the object of employee using method
e.set_employee_info();

// store object of employee inside the array of employee
emp[i]=e;
}
System.out.println("---------------------print employee details-------------------------------");
for (int i = 0; i < emp.length; i++) 
{
System.out.println("Record number "+(i+1)+"->");
// call method show_emp_info() on ith element of employee array
emp[i].show_emp_info();
System.out.println("-----------------------------------------------------------");
}

}

}

A basic program of array

This program is implemented by Vikash kumar

import java.util.Scanner;
class TestArray{
public static void main(String...args){
Scanner sc=new Scanner(System.in);
System.out.print("Enter size: ");
int size =sc.nextInt();
int[] array=new int[size];
int[] frq= new int[size];
System.out.println("Enter "+size+" Elements: ");
for(int i=0;i<size;i++){
array[i]=sc.nextInt();
frq[i]=-1;
}
System.out.println("Press 1 to show left to right: ");
System.out.println("Press 2 to show right to left: ");
System.out.println("Press 3 to show in ascending Order: ");
System.out.println("Press 4 to show in decending Order: ");
System.out.println("Press 5 to show sum : ");
System.out.println("Press 6 to show repeatation of element: ");
while(true){
System.out.print("\nEnter your choice:");

int choice=sc.nextInt();
switch(choice){
case 1:{
for(int vr:array)
System.out.print(vr+" ");
}
break;
case 2:{
for(int i=size-1;i>=0;i--){
System.out.print(array[i]+" ");
}
}
break;
case 3:{
System.out.print("No. in ascending order: ");
int temp;
for(int i=0;i<size;i++){
for(int j=0;j>size;j++){
if(array[i]<=array[j]){
temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
}
for(int vr:array)
System.out.print(vr+" ");
}
break;
case 4:{
System.out.print("No. in decending order: ");
int temp;
for(int i=0;i<size;i++){
for(int j=0;j<size;j++){
if(array[i]>=array[j]){
temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
}
for(int vr:array)
System.out.print(vr+" ");
}
break;
case 5:{
int sum=0;
for(int i=0;i<size;i++){
sum+=array[i];
}
System.out.print("sum is: "+sum);
}
break;
case 6:{
int count=0;
for(int i=0;i<size;i++){
count= 1;
for(int j=i+1;j<size;j++){
if(array[i]==array[j]){
count++;
frq[j]=0;
}
}
if(frq[i]!=0){
frq[i]=count;
}
}
for(int i=0;i<size;i++){
if(frq[i]!=0){
if(frq[i]==1)
System.out.println(array[i]+" comes "+frq[i]+" Time");
else 
System.out.println(array[i]+" comes "+frq[i]+" Times");
}  
}
}
break;
default:
System.out.println("Illegal Entry");
}
}
}
}

Tuesday, June 13, 2017

Wonder full java program for recursive file searching

This program is implemented by Sarnav Chauhan from JP University, Noida


import java.io.File;
import java.util.Scanner;

 class fileprogram {

void func( String fname, String p1)
{
File f1=new File(p1);
File[] a=f1.listFiles();

if(a!=null) {
for (int i = 0; i < a.length; i++)
{

if(f1.exists())
{

String filenames=a[i].getName();

if(fname.equals(filenames))
{

if(a[i].isDirectory())
{
System.out.println(" is a folder in "+p1);
}
if(a[i].isFile())
{
System.out.println(fname+" file is available inside folder ->"+p1);
}

}

if(a[i].isDirectory())
{
String s=a[i].getName();
String p2=p1+"\\"+s;
func(fname,p2);

}

}
else
{
System.out.println("file does not exist ");
}



}
}


}


public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

System.out.print("Enter the path: ");
String p1=sc.next();

System.out.print("Enter the name of file to be searched: ");
String fname=sc.next();

                fileprogram f2=new fileprogram();
f2.func(fname,p1);


}

}


A Java program to show the use constructor in java

This program is implemented by Naman Dhiman from NIT Uttrakhand


import java.util.Scanner;
public class Book {
// non static data members
int id;
String topic;
String author;
float price;
String publisher;
// no argument constructor of Book
public Book()
{
                // initializing the data members 
id = 101;
topic = "Let Us C";
author = "Kanethkar";
price = 350.2f;
publisher = "Macmillan";
}
// parameterized constructor of Book  
  public Book(int id, String topic, String author, float price, String publisher) {
                // initializing the data members 
               // this.id means non static variable while id is a local variable
this.id = id;
this.topic = topic;
this.author = author;
this.price = price;
this.publisher = publisher;
}

// non static method to show data of Book 
    void info()
    {
    System.out.println("ID = "+id);
    System.out.println("Topic = "+topic);
    System.out.println("Author = "+author);
    System.out.println("Price = "+price);
    System.out.println("Publisher = "+publisher);
    }
public static void main(String[] args) {
// create object of Book using no argument constructor
Book b1 = new Book();
// show info of Book
b1.info();
// create object of Book using parameterized constructor
Book b2 = new Book(102,"Concepts in Java","Herbert Schildt",800.5f,"PHI");
// show info of Book
b2.info();
// create object of Book using parameterized constructor
Book b3 = new Book(103,"C","E.Balaguruswamy",400.75f,"Hachette");
// show info of Book
b3.info();
// object of Scanner to take input from keyboard
Scanner sc = new Scanner(System.in);
// take some inputs
System.out.println("Enter Book id");
int id = sc.nextInt();
System.out.println("Enter book topic");
String topic = sc.next();
System.out.println("Enter Author's Name");
String author = sc.next();
System.out.println("Enter Price");
float price = sc.nextFloat();
System.out.println("Enter Publisher's Name");
String publisher = sc.next();
// create object of Book using parameterized constructor
// here we are passing variable names as arguments
Book b4 = new Book(id,topic,author,price,publisher);
// show info of Book
b4.info();
}
}




Java program to show the use of methods in order to implement modularity

This program is implemented and  by Manoj Gupta from NIT Uttrakhand

import java.util.Scanner;

public class Student {

        // lets have some non static data members
 int roll;
 String name;
 String email;
 int hindi;
 int english;
 int physics;
 int chemistry;
 int maths;

 // a non static method to take input for data members
 void input_details()
 {
  //scanner object is created
  Scanner sc=new Scanner(System.in);
  //data entry is being done
  System.out.println("\n Enter your name ");
  name=sc.next();
  System.out.println("\n Enter your roll number ");
  roll=sc.nextInt();
  System.out.println("\n Enter your email address ");
  email=sc.next();
  System.out.println("\n Enter your marks in hindi ");
  hindi=sc.nextInt();
  System.out.println("\n Enter your marks in english ");
  english=sc.nextInt();
  System.out.println("\n Enter your marks in physics ");
  physics=sc.nextInt();
  System.out.println("\n Enter your marks in chemistry ");
  chemistry=sc.nextInt();
  System.out.println("\n Enter your marks in maths ");
  maths=sc.nextInt();
  System.out.println("\nThank you for your details");
 }

 // a non static method to show the values of data members
void show_report_card() { //display of report card System.out.println("############################REPORT CARD#####################################"); System.out.println("Name :"+name); System.out.println("Roll :"+roll); System.out.println("Email :"+email); System.out.println("Marks in Hindi :"+hindi); System.out.println("Marks in English :"+english); System.out.println("Marks in Physics :"+physics); System.out.println("Marks in Chemistry :"+chemistry); System.out.println("Marks in Maths :"+maths); int avg; avg=(hindi+english+maths+chemistry+physics)/5; int total; total=hindi+english+maths+chemistry+physics; System.out.println("Total :"+total); System.out.println("Average :"+avg); if(avg<33) { System.out.println("Result :FAIL"); System.out.println("Remarks :Better luck next time"); } if(avg>=33&&avg<=48) { System.out.println("Result :PASS by III DIVISION"); System.out.println("Remarks :Can be improved "); } if(avg>48&&avg<=59) { System.out.println("Result :PASS by II DIVISION"); System.out.println("Remarks :Satisfactory"); } if(avg>60&&avg<=75) { System.out.println("Result :PASS by I DIVISION"); System.out.println("Remarks :VERY GOOD"); } if(avg>75) { System.out.println("Result :PASS by DISTINCTION"); System.out.println("Remarks :EXCELLENT"); } } public static void main(String[] args) {
  // object of class student is being created
                // name of object is 's'
  Student s=new Student();
                
                // invoke the methods
  s.input_details();
  s.show_report_card();

 }
 
} 
Here i am posting a very useful program of random number.
please take a look.

import java.util.Random;
import java.util.Scanner;

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

// create object of random class to generate a random number
Random r = new Random();

// create object of scanner to get input from keyboard
Scanner sc = new Scanner(System.in);

System.out.println("##welcome to the OTP generation system##");
System.out.println("enter 1 to generate a 6 digit numeric OTP");
System.out.println("enter 2 to generate a 8 letters alpha-numeric OTP");
System.out.print("enter 3 to generate a 6 letters mixed alpha-numeric OTP");

// take value for choice from keyboard
int choice = sc.nextInt();

if (choice == 1) {
System.out.println("6 digits numeric OTP: ");
for (int i = 1; i <= 6; i++) {
int var = r.nextInt(10);
System.out.print(var);
}

} else if (choice == 2) {
System.out.println("alpha-numeric 8 chars OTP: ");

for (int i = 1; i <= 4; i++) {
/*
* nextint() method will give a random number in the range of 0
* to 25, we will add 65 in it to get a value in the range of 65
* to 90 (values of alphabets in upper case) then the result
* will be converted into ASCII char using a type cast and will-
* be shown
*/
int var = 65 + r.nextInt(26);
System.out.print((char) var);
}

for (int i = 1; i <= 4; i++) {
int var = r.nextInt(10);
System.out.print(var);
}

} else if (choice == 3) {

System.out.println("mixed alpha-numeric OTP: ");
for (int i = 1; i <= 6; i++) {
int var1 = r.nextInt(10);
/*
* nextint() method will give a random number in the range of 0
* to 25, we will add 65 in it to get a value in the range of 65
* to 90 (values of alphabets in upper case) then the result
* will be converted into ASCII char using a type cast and will-
* be shown
*/
int var2 = 65 + r.nextInt(26);
/*
* nextint() method will give a random number in the range of 0
* to 25, we will add 97 in it to get a value in the range of 97
* to 122 (values of alphabets in lower case) then the result
* will be converted into ASCII char using a type cast and will-
* be shown
*/
int var3 = 97 + r.nextInt(26);
if (i < 3) {
System.out.print(var1);
} else if (i == 3) {
System.out.print((char) var2);
} else if (i == 4) {
System.out.print(var1);
} else if (i == 5) {
System.out.print((char) var3);
} else {
System.out.print(var1);
}
}

} else {
System.out.println("invalid choice....");
}

}
}