Monday, February 24, 2014

Primitive Data Types in Java


12/22/2015:

Srouce: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Primitive Data Types

The Java programming language is statically-typed, which means that all variables must first be declared before they can be used. This involves stating the variable's type and name, as you've already seen:
int gear = 1;
Doing so tells your program that a field named "gear" exists, holds numerical data, and has an initial value of "1". A variable's data type determines the values it may contain, plus the operations that may be performed on it. In addition to int, the Java programming language supports seven other primitive data types. A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java programming language are:
  • byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.
  • short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.
  • int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer. See the section The Number Classes for more information. Static methods like compareUnsigneddivideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.
  • long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. Use this data type when you need a range of values wider than those provided by int. The Long class also contains methods like compareUnsigneddivideUnsigned etc to support arithmetic operations for unsigned long.
  • float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations forbyte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.
  • double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
  • boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.
  • char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java.lang.String class. Enclosing your character string within double quotes will automatically create a new String object; for example,String s = "this is a string";String objects are immutable, which means that once created, their values cannot be changed. The String class is not technically a primitive data type, but considering the special support given to it by the language, you'll probably tend to think of it as such. You'll learn more about the String class in Simple Data Objects

Default Values

It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.
The following chart summarizes the default values for the above data types.
Data TypeDefault Value (for fields)
byte0
short0
int0
long0L
float0.0f
double0.0d
char'\u0000'
String (or any object)  null
booleanfalse

Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

Literals

You may have noticed that the new keyword isn't used when initializing a variable of a primitive type. Primitive types are special data types built into the language; they are not objects created from a class. A literal is the source code representation of a fixed value; literals are represented directly in your code without requiring computation. As shown below, it's possible to assign a literal to a variable of a primitive type:
boolean result = true;
char capitalC = 'C';
byte b = 100;
short s = 10000;
int i = 100000;

Integer Literals

An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int. It is recommended that you use the upper case letter L because the lower case letter l is hard to distinguish from the digit 1.
Values of the integral types byteshortint, and long can be created from int literals. Values of type long that exceed the range of int can be created from long literals. Integer literals can be expressed by these number systems:
  • Decimal: Base 10, whose digits consists of the numbers 0 through 9; this is the number system you use every day
  • Hexadecimal: Base 16, whose digits consist of the numbers 0 through 9 and the letters A through F
  • Binary: Base 2, whose digits consists of the numbers 0 and 1 (you can create binary literals in Java SE 7 and later)
For general-purpose programming, the decimal system is likely to be the only number system you'll ever use. However, if you need to use another number system, the following example shows the correct syntax. The prefix 0x indicates hexadecimal and 0b indicates binary:
// The number 26, in decimal
int decVal = 26;
//  The number 26, in hexadecimal
int hexVal = 0x1a;
// The number 26, in binary
int binVal = 0b11010;

Floating-Point Literals

A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is double and it can optionally end with the letter D or d.
The floating point types (float and double) can also be expressed using E or e (for scientific notation), F or f (32-bit float literal) and D or d (64-bit double literal; this is the default and by convention is omitted).
double d1 = 123.4;
// same value as d1, but in scientific notation
double d2 = 1.234e2;
float f1  = 123.4f;

Character and String Literals

Literals of types char and String may contain any Unicode (UTF-16) characters. If your editor and file system allow it, you can use such characters directly in your code. If not, you can use a "Unicode escape" such as '\u0108' (capital C with circumflex), or "S\u00ED Se\u00F1or"(Sí Señor in Spanish). Always use 'single quotes' for char literals and "double quotes" for String literals. Unicode escape sequences may be used elsewhere in a program (such as in field names, for example), not just in char or String literals.
The Java programming language also supports a few special escape sequences for char and String literals: \b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \" (double quote), \' (single quote), and \\ (backslash).
There's also a special null literal that can be used as a value for any reference type. null may be assigned to any variable, except variables of primitive types. There's little you can do with a null value beyond testing for its presence. Therefore, null is often used in programs as a marker to indicate that some object is unavailable.
Finally, there's also a special kind of literal called a class literal, formed by taking a type name and appending ".class"; for example, String.class. This refers to the object (of type Class) that represents the type itself.

Using Underscore Characters in Numeric Literals

In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, for example. to separate groups of digits in numeric literals, which can improve the readability of your code.
For instance, if your code contains numbers with many digits, you can use an underscore character to separate digits in groups of three, similar to how you would use a punctuation mark like a comma, or a space, as a separator.
The following example shows other ways you can use the underscore in numeric literals:
long creditCardNumber = 1234_5678_9012_3456L;
long socialSecurityNumber = 999_99_9999L;
float pi =  3.14_15F;
long hexBytes = 0xFF_EC_DE_5E;
long hexWords = 0xCAFE_BABE;
long maxLong = 0x7fff_ffff_ffff_ffffL;
byte nybbles = 0b0010_0101;
long bytes = 0b11010010_01101001_10010100_10010010;
You can place underscores only between digits; you cannot place underscores in the following places:
  • At the beginning or end of a number
  • Adjacent to a decimal point in a floating point literal
  • Prior to an F or L suffix
  • In positions where a string of digits is expected
