Wednesday, July 29, 2015

Java Code to Print age of user from B.Date

import java.util.*;
class Demo{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);       // to fetch user input
System.out.println("Enter B.date (dd-mm-yyyy):");
String bdate = sc.nextLine();
String year = bdate.substring(6); // to extract yyyy
int y = Integer.parseInt(year);  // convert into numberic value
int age = 2015 - y;                   // find age
System.out.println("Your age is "+ age+" hopefully");

// ans may not be correct as we need to take month into account as well.
}
}

Java Code to write method that returns both max and min number from an array of integers

class Demo{
static int[] getMaxMin(int[] arr){
int max = arr[0], min = arr[0];
for(int i = 0 ; i< arr.length; i++){
if(arr[i]>max){
max = arr[i];
}
if(arr[i]<min){
min = arr[i];
}
}
int[] ans = new int[2];
ans[0] = max;
ans[1] = min;
return ans;
}
public static void main(String[] args){
int[] arr = new int[]{1,2,3,6,4,3,9,7,0};
int[] ans  = Demo.getMaxMin(arr);
System.out.println("Max is: "+ ans[0]+" Min is: "+ ans[1]);
}

}

Random Maths Questions

import java.util.*;
class Demo{
public static void main(String[] args){
Random r = new Random();
Scanner sc = new Scanner(System.in);
while(true){

int i = r.nextInt(100);
int j = r.nextInt(100);
int op = r.nextInt(3);
int correctans = 0;


System.out.print(i);
if(op==0){
System.out.print("+");
correctans = i+j;
}
else if(op==1){
System.out.print("-");
correctans = i - j;
}
else if(op==2){
System.out.print("*");
correctans = i * j;
}
System.out.println(j+"=?");
int answer = sc.nextInt();

if(answer == correctans){
System.out.println("Correct Answer\n");

}
else{
System.out.println("Wrong Answer\n");
break;
}

}

}
}

Tuesday, July 21, 2015

Prog21.java

Write a method which takes 3 integers as parameters and adds the 2 highest numbers out of 3 then and returns the result. e.g. m1(5,7,2) will return you 12 (5+7).


class Utility{
static int addMax2(int i, int j, int k){
int max1, max2;
if(i<=j && i<=k){
return k+j;
}
else if(j<=k && j<=i){
return k+i;
}
else if(k<=j && k<=i){
return i+j;
}
else if(i==j && i==k){
return i+j;
}
return 0;
}
}

class Demo{
public static void main(String[] args){
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
int k = Integer.parseInt(args[2]);
int ans = Utility.addMax2(i,j,k);
System.out.println(ans);
}
}

Prog7.java

Write a program to find no. of digits in a String.

class Demo{
public static void main(String[] args){
String a="2sdf46sf4";
int count = 0;
for(int i =0; i<a.length(); i++){
char c = a.charAt(i);
if(Character.isDigit(c)){
count++;
}
}
System.out.println("No. of Digits = "+count);
}

}


Output:
No. of Digits = 4


[Hint: You can also go for command line argument instead of fixed string in program]

Prog10.java

Find whether an array is sorted or not.

class Prog10{
static boolean isSorted(int[] arr){
int flag = 0;
for(int i = 0 ; i<arr.length-1; i++){
if(arr[i] > arr[i+1]){
return false;
                               // Even if 1 item is greater then next item, ans is false.
}
}
          return true;
// if all items are perfect only then code reaches till here, so return true.
}

public static void main(String[] args){
// args[0] -> no . of  elements
int no = Integer.parseInt(args[0]);
int[] arr = new int[no];

for(int i = 0 ; i<no ; i++){
arr[i] = Integer.parseInt(args[i+1]);
}

if(Prog10.isSorted(arr)){
System.out.println("Yes sorted");
}
else{
System.out.println("Not sorted");
}
}
}

Saturday, July 11, 2015

Student class with overloaded constructors and method to display object


class Student{
    String name;
    int roll;
    int marks;
    Student(){            // default constructor
        name="unnamed";
        roll=0;
        marks=0;
    }
    Student(String s, int r, int m){    // overloaded constructor with 3 arguments
        this.name=s;
        this.roll=r;
        this.marks=m;
    }    
    void display(){            //method to display the object
        System.out.println("Student Details:");
        System.out.println("Name:"+this.name+" Roll:"+this.roll+" Marks"+this.marks);
    }
}
class TestStudent{            //class to test the Student class
    public static void main(String args[]){            //main method
        Student s1=new Student();
        Student s2=new Student("abcd",12, 80);
        s1.display();
        s2.display();
    }
}
Compile:
javac TestStudent.java

Run
java TestStudent

Circle class with Overloaded Constructors

class Circle{
    static final double PI = 3.1428;
    
