Wednesday, 31 July 2013

08:Identify Java keywords, Java literals, and primitive data types

Java Keywords
‰  Keywords are predefined identifiers reserved by Java for a specific purpose.
‰  You cannot use keywords as names for your variables, classes, methods, and so on. 

A list of Java keywords are as follows:
Java Literals
Literals are tokens that do not change. They are constant in value.
The different types of literals in Java are:
‰  Integer Literals
‰  Floating-Point Literals
‰  Boolean Literals
‰  Character Literals
‰  String Literals
Java Literals: Integer
Integer literals come in different formats:
‰  decimal (base 10)
‰  hexadecimal (base 16)
‰  octal (base 8)
Special notations in using integer literals in Java programs:
Decimal:
‰  No special notation
‰  Example: 12
Hexadecimal:
‰  Precede by 0x or 0X
‰  Example: 0xC
Octal:
‰  Precede by zero
‰  Example: 014
Java Literals: Floating point
Represents decimals with fractional parts:
Example: 3.1416
Can be expressed in standard or scientific notation:
Example: 583.45 (standard), 5.8345e2 (scientific)
Java Literals: Boolean
Boolean literals have only two values, true or false.
Java Literals: Character
Character Literals represent single Unicode characters.
Unicode character:
‰  A 16-bit character set that replaces the 8-bit ASCII character set
‰  Unicode allows the inclusion of symbols and special characters from other languages
Java Literals: Character
‰  To use a character literal, enclose the character in single quote delimiter.
‰  For example: The letter a, is represented as ‘a’.
‰  Special characters such as a newline character, a backslash is used followed by the
character code. For example, ‘\n’ for the newline character, ‘\r’ for the carriage return,
and ‘\b’ for backspace.
Java Literals: String
‰  String literals represent multiple characters and are enclosed by double quotes.
‰  An example of a string literal is, “Hello World”.
Primitive Data Types
The Java programming language defines eight primitive data types:
‰  boolean (for logical)
‰  char (for textual)
‰  byte
‰  short
‰  int
‰  long (integral)
‰  double
‰  float (floating point)
Primitive Data Types: Logical-boolean
‰  A boolean data type represents two states of true and false.
‰  An example is boolean result = true;
‰  The earlier example shown, declares a variable named result as boolean type and
assigns it a value of true.
Primitive Data Types: Textual-char
‰  A character data type (char), represents a single Unicode character.
‰  It must have its literal enclosed in single quotes(’ ’).
‰  For example the following code:
‘a’ //The letter a
‘\t’ //A tab
To represent special characters like ' (single quotes) or " (double quotes), use the escape
character \. For example the following code:
'\'' //for single quotes
'\"' //for double quotes
Important points to remember:
‰  A string represents a data type that contains multiple characters. It is not a primitive
data type, rather it is a class.
‰  It has its literal enclosed in double quotes(“”). For example, 
String message=“Helloworld!”; 