The following examples demonstrate valid and invalid underscore placements (which are highlighted) in numeric literals:
// Invalid: cannot put underscores
// adjacent to a decimal point
float pi1 = 3_.1415F;
// Invalid: cannot put underscores 
// adjacent to a decimal point
float pi2 = 3._1415F;
// Invalid: cannot put underscores 
// prior to an L suffix
long socialSecurityNumber1 = 999_99_9999_L;

// OK (decimal literal)
int x1 = 5_2;
// Invalid: cannot put underscores
// At the end of a literal
int x2 = 52_;
// OK (decimal literal)
int x3 = 5_______2;

// Invalid: cannot put underscores
// in the 0x radix prefix
int x4 = 0_x52;
// Invalid: cannot put underscores
// at the beginning of a number
int x5 = 0x_52;
// OK (hexadecimal literal)
int x6 = 0x5_2; 
// Invalid: cannot put underscores
// at the end of a number
int x7 = 0x52_;









- Java is Strongly typed language. It means if you want to use a variable, Java requires you to declare the type of information that this variable can store. And it has 8 Primitive data types.

package javaFAQsolutions;
//list of primitive data types in java
public class primitivedatatypes {
   
   
    public static void main(String[] args){  //here the main() method should have parameters , or else code will not run
    primitivedatatype();   
    }
     public static void primitivedatatype(){
        // what are primitive datatypes in java?
       
        //Ans:  Java programming language is statically-typed, which means that all variables must first be declared before they can be used.
        // The word primitive meaning is prime/original.
        // Java supports the following datatypes. (The word literals also comes with the datatypes only)
        boolean result = true;
        char capitalC = 'C';
        byte b = 100; //what type of data type is byte..if the literal is byte then no quotes for it
        short s = 10000;
        int i = 100000;
        double d= 34545; // or 34545d
        float f =(float) 4545.44343d; // or 4545.44343f // by default double is the data type //The floating point types (float and double) can also be expressed using E or e (for scientific notation), F or f (32-bit float literal) and D or d (64-bit double literal;
        //http://answers.yahoo.com/question/index?qid=20080210150117AAI8zQ3  ....for float and double
        //String is not a datatype, but to declare strings
      System.out.println(result);
      System.out.println(capitalC);
      System.out.println(b);
      System.out.println(s);
      System.out.println(i);
      System.out.println(d);
      System.out.println(f);
    }
   
}   
           

Creating object for class and accessing methods of class. Various forms of Object