    double radius;
    Circle(double r){
        this.radius=r;
    }
    Circle(int r){
        this.radius=r;
    }
    double calculateArea(){
        return PI*this.radius*this.radius;
    }
}
class TestCircle{
    public static void main(String args[]){
        Circle c1=new Circle(4);
        Circle c2=new Circle(4.2);
        System.out.println("Area of c1 is :"+c1.calculateArea());
        System.out.println("Area of c2 is :"+c2.calculateArea());
        
    }
}

Compile:
javac TestCircle.java

Run:
java TestCircle

abstract class with 2 concrete subclasses

abstract class A{
    abstract void display();
}
class A1 extends A{
    void display(){
        System.out.println("Object of A1");
    }
}
class A2 extends A{
    void display(){
        System.out.println("Object of A2");
    }
}
class TestA{
    public static void main(String args[]){
        A1 a1=new A1();
        A2 a2=new A2();
        a1.display();
        a2.display();
    }
}


Compile:
javac TestA.java

Run:
java TestA

Sort int [ ] of dynamic size with dynamic numbers (Command Line Arguments)

//class to sort an array of integers accepted form user

class Sort{
    public static void main(String args[]){
        int size=Integer.parseInt(args[0]);
        int[] arr=new int[size];
        int i=0;
        for(i=0;i<size;i++){
            arr[i]=Integer.parseInt(args[i+1]);
        }
        int temp;
        for(i=0;i<size;i++){
            for(int j=i+1;j<size;j++){
                if(arr[j]<arr[i]){
                    temp=arr[j];
                    arr[j]=arr[i];
                    arr[i]=temp;
                }
            }
        }
        for(i=0;i<size;i++){
            System.out.println(arr[i]);
        }
    }
}



Compile:
javac Sort.java

Run:
(First parameter is the size of array, followed by those many elements of array)

eg1. java Sort 3 7 4 9
eg2. java Sort 4 3 2 1 4

String class

Instance Methods of String class
1.       char charAt(int index)
2.       boolean equals(String str)
3.       boolean equalsIgnoreCase(String str)
4.       int compareTo(String other)
5.       int compareToIgnoreCase(String other)
6.       String concat(String str)
7.       boolean endsWith(String str)
8.       boolean startsWith(String str)
9.       byte[] getBytes(); // uses default charset of platform
10.   byte[] getBytes(String charsetName)
11.   int indexOf(int ch)
12.   int indexOf(int ch, int fromIndex)
13.   int indexOf(String str)
14.   int indexOf(String str, int fromIndex)
15.   int lastIndexOf(int ch)
16.   int lastIndexOf(int ch, int fromIndex)
17.   int length();
18.   String replace(char old, char new)
19.   String replace(String old, String new)
20.   String replaceFirst(String old, String new)
21.   String[] split(String breakPoint)
22.   String substring(int beginIndex)
23.   String substring(int beginIndex, int endIndex)
24.   char[] toCharArray()
25.   String toLowerCase()
26.   String toUpperCase()
27.   String trim()
28.   static String valueOf( Any Primitive Type)

Arrays in Java

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've used arrays already, in the C Language. This section discusses arrays in Java


Illustration of an array as 10 boxes numbered 0 through 9; an index of 0 indicates the first element in the array
An array of ten elements

Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.
The following program, ArrayDemo, creates an array of integers, puts some values in it, and prints each value to standard output.

class ArrayDemo {
    public static void main(String[] args) {
        // declares an array of integers
        int[] anArray;

        // allocates memory for 3 integers
        anArray = new int[3];
           
        // initialize first element
        anArray[0] = 100;
        // initialize second element
        anArray[1] = 200;
        // etc.
        anArray[2] = 300;
        System.out.println("Element at index 0: "
                           + anArray[0]);
        System.out.println("Element at index 1: "
                           + anArray[1]);
        System.out.println("Element at index 2: "
                           + anArray[2]);
        
    }
} 
The output from this program is:
Element at index 0: 100
Element at index 1: 200
Element at index 2: 300 
 
In a real-world programming situation, you'd probably use one of the supported looping 

constructs  to iterate through each element of the array, rather than write each 
line individually as shown above. However, this example clearly illustrates the 
array syntax. 

Declaring a Variable to Refer to an Array

The above program declares anArray with the following line of code:
// declares an array of integers
int[] anArray;
Like declarations for variables of other types, an array declaration has two components: the array's type and the array's name. An array's type is written as type[], where type is the data type of the contained elements; the square brackets are special symbols indicating that this variable holds an array. The size of the array is not part of its type (which is why the brackets are empty). An array's name can be anything you want, provided that it follows the rules and conventions as previously discussed in the naming section. As with variables of other types, the declaration does not actually create an array — it simply tells the compiler that this variable will hold an array of the specified type.
Similarly, you can declare arrays of other types:
byte[] anArrayOfBytes;
short[] anArrayOfShorts;
long[] anArrayOfLongs;
float[] anArrayOfFloats;
double[] anArrayOfDoubles;
boolean[] anArrayOfBooleans;
char[] anArrayOfChars;
String[] anArrayOfStrings;
You can also place the square brackets after the array's name:
// this form is discouraged
float anArrayOfFloats[];
However, convention discourages this form; the brackets identify the array type and should appear with the type designation.