Primitive Data Types: Integral – byte, short, int, and, long
Integral data types in Java uses three forms of decimal, octal, or hexadecimal.
Examples are:
‰  2 // The decimal value 2
‰  077 // The leading 0 indicates an octal value
‰  0xBACC // The leading 0x indicates a hex value
Integral types has int as default data type.
You can define its long value by appending the letter l or L.
For example: 10L
Integral data type have the following ranges:
Integer Length  Name or Type  Range
8 bits  byte  -27 to 27-1
16 bits  short  -215 to 215-1
32 bits  int  -231 to 231-1
64 bits  long  -263 to 263-1
Coding Guidelines:In defining a long value, a lowercase L is not recommended because it is
hard to distinguish from the digit 1.
Primitive Data Types: Floating Point-float and double
Floating point types has double as default data type.
Floating-point literal includes either a decimal point or one of the following,
‰  E or e //(add exponential value)
‰  F or f //(float)
‰  D or d //(double)
Examples are:
‰  3.14 //A simple floating-point value (a double)
‰  6.02E23 //A large floating-point value
‰  2.718F //A simple float size value
‰  123.4E+306D //A large double value with redundant D
Floating-point data types have the following ranges:
Try It Out
Problem Statement:
Write a program that contains the literal values for the following statements:
1.  Declare an int named sizeand assign it the value 32
2.  Declare a char named initialand assign it the value ‘j’.
3.  Declare double named dand assign it the value 456.709
4.  Declare a boolean named isAvailable(no assignment)
5.  Assign the value true to the isAvailable that is declared earlier
6.  Declare an int named y, and assign it the value thatis the sum of whatever xand 456.
Code:
class LiteralValues {
public static void main(String[] args) {
int size = 32;
char initial = 'j';
double d = 456.709;
boolean isAvailable;
isAvailable = true;
int y = size + 456;
}
}
Refer File Name: LiteralValues.javato obtain soft copy of the program code
How It Works:
You can assign a value to a variable in one of the following several ways including:
‰  Type a literal value after the equals sign (x = 12, isGood = true, and so on)
‰  Assign the value of one variable to another (x = y)
‰  Use an expression combining the two (x = y + 43)
For the given problem statement, the literalvalues are shown in bold italics:
int size = 32;
char initial = ‘j’;
double d = 456.709;
boolean isAvailable;
isAvailable = true;
int y = x + 456;
Tips and Tricks
List out few important points while using identifiers, literals, and keywords in Java.
Solution:
‰  An identifier must begin with a letter, dollar sign($), or underscore (_). Subsequent
characters may be letters, $, _ (underscore), or digits.
‰  An identifier cannot have a name of a Java keyword. Embedded keywords are
accepted. true, false, and null are literals (not keywords), but they cannot be used as
identifiers as well.
‰  const and goto are reserved words, but not used.
‰  All numeric data types are signed. char is the only unsigned integral type.
‰  A number is by default an int literal. A decimal number is by default a double literal.
‰  1E-5d is a valid double literal and E2d is not (since it starts with a letter, compiler
thinks that it’s an identifier).
Summary
‰  Integer literals can be decimal, octal (e.g. 013), or hexadecimal (e.g. 0x3d).
‰  Literals for longs end in L or l (lowercase of the alphabet L).
‰  Float literals end in F or f, double literals end in a digit D or d.
‰  The boolean literals are true and false.
‰  Literals for chars are single character inside single quotes: ‘d’.

09:‰ Define variables Declare variables ‰ Initialize variables ‰ Convert data types ‰ Cast data types



Variables
A variable is an item of data usedto store the state of objects.
A variable has a:
‰  data type:The data type indicates the type of value that the variable can hold.
‰  name:The variable name must follow rules for identifiers.
Declaring and Initializing Variables
Declare a variable as follows:
<data type> <name> [=initial value];
Note:Values enclosed in <> are required values, while those values in [] are optional.
Reference Variables Versus Primitive Variables
Two types of variables in Java:
‰  Primitive Variables
‰  Reference Variables
Primitive Variables:
‰  Variables with primitive data types such as int or long.
‰  Stores data in the actual memory location of where the variable is present
Reference Variables:
‰  Variables that store the address in the memory location
‰  Points to another memory location where the actual data is present
‰  When you declare a variable of a certain class, you are actually declaring a reference variable to the object with that certain class
Example of a reference variable and primitive variable 

Suppose you have two variables with data types int and String.
int num = 10; // primitive type
String name = "Hello"; // reference type
Example of memory handling of a reference variable and a primitive variable
The following picture is the actual memory of your computer, wherein you have the address of the memory cells, the variable name, and the data they hold. 