- Delcare object at class level:
See in order to use the object created in main method in all other methods in the same class, we need to declare object as class instance.

       Note: if you dont declare object at class level, then we cannot use it in multiple methods.

    public class DemoQAsitetesting {

private static WebDriver webDriverobj;  //declared object

public static void main(String[] args) {

webDriverobj = new FirefoxDriver(); //WebDriver webDriverobj=new FirefoxDriver();  ...if we declare this we were not able to use object webDriverobj in other methods.

}

public void registration(){
     
webDriverobj.get("http://www.demoqa.com");
          }


-
//Creating object for class and accessing methods of class

package javaFAQsolutions;

public class objectsandmethods {

    String empname="Sreekanth1";
    int empsal;
   
   
    public static void main(String arg[]){
       
        objectsandmethods obj1 = new objectsandmethods();

        obj1.fetch(); //obj1 is nothing but a copy of class, so should be able to access its methods
        obj1.getEmpName();
    }
    private void fetch(){
        String empname="Sreekanth";
        System.out.println(empname);
           
    }
   
   
    public void getEmpName(){
        objectsandmethods obj2=new objectsandmethods();
        System.out.println(obj2.empname);
        //System.out.println(obj1.empname);
       
    }
}



12/22/2015:


See how object is being used:

Source: http://docs.oracle.com/javase/tutorial/java/data/characters.html

Most of the time, if you are using a single character value, you will use the primitive char type. For example:
char ch = 'a'; 
// Unicode for uppercase Greek omega character
char uniChar = '\u03A9';
// an array of chars
char[] charArray = { 'a', 'b', 'c', 'd', 'e' };
There are times, however, when you need to use a char as an object—for example, as a method argument where an object is expected. The Java programming language provides a wrapper class that "wraps" the char in a Character object for this purpose. An object of type Charactercontains a single field, whose type is char. This Character class also offers a number of useful class (i.e., static) methods for manipulating characters.
You can create a Character object with the Character constructor:
Character ch = new Character('a');

Constructors - no parameter and with parameter


12/22/2015

Source: http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

Providing Constructors for Your Classes

A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. For example, Bicycle has one constructor:
public Bicycle(int startCadence, int startSpeed, int startGear) {
    gear = startGear;
    cadence = startCadence;
    speed = startSpeed;
}
To create a new Bicycle object called myBike, a constructor is called by the new operator:
Bicycle myBike = new Bicycle(30, 0, 8);
new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields.
Although Bicycle only has one constructor, it could have others, including a no-argument constructor:
public Bicycle() {
    gear = 1;
    cadence = 10;
    speed = 0;
}
Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike.
Both constructors could have been declared in Bicycle because they have different argument lists. As with methods, the Java platform differentiates constructors on the basis of the number of arguments in the list and their types. You cannot write two constructors that have the same number and type of arguments for the same class, because the platform would not be able to tell them apart. Doing so causes a compile-time error.
You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.
You can use a superclass constructor yourself. The MountainBike class at the beginning of this lesson did just that. This will be discussed later, in the lesson on interfaces and inheritance.
You can use access modifiers in a constructor's declaration to control which other classes can call the constructor.

Note: If another class cannot call a MyClass constructor, it cannot directly create MyClass objects.






/* The below example illustrate the use of construcutor and
 * informs that every constructor is called if it is created
 * when object is created.
 *
 */

package javaFAQsolutions;

public class ObjectConstructors {
   
    //ObjectConstructors ObjectConstructors;
    //Set ObjectConstructors=new ObjectConstructors();
    public ObjectConstructors(){  //constructor with no parameters
        System.out.println("Constructor is been called");
    }
    public ObjectConstructors(int a,int b){ //constructor with parameters
        System.out.println("sum of numbers is "+(a+b));
        System.out.println("Constructor with same name with parameters is been called");
    }
   
    public static void main(String args[]){
       
        //Create object Constructor?
        //Ans:
    ObjectConstructors obj1;
    obj1=new ObjectConstructors(); //when ever object is created constructor is called
    ObjectConstructors obj3=new ObjectConstructors();  // this is to illustrate that constructor is called evertime object is created
        //final int a=1;
        //System.out.println(obj1.a);
    ObjectConstructors obj2;
    obj2=new ObjectConstructors(1,2);
       
    }

}

Comparing Strings

package javaFAQsolutions;

public class comparingstrings {
   
    public static void main(String arg[]){
       
        //How to compare two strings in Java?
       
        //Ans: •The best would be using s1.equalsIgnoreCase(s2): (see javadoc)
        //•You can also convert them both to upper/lower case and use s1.equals(s2)
       String s1= "Are you there";
       String s2="are you there";
       if(s1.equalsIgnoreCase(s2)) { //method for comparing strings
//if(s1.equals(s2)) ---will compare string with same case
           System.out.println("both strings are equal");
       }
       else
       {
           System.out.println("both strings are not equal");
       }
          
    }

}

Sunday, February 23, 2014

Creating Thread(1st way)

//Creating a thread(1st way)...
class ThreadTest3
{
   
    public static void main(String args[])
    {
        Threads1 obj1 = new Threads1("Hello"); //parameter is passed to make sure that this particular thread is running
        Threads1 obj2 = new Threads1("World"); //Here pass a string but in 2nd way pass object of implemented class
        obj1.start();
        obj2.start();
    }
}

class Threads1 extends Thread //directly inheriting the Thread class
{
    String msg;
    public void run() //this is the run method available in class- Thread
    {
        for(int i=0;i<10;i++)
        {
        System.out.println(msg);
        }
    }
   
    Threads1(String m)
    {
        msg= m;
    }
}

String is a class and pass parameter to it.


- String is a builtin class



public class Stringclass {
   
    //public void String(a){
        //System.out.println(a);
    //}

    public static void main(String args[]){
        String str1=new String("A string");
       
        System.out.println(str1);
    }
}

Creating a Thread(2nd way)

//Create a Thread(2nd way)
//import java.lang.Thread;
import java.lang.Runnable;  // To implement Runnable class
class NameRunnable implements Runnable {  //It will make NameRunnable class use the methods in Runnable class
public int sum,a,b;

    public void run() {
   
System.out.println("NameRunnable running");
System.out.println("Run by "
+ Thread.currentThread().getName()); // Name of the current thread i,e Fed
final int c=funcsum(1,2);
System.out.println(c);
}

public int funcsum(int a,int b) {
    sum=a+b;
    return sum;
}
}

public class NameThread {
public static void main (String [] args) {
    NameRunnable nr = new NameRunnable(); //Creating object of class implemented from Runnable class
Thread t = new Thread(nr); //What does this mean, passing object as parameter to class
t.setName("Fred"); //this will name your thread
t.start(); //this will run the method 'run' in implemented class- NameRunnable
}
}

Two types of for loops for a variable which holds full of values

   
//Two types of for loops for a variable which holds full of values
public class miscelleneous {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        miscelleneous obj1=new miscelleneous();
        //System.out.println(obj1);  // this is a valid code because object is instance of class it has address of portion of class
       
        //System.out.println(new miscelleneous()); // this syntax is similar to above code for objects..here also object is created
        //System.out.println();
        
        String[] array = new String[2];
        for(int i = 0; i < array.length; i++) //for(String s:array)
            { 
            //array[0]="1";
        String s = array[i];       
        //System.out.println(s);
        }
        //String args1[];
                for (String s1: array) // Data type, variable and array name. This for loop will go till size of an array
                    // s1 gets successively each value in array
        //http://www.leepoint.net/notes-java/flow/loops/foreach.html
       
                {
            array[0]="2";
            System.out.println(array[0]);
            //System.out.println(s1); // s1=array(0);
            //s1=array[0];
            System.out.println(s1); //s1 gets each value of an array
                       
           
        }
           
        }
       
    }