Creating, Initializing, and Accessing an Array

One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates an array with enough memory for ten integer elements and assigns the array to theanArray variable.
// create an array of integers
anArray = new int[10];
If this statement were missing, the compiler would print an error like the following, and compilation would fail:
ArrayDemo.java:4: Variable anArray may not have been initialized.
The next few lines assign values to each element of the array:
anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // etc.
Each array element is accessed by its numerical index:
System.out.println("Element 1 at index 0: " + anArray[0]);
System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);
Alternatively, you can use the shortcut syntax to create and initialize an array:
int[] anArray = { 
    100, 200, 300,
    400, 500, 600, 
    700, 800, 900, 1000
};
Here the length of the array is determined by the number of values provided between { and }.
You can also declare an array of arrays (also known as a multidimensional array) by using two or more sets of square brackets, such as String[][] names. Each element, therefore, must be accessed by a corresponding number of index values.
In the Java programming language, a multidimensional array is simply an array whose components are themselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the rows are allowed to vary in length(RAGGED/JAGGED ARRAYS) , as shown in the followingMultiDimArrayDemoprogram:

class MultiDimArrayDemo {
    public static void main(String[] args) {
        String[][] names = {
            {"Mr. ", "Mrs. ", "Ms. "},
            {"Smith", "Jones"}
        };
        // Mr. Smith
        System.out.println(names[0][0] + names[1][0]);
        // Ms. Jones
        System.out.println(names[0][2] + names[1][1]);
    }
}
The output from this program is:
Mr. Smith
Ms. Jones
Finally, you can use the built-in length property to determine the size of any array. The code
 System.out.println(anArray.length);
will print the array's size to standard output.

Account class with 3 overloaded constructors, deposit & withdraw facility (With Security)

class Account{
int accountNo;
String holderName;
double balance;

Account(){
accountNo=0;
holderName="Unnamed";
balance=0;
}

Account(int accountNo, String h, double b){
this.accountNo = accountNo;
this.holderName = h;
this.balance = b;
}

Account(int accountNo, String h){
this.accountNo = accountNo;
this.holderName = h;
this.balance = 0;
}

void printDetails(){
System.out.println("\n\nInfo of Account:"+ this.accountNo);
System.out.println("----------------------");
System.out.println("Balance of "+ this.accountNo +" is " +this.balance);
System.out.println("Name of object is "+this.holderName);
System.out.println("No of object is "+this.accountNo);
}

void deposit(double amt){
if(amt>0){
this.balance +=  amt;
}
else{
System.out.println("Negative Amount cannot be deposited");
}
}
void withdraw(double amt){
if(amt <= this.balance){
this.balance -= amt;
}
else{
System.out.println("Insufficient balance. Cannot do withdrawal");
}
}
}
class TestAccount{
public static void main(String[] args){
int i = 6;
Account a1 = new Account();
Account a2 = new Account(1001, "Abcd");
Account a3 = new Account(1001, "Efgh", 200);

a2.deposit(100);
a2.withdraw(500);
a2.printDetails();

}
}










Shape class with Rect & Cirlce as subclasses

class Shape{
double area;
}
class Rect extends Shape{
int l;
int w;

Rect(int length , int w){
this.l = length;
this.w = w;
}
Rect(){
this.l = 0;
this.w= 0;
}
double getArea(){
return this.l * this.w;
}
}
class Circle extends Shape{
int radius;
Circle(int r){
this.radius = r;
}
Circle(){
this.radius = 0;
}
double getArea(){
return 3.1428 * this.radius* this.radius;
}
}
class TestShapes{
public static void main(String args[]){
Rect r1 = new Rect(5,5);
Circle c = new Circle(5);
System.out.println("Area of r1 is: "+ r1.getArea());
System.out.println("Area of c is: "+ c.getArea());

}
}

Program for Auto Generation of Employee ID & Creating 5 Objects

class Employee{
static int noOfObjects=0;
int id;
String name;
double salary;

Employee(String name, double salary){
this.id = noOfObjects;
this.name = name;
this.salary= salary;
noOfObjects++;
}
void print(){
System.out.println("Emp Details\n--------------\n"+this.id+"\t"+this.name+"\t"+this.salary);
}

}
class TestEmployee{
public static void main(String[] args){
Employee e1 = new Employee("Abcd", 12000);
Employee e2 = new Employee("Efgh", 2000);
                Employee e3 = new Employee("Qwert", 14000);
                Employee e4 = new Employee("Poioi", 19000);
                Employee e5 = new Employee("dfsdfsfs", 22000);

e1.print();
e2.print();
                e3.print();
                e4.print();
                e5.print();
}
}