Type Casting
Type Casting is the mapping type of an object to another.
Casting Primitive Types
‰  Casting between primitive types enables you to convert the value of one data from one type to another primitive type
‰  Commonly occurs between numeric types
‰  There is one primitive data type that you cannot do casting and that is the boolean data type
‰  Types of Casting:
Implicit Casting
Explicit Casting
Implicit Casting
Suppose you want to store a value of int data type to a variable of data type double.
int numInt = 10;
double numDouble = numInt; //implicit cast
In this example, as the data type (double) of the destination variable holds a larger value than the
data type (int) of the value, the data is implicitly casted to the data type double of the destination variable.
Example of implicit casting:
int numInt1 = 1;
int numInt2 = 2;
//result is implicitly cast to type double
double numDouble = numInt1/numInt2;
Explicit Casting
When you convert a data that has a large type to a smaller type, you must use an explicit cast.
Explicit casts take the following form:
(Type)valuewhere, Typeis the name of the type you are converting to value. It is an expression that results in the value of the source type.
Explicit Casting Examples
double valDouble = 10.12;
int valInt = (int)valDouble;
//convert valDouble to int type
double x = 10.2;
int y = 2;
int result = (int)(x/y); //typecast result of operation to int
Casting Objects
Instances of classes also can be cast into instances of other classes, with one restriction. The source and destination classes must be related by inheritance. One class must be a subclass of the other.
Casting objects is analogous to converting a primitive value to a larger type. Some objects might not need to be cast explicitly.
Cast, (classname)object where, classname is the name of the destination class and object is a reference to the source object.
Casting Objects Example
The following example casts an instance of the class VicePresident to an instance of the class
Employee. VicePresident is a subclass of Employee with more information, which here defines that the VicePresident has executive washroom privileges.
Employee emp = new Employee();
VicePresident vp = new VicePresident();
// no cast needed for upward use
emp = vp;
// must cast explicitly
vp = (VicePresident)emp;
Try It Out
Problem Statement:
Write a program that illustrates the implementation of the automatic initialization of member
variables.
Code:
class Initialization {
boolean bo;
byte by;
char c;
short s;
int i;
long l;
float f;
double d;
Object o;
public static void main(String[] args) {
Initialization app = new Initialization();
app.run();
}
// continued …
Refer File Name: Initialization.javato obtain soft copy of the program code
How It Works:
The Initialization program illustrates the use of the automatic initialization of member variables. It
displays the following output:
boolean: false
byte: 0
char:
short: 0
int: 0
long: 0
float: 0.0
double: 0.0
Object: null
Tips and Tricks
List out the key points related to ‘instance’ (or member) variables and ‘local’ variables.
Solution:
‰  Instance (or member) variables:
oAccessible anywhere in the class
oAutomatically initialized before invoking any constructor
oStatic variables are initialized at class load time
oCan have the same name as the class
‰  Local variables:
oMust be initialized explicitly and (Or, the compiler will catch it.) Object references
can be initialized to null to make the compiler happy
oThe following code will not compile. Specify else part or initialize the local variable explicitly.
public String testMethod(int a) {
String tmp;
if (a > 0) tmp = “Positive”;
return tmp;
}
Can have the same name as a member variable and resolution is based on scope
Note:Here is the figure of allowable primitive conversion
byte -> short -> int ->long -> float -> double
char
Summary
‰  Automatic conversion from narrow to widertype. For e.g., whenever division is
performed between a floating type and an integer type, the integer type is
automatically converted (sometimes called promoted) to a floating type and floating
arithmetic is performed.
‰  Arithmetic with boolean is not allowed.
‰  Variables can be initialized when declared
‰  All Java variables can be initialized when they are declared.
‰  Member (or instance) variablesare automatically initialized
‰  If the programmer doesn't initialize the variables declared inside the class but outside of a method (often referred to as member variables as opposed to local variables), they are automatically initialized to a default value.
‰  The default value for a boolean member variable is false.
‰  Local variables are not automatically initialized
‰  Unlike instance (or member) variables, if you fail to initialize a local variable, the variable is not automatically initialized.
‰  Must initialize or assign value to all local variables
‰  Thus, the programmer is responsible for either initializing all local variables, or assigning a value to them before attempting to access their value with code later in the program.
‰  Cannot access value from uninitialized local variable
‰  If you attempt to access and use the value from an uninitialized local variable before you assign a value to it, you will get a compiler error.

Java interview questions and answers 3



101. What are the three types of  Thread priority ?
Ans: Thread have following three priority
  1. Thread.MIN_PRIORITY - minimum thread priority.
  2. Thread.MAX_PRIORITY - maximum thread priority.
  3. Thread.NORM_PRIORITY - default thread priority
102. What is the use of synchronizations ?
Ans: The synchronized keyword can be used for locking in program or utilize for lock and free the resource for any thread/program.
103. Garbage collector thread belongs to which priority ?
Ans: Low-priority Thread.

104. What is meant by time-slicing ?
Ans: Time- slice means which provided threads of equal priority and enable to share a processor equally, even if the thread has not finished executing while the quantum expires, the processor is taken away from that thread and given to the next thread of equal priority, if another thread is available.
105. What is the use of ‘this’ ?
Ans: Simple this keyword is refer to the current state of an object and also enable to call a constructor to another constructor

·          
107. How to compare two strings ?
Ans: By equal() method.
108. What are the interfaces defined by java.lang.Package?
Ans:  Following interface defined in java.lang.Package are
  • Appendable - An object to which char sequences and values can be appended. The Appendable interface must be implemented by any class whose   instances are intended to receive formatted output from a Formatter. Appendables are not necessarily safe for multithreaded access.
    (Introduce since JDK- 1.5 ).
     
