Java basics


Click here to download eclipse supported ZIP file




When we consider a Java program it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what do class, object, methods and instance variables mean.

  • Object - Objects have states and behaviours. Example: A dog has states - colour, name, breed as well as behaviours -wagging, barking, eating. An object is an instance of a class.

  • Class - A class can be defined as a template/ blue print that describes the behaviours/states that object of its type support.

  • Methods - A method is basically a behaviour. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.

  • Instance Variables - Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.

First Java Program:

Let us look at a simple code that would print the words Hello World.

 

    

package com.cv.java.oops;
/**
 @author Chandra Vardhan
 
 */
public class MyFirstJavaProgram {

   /* This is my first java program.  
    * This will print 'Hello World' as the output
    */
  
    public static void main(String[] args) {
       System.out.println("Hello World")// prints Hello World
    }

Let's look at how to save the file, compile and run the program. Please follow the steps given below:

  • Open notepad and add the code as above.

  • Save the file as: MyFirstJavaProgram.java.

  • Open a command prompt window and go to the directory where you saved the class. Assume it's C:\.

  • Type ' javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption : The path variable is set).

  • Now, type ' java MyFirstJavaProgram ' to run your program.

  • You will be able to see ' Hello World ' printed on the window.

C:\> javac MyFirstJavaProgram.java
C:\> java MyFirstJavaProgram 
Hello World

Basic Syntax:

About Java programs, it is very important to keep in mind the following points.

  • Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would have different meaning in Java.

  • Class Names - For all class names the first letter should be in Upper Case.

    If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.

    Example class MyFirstJavaClass

  • Method Names - All method names should start with a Lower Case letter.

    If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.

    Example public void myMethodName()

  • Program File Name - Name of the program file should exactly match the class name.

    When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match your program will not compile).

    Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'

  • public static void main(String args[]) - Java program processing starts from the main() method which is a mandatory part of every Java program.

Java Identifiers:

All Java components require names. Names used for classes, variables and methods are called identifiers.

In Java, there are several points to remember about identifiers. They are as follows:

  • All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).

  • After the first character identifiers can have any combination of characters.

  • A key word cannot be used as an identifier.

  • Most importantly identifiers are case sensitive.

  • Examples of legal identifiers: age, $salary, _value, __1_value

  • Examples of illegal identifiers: 123abc, -salary

Java Modifiers:

Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers:

  • Access Modifiers: default, public , protected, private

  • Non-access Modifiers: final, abstract, strictfp

We will be looking into more details about modifiers in the next section.

Java Variables:

We would see following type of variables in Java:

  • Local Variables
  • Class Variables (Static Variables)
  • Instance Variables (Non-static variables)

Java Arrays:

Arrays are objects that store multiple variables of the same type. However, an array itself is an object on the heap. We will look into how to declare, construct and initialize in the upcoming chapters.

Java Enums:

Enums were introduced in java 5.0. Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums.

With the use of enums it is possible to reduce the number of bugs in your code.

For example, if we consider an application for a fresh juice shop, it would be possible to restrict the glass size to small, medium and large. This would make sure that it would not allow anyone to order any size other than the small, medium or large.

Example:

 

    



package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
class FreshJuice {

   enum FreshJuiceSizeSMALL, MEDIUM, LARGE }
   FreshJuiceSize size;
}

public class FreshJuiceTest {

   public static void main(String args[]){
      FreshJuice juice = new FreshJuice();
      juice.size = FreshJuice.FreshJuiceSize.MEDIUM ;
      System.out.println("Size: " + juice.size);
   }
}

Above example will produce the following result:

Size: MEDIUM

Note: enums can be declared as their own or inside a class. Methods, variables, constructors can be defined inside enums as well.

Java Keywords:

The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names.

abstract assert boolean break
byte case catch char
class const continue default
do double else enum
extends final finally float
for goto if implements
import instanceof int interface
long native new package
private protected public return
short static strictfp super
switch synchronized this throw
throws transient try void
volatile while

Comments in Java

Java supports single-line and multi-line comments very similar to c and c++. All characters available inside any comment are ignored by Java compiler.

 

    