Creating Arraylist, adding value to it and extracting value from it

//crating Arraylist, adding value to it and geting value from it.

import java.util.ArrayList;
public class Collectionframeworkclass {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ArrayList<String> arr = new <String>ArrayList();
        arr.add(0, "a"); //set(0,"a");
        System.out.println(arr.get(0));
       
       
    }

}


How does this array work?

String authHeaderInputs[] = new String[] { "\"" + mId + "\"",
"\"" + timestm + "\"", "\"" + noce + "\"",
"\"" + mignature + "\"", "\"" + bhash + "\"" };

Creating Arraylist, adding value to it and extracting value from it

//crating Arraylist, adding value to it and geting value from it.

import java.util.ArrayList;
public class Collectionframeworkclass {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ArrayList<String> arr = new <String>ArrayList();
        arr.add(0, "a"); //set(0,"a");
        System.out.println(arr.get(0));
       
       
    }

}


How does this array work?

String authHeaderInputs[] = new String[] { "\"" + mId + "\"",
"\"" + timestm + "\"", "\"" + noce + "\"",
"\"" + mignature + "\"", "\"" + bhash + "\"" };

int, float, String type casting in java

// int, float, String type casting in java
public class Castingdatatypes
{

    public int a=10;
    public float b=10;
    public String b1="11";
    public float d1=1.1f;
    public int e1=13;
           
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Castingdatatypes obj1= new Castingdatatypes();
       
        obj1.casting();
    }
        public void casting()
        {
     float c;
     int d;
     float e;
     //parseInt is a method for String conversions
     c=Float.parseFloat(b1); // b1 is a String, we are converting it to float, nothing but
     d=Integer.parseInt(b1); //String to int conversion

     //e=(Integer)c;
     e = (float)d1; //cannot convert from float to int. But this is float to float conversion
     d1=(int)e1; //convert from int to float, is possible and now being converted.
     //c= Float.parseFloat(b1);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             (b1);
     System.out.println(c); //this outputs the float(String b1)
     System.out.println(d); //this outputs the Int(String b1)
     System.out.println(e); //this outputs the Int(float d1)
     System.out.println(d1);//this outputs the float(int d1)
        }
}

Creating single array, multidimentional array and array of objects in java



//Creating single array, multidimentional array and array of objects in java
public class Arrayexample {

    public static void main(String[] args) {
        String arr1[]= new String[10]; //Creating String array arr1[]
        arr1[0]="a";
        arr1[1]="1";
        int arr2[]=new int[10]; //creating int array arr2[]
        arr2[0]=1;
        //arr2[1]="1";----cannot convert string to int
        //arr1[2]=1;---cannot convert int to string
        float arr3[] = new float[3]; //creating float array arr3[]
        arr3[0]=1;
        String arr4[][]=new String[2][2]; //Creating String multidimensional array arr4[]
        arr4[0][0]="a";
        Arrayexample obj1= new Arrayexample();
        System.out.println(obj1);
        Arrayexample obj2=new Arrayexample();
        Arrayexample arr5[]=new Arrayexample[2]; //Crating an array which stores objects, arr5[]
        arr5[0]=obj1; //Assigning value of obj1 i,e address to arr5[0]
        arr5[1]=obj2;
        System.out.println(arr5[0]); //here the value of obj1 is displayed i,e one of the address of memory
   
    }

}