  • CharSequence -A CharSequence is a readable sequence of char values. This interface provides uniform, read-only access to many different kinds of char sequences. A char value represents a character in the Basic Multilingual Plane (BMP) or a surrogate.                                                          (Introduce since JDK- 1.4 ).
     
  • Cloneable -A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class. it is important that Cloneable doesn't contain any clone()method.                                                                     (Introduce since JDK- 1.0 ).
     
  • Comparable<T> -This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo() method is referred to as its natural comparison method.
*T - the type of objects that this object may be compared to                                                                                                                              ( Introduce since JDK- 1.2)
  • Deprecated -A program element annotated @Deprecated is one that programmers are discouraged from using, typically because it is dangerous, or because a better alternative exists. Compilers warn when a deprecated program element is used or overridden in non-deprecated code.                     (Introduce since JDK- 1.4 ).
     
  • Iterable<T> -Implementing this interface allows an object to be the target of the "foreach" statement .                                                                   (Introduce since JDK- 1.5 ).
     
  • Override - Indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message.                                                                              (Introduce since JDK- 1.5 ).
     
  • Readable - A Readable is a source of characters. Characters from a Readable are made available to callers of the read method via a CharBuffer. (Introduce since JDK- 1.5 ).
     
  • Runnable -The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run. This interface is designed to provide a common protocol for objects that wish to execute code while they are active.  (Introduce since JDK- 1.0 ).
     
  • SuppressWarnings - Indicates that the named compiler warnings should be suppressed in the annotated element (and in all program elements contained in the annotated element).
    (Introduce since JDK- 1.5 ).
    (** Following data taken form sun/java)
109. What is the purpose of run-time class and system class? The System class provide system level functionality to Java applications. Some of the facilities provided by System class: * Reading input from the keyboard. * Writing output to console. * Reading and writing system properties and environment variables Runtime class provides support for runtime environment.

110. What is meant by Stream and Types of Stream ?
Ans:  Generally, Streams are a way of transferring and filtering information or use data in one form or another, however it is as input, output, or both. The sources of input and output can vary between a local file, a database, variables in memory, a socket on the network, or another program. Streams may be in between byte and character streams and various stream classes define into the java.io package, so stream are of two type-
  • Input Stream
  • Output Stream
111. What is the method used to clear the buffer ?
Ans: For Clear the buffer following method is call-
  • clear() -The position is set to zero, the limit is set to the capacity, and the mark is discarded.
  • flip() - The limit is set to the current position and then the position is set to zero.
  • rewind()- The position is set to zero and the mark is discarded.
112. What is meant by StreamTokenizer ?
Ans: The StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens to be read one at a time. 
113. What is serialization and de-serialization ?
Ans: Serialization is the process of  transforming a data structure/object into a sequence of bits stream so that it can be stored in a memory buffer or file, or transmitted across a network while in case of Deserialization is the inverse process of reconstructing an object from a byte stream to the same state in which the object was previously serialized.

  // Serialization code

   FileOutputStream out = new FileOutputStream( “save.ser” );

   ObjectOutputStream x =  new ObjectOutputStream( out );

   oos.writeObject( new Date() );

   x.close();



  //Deserialization code

   FileInputStream in =  new FileInputStream( “save.ser” );

   ObjectInputStream x = new ObjectInputStream( in );

   Date d = (Date) ois.readObject();

   x.close();

114. What is meant by Applet ?
Ans: Applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part of a Web document.
115. How to find the host from which the Applet has originated ?
Ans: Following two method may be used-

   
public java.net.URL getDocumentBase();
   
public java.net.URL getCodeBase();
116. What is the life cycle of an Applet ?
Ans: Life cycle of an Applet totally dependent upon following four method which is-
   