package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class MyFirstJavaProgram2 {

   /* This is my first java program.
    * This will print 'Hello World' as the output
    * This is an example of multi-line comments.
    */

    public static void main(String[] args){
       // This is an example of single line comment
       /* This is also an example of single line comment. */
       System.out.println("Hello World")
    }

Using Blank Lines:

A line containing only white space, possibly with a comment, is known as a blank line, and Java totally ignores it.

Inheritance:

In Java, classes can be derived from classes. Basically if you need to create a new class and here is already a class that has some of the code you require, then it is possible to derive your new class from the already existing code.

This concept allows you to reuse the fields and methods of the existing class without having to rewrite the code in a new class. In this scenario the existing class is called the superclass and the derived class is called the subclass.

Interfaces:

In Java language, an interface can be defined as a contract between objects on how to communicate with each other. Interfaces play a vital role when it comes to the concept of inheritance.

An interface defines the methods, a deriving class(subclass) should use. But the implementation of the methods is totally up to the subclass.

What is Next?


 

    
package com.cv.java.oops;

import java.lang.reflect.Constructor;


/**
 @author Chandra Vardhan
 
 */
public class AccessingSingletonClass {

  /**
   @param args
   @throws ClassNotFoundException 
   */
  public static void main(String[] argsthrows ClassNotFoundException {
    
    //MySingleton mySingleton = MySingleton.getInstance();
    //System.out.println(mySingleton);
    
    Class ccc = Class.forName("com.cv.java.oops.AccessingSingletonClass");
    Constructor[] cons = ccc.getDeclaredConstructors();
    for (int i = 0; i < cons.length; i++) {
      
      cons[i].setAccessible(true);
      Class name = cons[i].getClass();
      
      System.out.println(name);
      
    }
    System.out.println(cons);

  }

}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class AutoBoxing {

  
  static Integer i = 10;//AutoBoxing
  /**
   @param args
   */
  public static void main(String[] args) {  

    int i2= i;//AutoUNBoxing
    m1(i2);
  }
  private static void m1(Integer i2) {//AutoBoxing
  
    int i3= i2;//AutoUNBoxing
    System.out.println(i3);
    
  }

}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class AutoBoxing2 {

  static Integer i = 0;
  static Integer i2;

  /**
   @param args
   */
  public static void main(String[] args) {
    int k = i;
    // int k2 = i2;//NullPE
    System.out.println(k);//0
    // System.out.println(k2);//NullPE

    Integer x = 10;

    Integer y = x;
    x++;
    System.out.println(x);// 11

    System.out.println(y);// 10

    System.out.println(x == y);// F

    Integer integer = new Integer(10);
    Integer integer2 = new Integer(10);
    System.out.println(integer == integer2);//F

    Integer integer3 = 100;

    System.out.println(integer == integer3);//F

    Integer integer4 = 100;

    System.out.println(integer3 == integer4);//T
    
    
    
    Integer integer5 = new Integer(1000);
    Integer integer6 = new Integer(1000);
    System.out.println(integer5 == integer6);//F

    Integer integer7 = 1000;

    System.out.println(integer5 == integer7);//F

    Integer integer8 = 1000;

    System.out.println(integer7 == integer8);//F
    
    
  }

}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class AutoboxingVsVarArg {

  public static void m1(Integer I) {
    System.out.println("Autoboxing");
  }

  public static void m1(int... i) {
    System.out.println("var-arg");
  }

  public static void main(String[] args) {
    int x = 10;
    m1(x);
  }

}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class Cat {
  int j;

  Cat(int j) {
    this.j = j;
  }

}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class CatDogShallowCloning {
  
  public static void main(String[] argsthrows CloneNotSupportedException {
    Cat c = new Cat(10);
    Dog d = new Dog(10, c);
    Dog d2 = (Dogd.Clone();
    d.i = 222;
    d.c.j = 333;
    System.out.println(d2.i + "============" + d2.c.j);
  }

}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class Clone  implements Cloneable {

  private int i = 10, j = 20;

  /**
   
   */
  public Clone() {

  }

  public Clone(int i, int j) {
    this.i = i;
    this.j = j;
  }

  public Clone(int i) {
    this.i = i;
  }

  @Override
  public String toString() {
    return "Clone [i=" + i + ", j=" + j + "]";
  }

  @Override
  protected Object clone() throws CloneNotSupportedException {
    return new Clone(i,j);
  }
}


 

    
package com.cv.java.oops;


/**
 @author Chandra Vardhan
 
 */
public class CloneTest {

  /**
   @param args
   */
  public static void main(String[] args) {

    Clone clone = new Clone(8,9);

    Clone clone2 = new Clone(8,9);
    clone = clone2;

    System.out.println(clone == clone2);//true

    try {
      Object object = clone.clone();

      System.out.println(object.hashCode());//

      System.out.println(clone.hashCode());//

      System.out.println(object.equals(clone));// Even though two
                            // objects are equal
                            // by equals(Object)
                            // method clone does
                            // not return
                            // true...

      System.out.println(object != clone);//true
      // even though object are
      // same but its cloned
      // values are different.

      System.out.println(object.getClass() == clone.getClass());//true

      System.out.println(object == clone);// false

    catch (CloneNotSupportedException e) {
      e.printStackTrace();
    }

  }

}


 

    

package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class DeepVsShallowClone implements Cloneable {

  private int i = 10, j = 20;

  /**
   
   */
  public DeepVsShallowClone() {

  }

  public DeepVsShallowClone(int i, int j) {
    this.i = i;
    this.j = j;
  }

  @Override
  public String toString() {
    return "Clone [i=" + i + ", j=" + j + "]";
  }

  /**
   @param args
   @throws CloneNotSupportedException
   */
  public static void main(String[] argsthrows CloneNotSupportedException {

    System.out.println(" Deep cloning... ");

    DeepVsShallowClone clone = new DeepVsShallowClone(23);
    System.out.println(clone);// Clone [i=2, j=3]

    DeepVsShallowClone clone2 = (DeepVsShallowCloneclone.clone();// deep
                                    // cloning...

    System.out.println(clone2);// Clone [i=2, j=3]

    clone2.i = 1000;
    clone2.j = 2000;
    System.out.println(clone2);// Clone [i=1000, j=2000]
    System.out.println(clone);// Clone [i=2, j=3]

    System.out.println("=========================================");

    System.out.println(" Shallow cloning... ");

    DeepVsShallowClone clone3 = new DeepVsShallowClone(23);
    System.out.println(clone3);// Clone [i=2, j=3]

    DeepVsShallowClone clone4 = clone3;// Shallow cloning...
    System.out.println(clone4);// Clone [i=2, j=3]
    clone4.i = 1000;
    clone4.j = 2000;// If we change one object then remaining also
            // effected...
    System.out.println(clone4);// Clone [i=1000, j=2000]
    System.out.println(clone3);// Clone [i=1000, j=2000]

    // Here is the actual object if effected...

  }

}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class Dog implements Cloneable {
  int i;
  Cat c;

  Dog(int i, Cat c) {
    this.i = i;
    this.c = c;
  }

  public Object Clone() throws CloneNotSupportedException {

    return clone();

  }
}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class EqaulsCheck {

  /**
   @param args
   */
  public static void main(String[] args) {

    Student student = new Student("chote"1228);

    Student student2 = new Student("dev"1229);

    Student student3 = new Student("chote"1228);

    Student student4 = student;

    System.out.println(student.equals(student2));//f

    System.out.println(student2.equals(student3));//f

    System.out.println(student3.equals(student4));// True(if we override
                            // equals(-) method in
                            // Student class...

    System.out.println(student4.equals(student));//t

    System.out.println(student == student4);//t

  }

}


 

    
/**
 
 */
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class EqualHashcode {

  /**
   
   */
  public EqualHashcode() {

  }

  /**
   @param args
   */
  public static void main(String[] args) {

    String string = new String("c");

    String string2 = string;

    System.out.println(string == string2);// Object class equals(-)method
                        // will execute.

    System.out.println(string.hashCode());
    System.out.println(string2.hashCode());
    System.out.println("===============");
  }

}


 

    
/**
 
 */
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 *
 */
public class EqualsTest {

  /**
   @param args
   */
  public static void main(String[] args) {

    Integer integer = 34;
    int l = 34;
    if (integer.equals(l)) {
      System.out.println("true");
    else {
      System.out.println("false");
    }

  }

}


 

    
/**
 
 */
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class FinalImmutable {

  /**
   
   */
  public FinalImmutable() {

  }

  /**
   @param args
   */
  public static void main(String[] args) {

    final StringBuffer buffer = new StringBuffer("cv");
    
    buffer.append("kodam");
    
    System.out.println(buffer);
    
    StringBuffer buffer2  = new StringBuffer("chandra");
    
//    buffer = buffer2; //re-assignment not possible ...
    
    System.out.println(buffer.capacity());//16+2

  }

}


 

    
package com.cv.java.oops;

import java.util.HashMap;
import java.util.Map;


/**
 @author Chandra Vardhan
 
 */
public class HashCodeEqualsImportance {

  public HashCodeEqualsImportance() {

  }

  /**
   @param args
   */
  public static void main(String[] args) {

    Map<KeyWithHash, Integer> map = new HashMap<KeyWithHash, Integer>();

    KeyWithHash key = new KeyWithHash(1);
    KeyWithHash key2 = new KeyWithHash(2);
    KeyWithHash key3 = new KeyWithHash(3);
    System.out.println("hashCode for "+key.getValue()+" is : " + key.hashCode());

    map.put(key, 111);
    map.put(key2, 222);
    map.put(key3, 333);

    for (Map.Entry<KeyWithHash, Integer> entry : map.entrySet()) {
      System.out.println(entry.getKey().getValue() "," + entry.getValue());
    }

    KeyWithHash key5 = new KeyWithHash(1);
    System.out.println("hashCode for "+key5.getValue()+" is : " + key5.hashCode());
    Integer integer = map.get(key5);// If you did not override
                    // equals(-),hashCode() method(in KeyWithHash
                    // class) then u
                    // will get null..

    System.out.println(integer);

    System.out.println("======================================================");

    Map<Key, Integer> map2 = new HashMap<Key, Integer>();

    Key key6 = new Key(1);
    Key Key7 = new Key(2);
    Key Key8 = new Key(3);
    System.out.println("hashCode for "+key6.getValue()+" is : " +key6.hashCode());

    map2.put(key6, 111);
    map2.put(Key7, 222);
    map2.put(Key8, 333);

    for (Map.Entry<Key, Integer> entry : map2.entrySet()) {
      System.out.println(entry.getKey().getValue() "," + entry.getValue());

    }

    Key key9 = new Key(1);
    System.out.println("hashCode for "+key9.getValue()+" is : " +key9.hashCode());
    Integer integer2 = map2.get(key9);// If you did not override
                      // equals(-),hashCode() method(in
                      // Key class) then u
                      // will get null..

    System.out.println(integer2);
  }

}


 

    

package com.cv.java.oops;

/**
 @author Chandra Vardhan
 *
 */
public class HashCodeTest {
  
  private int i ;
  /**
   
   */
  public HashCodeTest() {
    
  }
  public HashCodeTest(int i) {
    this.i = i;    
  }
  
  
  @Override
  public int hashCode() {
    System.out.println("hashCode() called");
    final int prime = 31;
    int result = 1;
    result = prime * result + i;
    return result;
  }
  /**
   @param args
   */
  @Override
  public boolean equals(Object obj) {
    System.out.println("equals() called...");
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    HashCodeTest other = (HashCodeTestobj;
    if (i != other.i)
      return false;
    return true;
  }
  
  

  
  public static void main(String[] args) {
    HashCodeTest hash1 = new HashCodeTest(10);
    HashCodeTest hash2 = new HashCodeTest(10);
    System.out.println(hash1);
    System.out.println(hash2);
    if(hash1.equals(hash2)) {      
      System.out.println(" both equal");
    else {
      System.out.println(" not equal");
    }      
  }
}


 

    
/**
 
 */
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public final class Immutable {

  private int i;

  /**
   
   */
  public Immutable(int i) {
    this.i = i;
  }

  public synchronized Immutable modify(int i) {

    if (this.i == i) {
      return this;
    else {
      return new Immutable(i);
    }

  }

  /**
   @param args
   */
  public static void main(String[] args) {

    Immutable immutable = new Immutable(10);
    Immutable immutable2 = immutable.modify(100);
    Immutable immutable3 = immutable.modify(10);
    Immutable immutable4 = immutable2.modify(10);
    
    Immutable immutable5 = immutable3.modify(10);
    System.out.println(immutable == immutable2);//F
    
    System.out.println(immutable == immutable3);//T
    System.out.println(immutable == immutable5);//T
    
    System.out.println(immutable == immutable4);//F
    
    System.out.println(immutable2 == immutable3);//F
    
    System.out.println(immutable2 == immutable4);//F
    System.out.println(immutable3 == immutable4);//F
    
  }

}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class InstanceAndStaticUsage {

  static {
    System.out.println("static block");
  }

  {
    System.out.println("instance block");
  }

  public InstanceAndStaticUsage() {
    System.out.println("constructor...");
  }

  /**
   @param args
   */
  public static void main(String[] args) {
    System.out.println("main()");
    new InstanceAndStaticUsage();

  }

}


 

    
/**
 
 */
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 *
 */
public class InstanceStaticTest {

  private String name = "Chandra";

  private static final String CLG_NAME = "KITS";

  public void instanceMethod() {
    System.out.println(name);
    System.out.println(CLG_NAME);
    staticMethod();
  }

  public static void staticMethod() {
//    System.out.println(name); //Cann't access the instance variables directly...
    System.out.println(CLG_NAME);
  }

  public static void main(String[] args) {
    InstanceStaticTest instanceObject = new InstanceStaticTest();
    instanceObject.instanceMethod();
    System.out.println(instanceObject.name);
    System.out.println(CLG_NAME);
  }
}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class IntegerBuffer {

  /**
   @param args
   */
  public static void main(String[] args) {

    Integer x = new Integer(10);

    Integer y = new Integer(10);

    System.out.println(x == y);// F

    System.out.println("=================================");
    
    Integer x1 = new Integer(10);

     Integer y1 = 10;

    System.out.println(x1 == y1);// F

    System.out.println("=================================");

    Integer x2 = 10;

    Integer y2 = 10;

    System.out.println(x2 == y2);// T(Bcoz these are there in buffer...)

    System.out.println("=================================");

    Integer x3 = 128;// Upto 127 it is true....

    Integer y3 = 128;

    System.out.println(x3 == y3);// T(Bcoz these are there in buffer...)

    System.out.println("=================================");

    Integer x4 = Integer.valueOf(10);// valueOf(-)method developed by
    // following auto boxing.

    Integer y4 = 10;

    System.out.println(x4 == y4);// T(Bcoz these are there in buffer...)

    System.out.println("=================================");

    Integer x5 = Integer.valueOf(10);// valueOf(-)method developed by
    // following auto boxing.

    Integer y5 = Integer.valueOf(10);

    System.out.println(x5 == y5);// T(Bcoz these are there in buffer...)

    System.out.println("=================================");
    
  
  }

}


 

    
/**
 
 */
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class IntegerImmutableCheck {

  /**
   @param args
   */
  public static void main(String[] args) {

    Integer x = 10;

    System.out.println(x.hashCode());
    Integer y = x;

    System.out.println(y.hashCode());
    x++;
    System.out.println("val of x===" + x);

    System.out.println(x.hashCode());

    System.out.println("val of y===" + y);

    System.out.println(x == y);

    System.out.println("======================================");

    Integer x1 = 1000;
    Integer y1 = x1;
    x1++;
    System.out.println("val of x1===" + x1);

    System.out.println("val of y1===" + y1);

    System.out.println(x1 == y1);// Becoz Integer objects are immutable...

  }

}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class IntegerTest {

  /**
   @param args
   */
  public static void main(String[] args) {
    Integer x = 10;

    Integer y = x;

    System.out.println(x == y);// T

    System.out.println("=================================");

    ++x;

    System.out.println(x);
    System.out.println(y);
    System.out.println("=================================");

    
    
  }

}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class Key {

  private int value;

  public Key(int i) {
    this.value=i;
  }

  public int getValue() {
    return value;
  }

  public void setValue(int value) {
    this.value = value;
  }


}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class KeyWithHash {

  private int value;

  public KeyWithHash(int i) {
    this.value=i;
  }

  public int getValue() {
    return value;
  }

  public void setValue(int value) {
    this.value = value;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + value;
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    KeyWithHash other = (KeyWithHashobj;
    if (value != other.value)
      return false;
    return true;
  }

}


 

    
package com.cv.java.oops;


/**
 @author Chandra Vardhan
 
 */
public class PrintingFormat {
  public static void main(String[] args) {
    for (int i = 1; i < 5; i++) {
      for (int j = 0; j < i; j++) {
        System.out.print(" $ ");
      }
      System.out.println();
    }
    for (int i = 4; i >= 0; i--) {
      for (int j = 1; j < i; j++) {
        System.out.print(" $ ");
      }
      System.out.println();

    }

  }

}


 

    
/**
 
 */
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class ProtectedMember {
  
  protected String name = "cv";

  protected ProtectedMember() {
    System.out.println("cons...");
  }
  

  protected String getName() {
    return name;
  }
}


 

    
/**
 
 */
package com.cv.java.oops;


/**
 @author Chandra Vardhan
 
 */
public class ProtectedTestNotSubClass {//Not a child class.

  /**
   
   */
  public ProtectedTestNotSubClass() {

  }

  /**
   @param args
   */
  public static void main(String[] args) {

    m1();

  }

  private static void m1() {

    ProtectedTestNotSubClass protectedTest = new ProtectedTestNotSubClass();
    
//    System.out.println(protectedTest.name); not accessing here...
    
    ProtectedMember member = new ProtectedMember();
    System.out.println(member.name);//accessing here... with parent class object...

  }
}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class ProtectedTestSubClass extends ProtectedMember {

  /**
   
   */
  public ProtectedTestSubClass() {

  }

  /**
   @param args
   */
  public static void main(String[] args) {

    m1();

  }

  private static void m1() {

    // In the same package both the things are possible... Like accessing
    // with the parent reference and child reference...

    // parent object and child object...

    ProtectedTestSubClass protectedTestSubClass = new ProtectedTestSubClass();

    System.out.println(protectedTestSubClass.name);// access here... with
                            // child class object...

    // Bcoz classes are there in inheritance relationship..

    ProtectedMember member = new ProtectedMember();
    System.out.println(member.name);// accessing here... with parent class
                    // object...

    ProtectedMember member2 = new ProtectedTestSubClass();

    System.out.println(member2.name);// accessing here... with parent
                      // reference and child object...

  }
}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class ReverseString {
  public static void main(String[] args) {
    String original = "chandra";

    String reverse = "";

    int length = original.length();

    for (int i = length - 1; i >= 0; i--)
      reverse += original.charAt(i);

    System.out.println("Reverse of entered string is: " + reverse);
  }
}


 

    
/**
 
 */
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 *
 */
public class SBuffer {

  /**
   
   */
  public SBuffer() {
  
  }

  /**
   @param args
   */
  public static void main(String[] args) {
    
    StringBuffer buffer = new StringBuffer();
    
    StringBuffer buffer9 = new StringBuffer("chote");
    
    System.out.println(buffer9.capacity());//21==>5+16
    
    System.out.println(buffer.capacity());//16
    
    StringBuffer buffer2 = buffer.append("chandravardhanko");//16 added
    
    System.out.println(buffer2);
    
    System.out.println(buffer.capacity());
    System.out.println(buffer2.capacity());
    
    buffer.append("d");
    System.out.println(buffer.capacity());
    
    buffer.append("chandravardhanko");
    buffer.append("chandravardhanko");
    
    buffer.append("chandravardhanko");
    System.out.println(buffer);
    
    System.out.println(buffer.capacity());
     

  }

}


 

    
/**
 
 */
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class SBufferMethods {

  /**
   
   */
  public SBufferMethods() {

  }

  /**
   @param args
   */
  public static void main(String[] args) {

    StringBuffer buffer = new StringBuffer("chote");
    System.out.println(buffer.length());// 5

    System.out.println(buffer.capacity());// 21

    System.out.println(buffer.charAt(3));// t
    // System.out.println(buffer.charAt(30));//java.lang.StringIndexOutOfBoundsException:

    buffer.setCharAt(4'u');

    System.out.println(buffer);

    StringBuffer buffer2 = new StringBuffer();

    buffer2.append("PI value is:").append("\t").append(3.14).append("\t")
        .append("It is exactly...");
    buffer2.append(true);
    System.out.println(buffer2);

    buffer.insert(4"kodam");

    System.out.println(buffer);

    System.out.println(buffer.delete(49));// chotu

    System.out.println(buffer.deleteCharAt(4));// chot

    System.out.println(buffer.reverse());// tohc

    StringBuffer buffer3 = new StringBuffer("aiswaryaabhi");

    buffer3.setLength(8);

    System.out.println(buffer3);

    buffer3.setLength(89);

    System.out.println(buffer3);

    StringBuffer buffer4 = new StringBuffer();

    System.out.println(buffer4.capacity());

    buffer4.ensureCapacity(1000);

    System.out.println(buffer4.capacity());

    StringBuffer buffer5 = new StringBuffer("chotechote");

    System.out.println(buffer5.capacity());

    buffer5.ensureCapacity(27);

    System.out.println(buffer5.capacity());
    
    
    StringBuffer buffer6 = new StringBuffer(1000);
    buffer6.append("chote");
    buffer6.trimToSize();
    System.out.println(buffer6.length());
    System.out.println(buffer6.capacity());

  
  }

}


 

    
/**
 
 */
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 *
 */
public class SBufferTrimToSize {

  

  /**
   @param args
   */
  public static void main(String[] args) {
    
    StringBuffer buffer = new StringBuffer("  chote is looking good  ");
    
    System.out.println(buffer.length());
    
    System.out.println(buffer.capacity());
    
    System.out.println(buffer);
    
    buffer.trimToSize();
    
    System.out.println(buffer.length());
    
    System.out.println(buffer.capacity());
     

  }

}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class Singleton {

  private static Singleton singleton = new Singleton();

  /*
   * A private Constructor prevents any other class from instantiating.
   */
  private Singleton() {
  }

  /* Static 'instance' method */
  public static synchronized Singleton getInstance() {
    return singleton;
  }

  public static void main(String[] args) {
    Singleton singletondemo1 = Singleton.getInstance();
    System.out.println(singletondemo1.hashCode());
    Singleton singletondemo2 = Singleton.getInstance();
    System.out.println(singletondemo2.hashCode());
  }
}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 */
public class StaticVsInstanceVariable {

  static int x = 20;
  int y = 10;

  /**
   @param args
   */
  public static void main(String[] args) {

    StaticVsInstanceVariable t = new StaticVsInstanceVariable();
    t.x = 999;
    t.y = 888;

    System.out.println(t.x);
    System.out.println(t.y);

    StaticVsInstanceVariable t1 = new StaticVsInstanceVariable();
    t1.x = 99;
    t1.y = 88;

    System.out.println(t1.x);
    System.out.println(t1.y);
    System.out.println(x);
  }

}


 

    

package com.cv.java.oops;

/**
 @author Chandra Vardhan
 *
 */
public class StringBufferEqTest {

  /**
   @param args
   */
  public static void main(String[] args) {
    StringBuffer sb =  new StringBuffer("cv");
    StringBuffer sb2 =  new StringBuffer("cv");
    if(sb.equals(sb2)){
      System.out.println("equal");
    else {
      System.out.println("not");
    }
  }

}


 

    
package com.cv.java.oops;


/**
 @author Chandra Vardhan
 
 */
public class StringCompare {

  /**
   @param args
   */
  public static void main(String[] args) {
    String one = " i am very sincere. And i am doing very  good." ;
    String two = " i am very sincere. And i am doing very  good." ;
    System.out.println(one.length());
    System.out.println(one.trim().equals(two.trim()));

  }

}


 

    
/**
 
 */
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class StringEquals {

  

  /**
   @param args
   */
  public static void main(String[] args) {

    String s1 = new String("cv");
    String s2 = new String("cv");
    System.out.println("=========================");
    System.out.println("s1.hashCode : " + s1.hashCode());
    System.out.println("s2.hashCode : " + s2.hashCode());
    System.out.println(s1);
    System.out.println(s2);
    System.out.println("Objects (s1,s2) are equal with == operator :" + s1 == s2);// false//MOST IMPORATANT Statement...
    boolean b = s1 == s2;
    System.out.println("Objects (s1,s2) are equal with == operator :" + b);// false
    System.out.println("Objects (s1,s2) are equal with equals() method :" + s1.equals(s2));//true
    System.out.println("=========================");
    String s5 = "c" "v";
    String s6 = "c";
    String s7 = s6 + "v";
    final String s8 = "c";
    String s9 = s8 + "v";
    boolean b2 =s1 == s5;
    System.out.println("Objects (s1,s5) are equal with == operator :" +b2);// false
    System.out.println("s5.hashCode : " + s5.hashCode());
    System.out.println("Objects (s1,s5) are equal with equals() method :" + s1.equals(s5));// true
    System.out.println("=========================");
    System.out.println("Objects (s1,s7) are equal with equals() method :" +s1.equals(s7));//true
    System.out.println("=========================");
    System.out.println(s6 == s8);//true
    System.out.println(s5 == s7);// false
    System.out.println(s5 == s9);//true
    System.out.println(s9 == s7);// false
    System.out.println("=========================");
    System.out.println(s5.equals(s7));//true
    System.out.println(s9.equals(s7));//true
    System.out.println(s5.equals(s9));//true
    System.out.println("=========================");
  }

}


 

    
/**
 
 */
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class StringHashCode {

  /**
   
   */
  public StringHashCode() {

  }

  /**
   @param args
   */
  public static void main(String[] args) {

    String string = new String("cv");

    String string2 = new String("cv");

    String string3 = "cv";

    String string4 = "cv";

    System.out.println(string == string2);//f

    System.out.println(string == string3);//f

    System.out.println(string3 == string4);//true
    
    System.out.println("==========================");
    
    String s1 = new String("spring");
    
    System.out.println(s1.hashCode());
    
    s1= s1+"winter";
    
    System.out.println(s1.hashCode());
      
    s1.concat("summer");
    
    String s2 = s1.concat("fall");
    
    System.out.println(s1.hashCode());
    
    
    System.out.println(s1);
    
    System.out.println(s2);

  }

}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class StringIntern {

  /**
   @param args
   */
  public static void main(String[] args) {
    
    String string = new String("cv");
    
    String string2 = "cv";
    
    System.out.println(string == string2)//false
    
    String string3 = string.intern();
    
    System.out.println(string3 == string2);//true

  }

}


 

    
/**
 
 */
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class StringMethods {

  // private static String s = "chote";
  /**
   
   */
  public StringMethods() {

  }

  /**
   @param args
   */
  public static void main(String[] args) {

    // charAt(-)

    String s = "chote";
    System.out.println(s.charAt(3));// t

    //System.out.println(s.charAt(30));// java.lang.StringIndexOutOfBoundsException:

    // concat(-)

    String s2 = "cv";
    //s2 = s2.concat("kodam");
    System.out.println("s2==="+s2);//cvkodam(if line above enabled) otherwise cv
    s2 += "kodam";
    System.out.println(s2);//cvkodam
    
    //equals(-)
    
    System.out.println(s.equals("chote"));//T
    System.out.println(s.equals("CHOTE"));//F
    System.out.println(s.equalsIgnoreCase("CHotE"));//T
    System.out.println(s.equalsIgnoreCase("CHOTE"));//T
    
    //substring(-)
    
    String string = "chandravardhan";//index always starts from zero..
    System.out.println(string.substring(7));//vardhan    
    System.out.println("unHappy".substring(2));//Happy
    //substring(-,-)
    System.out.println(string.substring(714));//vardhan
    System.out.println(string.substring(014));//chandravardhan
    System.out.println(string.subSequence(014));//chandravardhan

    //length()
    System.out.println(string.length());
    
    //replace(-,-)
    String string2 = "chandravardhan";
    
    System.out.println(string2.replace('a''A'));
    
    String s3="aaa";
    
    System.out.println(s3.replace('a''b'));
    System.out.println(s3.replace("aa""b"));
    
    //toLowerCase()
    String s4 = "CHOTE";
  
    System.out.println(s4.toLowerCase());//chote
    
    //toUpperCase()
    System.out.println(s3.toUpperCase());//AAA
    
    //trim()
    
    String s1 = "  chote is looking good  ...  ";
    
    System.out.println(s1.trim());//chote is looking good  ... It would not trim middle chars.
    
    //indexOf(-)
    String ss = " cv ko da m"
    System.out.println(s1.indexOf('d'));//22
    System.out.println(s1.indexOf('o'));//4
    
    System.out.println(s1.indexOf('k'));//14
    System.out.println(s1.indexOf('s'));//9
    
    System.out.println(ss.indexOf('k'));//4
    System.out.println(ss.indexOf('d'));//7
    System.out.println(ss.indexOf('m'));//10
    System.out.println(ss.indexOf('c'));//1
    System.out.println(ss.indexOf("da"));//7
    
    String string3 = new String(new StringBuffer("cv"));
    
    System.out.println(string3);
    
    char[] ch = {'a','b','c','d'};
    
    String string4 = new String(ch);
    System.out.println(string4);
    
    byte[] b = {100,101,102,103};
    String string5 = new String(b);
    System.out.println(string5);  

  }

}


 

    
/**
 
 */
package com.cv.java.oops;

/**
 @author Chote
 
 */
public class StringTest {

  /**
   
   */
  public StringTest() {

  }

  /**
   @param args
   */
  public static void main(String[] args) {

    String string = new String("cv");
    string.concat("kodam");
    String string2 = string.concat("netha");

    System.out.println(string);
    System.out.println(string2);

    String string3 = new String("cv");
    String string4 = string3.concat("kc");
    String string5 = string4.intern();

    String string6 = "cvkc";
    String string7 = new String("cvkc");
    
    System.out.println(string5 == string6);
    System.out.println(string5 == string7 );

  }

}


 

    
/**
 
 */
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class StrinVsStringBuffer {

  /**
   @param args
   */
  public static void main(String[] args) {

    String string = new String("c");

    String string2 = new String("c");

    System.out.println(string == string2);// f

    System.out.println(string.equals(string2));// T
    
    System.out.println("====================");

    StringBuffer buffer = new StringBuffer("c");

    StringBuffer buffer2 = new StringBuffer("c");
    
    System.out.println("string AND SB===" + buffer.equals(buffer2));// f

    System.out.println(buffer == buffer2);// f

    System.out.println(string.equals(buffer2));// f
    
//    System.out.println(string == buffer); incompatible operand types...
    
    

  }

}


 

    
/**
 
 */
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class Student {

  private String name;
  private int rollNo;
  private int hashCode;

  

  public Student(String name, int rollNo) {
    super();
    this.name = name;
    this.rollNo = rollNo;
  }



  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + hashCode;
    result = prime * result + ((name == null: name.hashCode());
    result = prime * result + rollNo;
    return result;
  }



  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    Student other = (Studentobj;
    if (hashCode != other.hashCode)
      return false;
    if (name == null) {
      if (other.name != null)
        return false;
    else if (!name.equals(other.name))
      return false;
    if (rollNo != other.rollNo)
      return false;
    return true;
  }



  @Override
  public String toString() {
    return "Student [name=" + name + ", rollNo=" + rollNo + ", hashCode=" + hashCode + "]";
  }



  /**
   @param args
   */
  public static void main(String[] args) {

    Student student = new Student("chote"1228);

    Student Student = new Student("dev"1229);

    Student student3 = new Student("jyo"1230);

    System.out.println(student);

    System.out.println(student.toString());
    System.out.println(Student);
    System.out.println(student3);

    System.out.println(student.name + " " + student.rollNo);

    System.out.println(student.hashCode());
    System.out.println(Student.hashCode());
    System.out.println(student3.hashCode());
    System.out.println(System.identityHashCode(student));
    System.out.println(System.identityHashCode(Student));
    System.out.println(System.identityHashCode(student3));
    
    Student student4 = new Student("chote"1228);

    Student student5 = new Student("dev"1229);

    Student student6 = new Student("chote"1228);
  
    Student Student2 = student4;
    
    System.out.println(student4.equals(student5));
    
    System.out.println(student5.equals(student6));
    
    System.out.println(student4.equals(student6));
    
    System.out.println(student4.equals(Student2));    
    System.out.println("======================");
    System.out.println(student4.hashCode());
    System.out.println(Student.hashCode());
    System.out.println(student5.hashCode());
    System.out.println(student6.hashCode());
  }

}


 

    
package com.cv.java.oops.sub;

import com.cv.java.oops.ProtectedMember;

/**
 @author Chandra Vardhan
 
 */
public class ProtectedTest extends ProtectedMember {

  /**
   @param args
   */

  private static void m1() {

    // ProtectedMember protectedMember = new ProtectedMember();

    ProtectedTest protectedTest = new ProtectedTest();
    // we have to access field and method from the child reference and it
    // must be child object also...

    System.out.println(protectedTest.name);

  }

  public static void main(String[] args) {

    m1();

  }

}


 

    
/**
 
 */
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 *
 */
public class UpperLower {

  /**
   
   */
  public UpperLower() {
    
  }

  /**
   @param args
   */
  public static void main(String[] args) {
    
    String string = new String("CHOTE");
    
    String string2 = string.toLowerCase();
    
    String string3 = string.toUpperCase();
    
    String string4 = string2.toUpperCase();
    System.out.println(string == string2);//false
    System.out.println(string == string3);//true
    System.out.println(string == string4);//false
    System.out.println(string4 == string3);//false
  }
}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class VarArg {

  /**
   @param args
   */
  public static void main(String[] args) {

    int i = 10;
    m1(i);

  }

  private static void m1(Integer i) {

    System.out.println("AutoBox");
  }

  private static void m1(int... i) {

    System.out.println("var-arg");
  }

  private static void m1(Integer... i) {

    System.out.println("var-arg");
  }

}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class VarArgsTest {

  public static void main(String[] args) {

    sum();
    sum(10);
    sum(1020);
  }

  public static void sum(int... x) {
    int total = 0;
    for (int x1 : x) {
      total = total + x1;
    }
    System.out.println("the sum:" + total);
  }
}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class WidenAndAutoBox {

  /**
   @param args
   */
  public static void main(String[] args) {
    
    int i=10;
    m1(i);

  }

  private static void m1(Object i) {
    
    System.out.println("Object");
  }

}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class Widening {

  /**
   @param args
   */
  public static void main(String[] args) {

    int i = 10;
    m1(i);

  }

  private static void m1(long i) {

    System.out.println("widen");
  }

  private static void m1(Integer i) {

    System.out.println("AutoBox");
  }

}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class Widening2 {

  /**
   @param args
   */
  public static void main(String[] args) {

    int i = 10;
    m1(i);

  }

  private static void m1(long i) {

    System.out.println("widen");
  }

  private static void m1(int... i) {

    System.out.println("var-arg");
  }

}


 

    
package com.cv.java.oops;

/**
 @author Chandra Vardhan
 
 */
public class Widening3 {

  /**
   @param args
   */
  public static void main(String[] args) {

    int i = 10;
    // long i2=i;
    m1(i);

  }

  private static void m1(long i) {

    System.out.println("long");

  }

  private static void m1(Integer i) {

    System.out.println("Integer");

  }

  private static void m1(Long i) {

    System.out.println("Long");//Long

  }

}


 

    
package com.cv.java.oops;


/**
 @author Chandra Vardhan
 
 */
public class WrapperTest {
  public static char a;

  public static void main(String[] args) {
    Integer i=new Integer(10);
    Integer i2=new Integer("10");
    System.out.println(i+"===="+i2);
    
    Float f=new Float(10);
    Float f2=new Float("10");
    System.out.println(f+"=="+f2);
    
    Double d=new Double(10);
    Double d2=new Double("10");
    System.out.println(d+"====="+d2);
    
    Boolean b=new Boolean(true);
    Boolean b2=new Boolean("true");
    //Boolean b3=new Boolean(True);
    //Boolean b3=new Boolean(TRUE);
    Boolean b4=new Boolean(false);
    Boolean b5=new Boolean("false");
    System.out.println(b+"====="+b2+"===="+b4+"===="+b5);
    
    Boolean x=new Boolean("yes");
    Boolean y=new Boolean("no");
    System.out.println(x+"======"+y);
    
    Character c=new Character('b')
//    Character c1=new Character("c");
    System.out.println(c);
    //System.out.println(c1);
    
    
  }

}

No comments:

Post a Comment