Showing posts with label Basics. Show all posts
Showing posts with label Basics. Show all posts

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();
}
}

Program to create Array of Dynamic Size & take values from Command Line

import java.util.Scanner;

class Demo{
public static void main(String[] args){
int no = Integer.parseInt(args[0]);
String[] arr = new String[no];

for(int i = 0 ; i< no;i++){
arr[i] = args[i+1];
System.out.println(arr[i]);
}


}
}


How to run:
java Demo 3 vadodara anand delhi

Output:
vadodara
anand
delhi



Explain "abstract" keyword

abstract is a keyword in java which is used as a modifier for methods and classes. Abstract methods do not have body(implementation). e.g. abstract void m1();

If a method does not have body, it must be declared to be abstract. If a method is abstract, the class must also be abstract. However abstract classes are classes for which objects cannot be created. If class is abstract, it is not necessary that method(s) should be abstract. A class having no abstract methods may also be declared to be abstract meaning that objects cannot be created for it.
eg.

abstract class A{
        abstract void m1();
        void m2(){

}
}
-          Here since m1 is abstract method, class also must be abstract.
abstract class A{
        void m1(){

}
}
-          Here, even though m1 is not abstract, class can be abstract - meaning objects cannot be created of class A

abstract class A{
        abstract void m1();
}
class B extends A{
        void m1(){

        }
}
- Here, since class A is having a abstract method, class B must override/implement the method. Otherwise, B will inherit that abstract method from A, and B also needs to be an Abstract Class then.


- Abstract classes can have constructors
(But objects cannot be created. Then what's the use of constructor? )
Abstract classes have constructors which cannot be directly invoked to create objects but are invoked by subclasses using super()

Explain "final" keyword

final is a keyword in java which is used as a modifier for variables, methods and classes.
Final variables cannot be reassigned values. Once given, the value of a final variable cannot be changed. For final instance variables, you may assign value then and there, or in the constructor once. For final local variables within methods, value must be assigned before using the variable. The value cannot be changed for final variable. Final and static when used together with variables, define a constant in java. static means single copy and final means value cannot change. - Show simple example.
Final methods cannot be overridden. The subclass cannot redefine the method if superclass declares the method to be final. – Show simple example.

Final classes cannot be extended. Subclasses cannot be created for a final class. So a final class is typically a leaf class in the class heirarcgy – Show simple example

Explain "static" keyword

a.       static is a keyword in java which is used as a modifier for variables and methods within a class. static means something which belongs to the class and not to every object. If a property is static, only 1 copy is maintained for that property per class. Separate copies are not created for every object. Similary static methods are also invoked on the class and not on objects. Since static methods are not invoked on objects, we cannot use “this” keyword within static methods. Syntax of using static variables and methods is

ClassName.variable= value  (or)  ClassName.method();

In java we also have a concept of a static block which is written within a class. A static block of code is executed when the class is initially loaded by the class loader of jvm.

How to declare static?
 class A{
      static int I;           // static variable
      static void m1(){
                                      // static method
}
      static{
                                      // static block
}
}
How to use?
A.i=5;                          // assigning value to static variable: ClassName.variable
A.m1();                       //invoking a static method: ClassName.method()
     

A static variable is often called as a class variable as it is a property of the class. A static method cannot use instance variables. It can use static variables only. Static variables are often used to count the number of objects created or to manage some global constant accessible from anywhere by using the class name. Also write a simple code to show use of static. 

Garbage Collection in Java

·         objects are created on heap area in Java  irrespective of their scope e.g. local or member variable.
·         Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection.
·         Garbage collection relieves java programmer from memory management which is essential part of C++ programming and gives more time to focus on business logic.
·         Garbage collector works on Mark and Sweep algorithm and is lineant in its operation.
·         Garbage Collection in Java is carried by a daemon thread called Garbage Collector.
(daemon=background)
·         Before removing an object from memory Garbage collection thread invokes finalize () method of that object and gives an opportunity to perform any sort of cleanup required.
·         You as Java programmer can not force Garbage collection in Java; it will only trigger if JVM thinks it needs a garbage collection based on Java heap size.
·         There are methods like System.gc () and Runtime.gc () which is used to send request of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen.
·         JVM supports many different implementations of Garbage collectors.. Many are bundled into J2SE also. An application may choose the GC according to the needs (In case of advance programming needs).
·         One thing is assured, that before the Garbage Collector reclaims and object and releases its memore, it will invoke the protected method finalize() on the object. This method is invoked only once on an object during its life time and that too at the end of life time.


Since Garbage Collection is automatic in Java, memory management errors get reduced in java which may occur in case of manual memory allocation and de-allocation. Allocation part is take care of by constructors in java and de-allocation by Garbage Collector, thereby automating the memory mgmt. in java completely.