   public void init();
   public void start();
   public void stop();
   public void destroy();

  // A very simpleDemo of an Applet life

  package r4r.co.in;

  import java.applet.Applet;
  import java.awt.Color;
  import java.awt.Graphics;

  public class AppletDemo extends Applet {

    StringBuffer Demo;

    public void init() {
        Demo = new StringBuffer();
        addItem("initializing/java//java/. ");            // initializing an applet
    }

    public void start() {
        addItem("starting of an applet. ");       //start an applet
    }

    public void stop() {
        addItem("stopping an applet. ");          //stop an applet
    }

    public void destroy() {
        addItem("Finally unload.");               //Free all the resource
    }

    private void addItem(String newWord) {
        System.out.println(newWord);
        Demo.append(newWord);

    }

    public void paint(Graphics g) {
        g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);      // Rectangular area
        g.setColor(Color.BLUE);                                 // Color in applet

        g.drawString(Demo.toString(), 10, 15);                 //Display the string inside the rectangle.

    }
 }

 Result:
    
     initializing/java//java/.
     starting of an applet.
    
     //Remaining two method call on closing the applet.
    
     stopping an applet.
     Finally unload.

117. How do you load an HTML page from an Applet ?
Ans: For such operation used small code which written in HTML file
   
 <applet code="AppletDemo" width=300 height=100>
        </applet>

118. What is meant by AppletStub Interface ?
Ans: The
AppletStub interface is a way to get information from the run-time browser environment. The Applet class provides following methods-
  • public abstract boolean isActive()-The isActive() method returns the current state of the applet.
     
  • public abstract URL getDocumentBase()- The getDocumentBase() method returns the complete URL of the HTML file that loaded the applet.
     
  • public abstract URL getCodeBase()- The getCodeBase() method returns the complete URL of the .class file that contains the applet.
     
  • public abstract String getParameter(String name)- The getParameter() method allows you to get parameters from <PARAM> tags within the <APPLET> tag of the HTML file that loaded the applet.
     
  • public abstract AppletContext getAppletContext()- The getAppletContext() method returns the current AppletContext of the applet.The getAppletContext() method returns the current AppletContext of the applet.
     
  • public abstract void appletResize(int width, int height)- The appletResize() method is called by the resize method of the Applet class.
    (** Following data taken from JAVA AWT Reference( Chapter 14))
119. What is meant by getCodeBase and getDocumentBase method ?(Not sure)
Ans: The getCodebase() method is used to establish a path to other files/folders that are in the same location as the class being run.
         
     URL getCodeBase() -  Gets the base URL.

     URL getDocumentBase() -  Gets the URL of the document in which the applet is embedded.       
       
120. How can you call an applet from a HTML file?
Ans: Following example is used

  <HTML>
    <HEAD>
       <TITLE>AppletDemo example- call applet parameter from HTML file </TITLE>
     </HEAD>
       <BODY>
          <APPLET CODE="AppletDemo.class" WIDTH="500" HEIGHT="100">
         </APPLET>
      </BODY>
  </HTML>
121. What is meant by Applet Flickering ?
Ans: When an applet is executing some graphics using a thread, some color desolation will be happening, this is called as flickering.
122. What is the use of parameter tag ?
Ans: The <param> tag is used to define parameters or variables for an object or applet element.
123. What is audio clip Interface and what are all the methods in it ?
Ans:Three methods define the AudioClip interface-
  • void play()-  Starts playing this audio clip from the beginning.
  • void loop()- Starts playing this audio clip in a continuously loop
  • void stop()- Stops playing this audio clip.
     
124. What is the difference between getAppletInfo and getParameterInfo ?
Ans: getAppletInfo()method is used for returns information about this applet in the String form.
           (public String  getAppletInfo())    
       getParameterInfo() method is used for returns information about the parameters that are understood by this applet in the array of Strings.
           ( public String[][]   getParameterInfo())

125. How to communicate between applet and an applet ?
Ans:JavaScript functions enable communication between two applets by receiving messages from one applet and invoking methods of other applets.