Wednesday, 8 August 2018

TYPE CASTING



The process of converting one data type to another is called type casting
Examples:
int m=50;
byte n=(byte)m;
long count=(long) m;
class Typecasting
{
public static void main(String args[])
{
System.out.println("variales created");
char c='x';
byte b=50;
short s=1996;
int i=123456789;
long l=1234567654321L;
float f1=3.142F;
float f2=1.2e-5F;
double d2=0.000000987;
System.out.println(" c="+c);
System.out.println(" b ="+b);
System.out.println(" s= "+s);
System.out.println(" i="+i);
System.out.println(" l="+l);
System.out.println(" f1= "+f1);
System.out.println(" f2="+f2);
System.out.println("d2 ="+d2);
System.out.println(" ");
System.out.println(" Types converted");
short s1=(short)b;
short s2=(short)i;
float n1=(float)l;
int m1=(int)f1;
System.out.println(" (short)b ="+s1);
System.out.println(" (short)i ="+s2);
System.out.println(" (float)l= "+n1);
System.out.println(" (int)f1= - "+m1);
}
}
Note : floating point constants have a default type of double
For example when we want to declare a float variable and initializing it to constant
float x=7.56;
This will give “incompatible type for declaration. Explicit cast needed to convert double to
float.”
This should be written as

float x=7.56F

VARIABLES



A variable is a basic unit of storage, which represents memory location in which value can be
stored.
Rules for variables:
1. They must not begin with a digit
2. It should not be a keyword
3. White space is not allowed
4. Variable names can be of any length

DECLARATION OF VARIABLES
Before using any variable, it must first be declared. A variable declaration specifies the
datatype, the variable name, and optionally the default value for the variable.
Syntax: datatype identifier {=default value}
Ex: byte b;
int age, enrolno
boolean male

GIVING VALUES TO VARIABLES
Once you have declared the type of a variable, you can initialize it with some value.
Syntax: variable name=some value
Ex: int year=20;

SCOPE OF VARIABLES
Java actually has three kinds of variables
Instance variables
Class variables
Local variables
Instance variables are created when the objects are instantiated and therefore they are
associated with the objects. They take different values for each object. Class variables are
similar to instance variables, except their values apply to all the instances of a class rather
than having different values for each object. Local variables are declared and used inside
methods.

Variables :
Variables are also the key to creating programs that can perform calculations.
Type of Variables :
1. class variable
2. Instance variable
3. Local variable
4. Final variable
5. shadowing variable

Class Variable :
A class variable is a variable that any method in a class can access, including static
methods such as main.
When declaring a class variable you have two basic rules to follow:
1. You must place the declarations within the body of the class, but not within any of
the class method.
2. You must include the word static in the declaration. The word static comes before the
variable type.
E.g.: public class helloapp {
static string hellomessage;
public static void main(String[] args) {
hellomessage = “Helloworld!”;
System.out.println(“hellomessage”);
}
}

Instance variable :
An instance variable is similar to a class variable, but doesn’t specify The word static in its
declaration.
• Instance variables are associated with instances of classes.
E.g.:
public class helloapp {
string hellomessage;
public static void main(String[] args) {
hellomessage = “Helloworld!”;
System.out.println(“hellomessage”);
}
}
Error :
Cannot make a static reference to the non-static field hellomessage

Local variable :
A local variable is a variable that’s declared within the body of a method.
• You don’t specify “static” on a declaration for a local variable.
• local variables are not given initial default values. The compiler checks to make sure
that you have assigned a value before you use a local variable.

Final variable (Constants) :
• A final variable, also called a constant.
• It is a variable whose value you can’t change once it’s been initialized.
Final variables are class or instance variables
Shadowing variables :
A shadowing variable is a variable that would otherwise be accessible, but is temporarily
made unavailable because a variable with the same name has been declared in a more
immediate scope.
Scope :
The scope of a variable refers to which parts of a class the variable exists in.

*SYMBOLIC CONSTANTS
symbolic constants are used like macros in C and C++
symbolic names take the same form as variable names. But, they are written in capitals to
visually distinguish them from normal variables. After declaration of symbolic constants they
should not be assigned to any other within the program by using an assignment statement.
A constant can be declared as follows:
Examples:
final int STRENGTH = 100;
final int PASS_MARK = 50;
final float PI = 3.14159;

DATA TYPES



A Data type is the type of data that can be stored into the variable. A description on a variable
that determines what kind of information you can enter in the variable.
There are seven primitive data types, which are supported by Java language programming. A
primitive data type is a data type, which is predefined in Java. Following are the eight
The term “ Data Type” refers to the type of data that can be stored in a variable.
Java is sometimes called a “ strongly typed ” language.
Java has two types of data types.
1. Primitive data types.
2. Reference data types.

Primitive data types:
Primitive data types are the data types that are defined by the language Itself.
The memory location associated with a primitive types variables contains the actual value of
the variable.It is also called as Value types.

Java’s Primitive Types
Type Explanation
int A 32-bit (4-byte) integer value
short A 16-bit (2-byte) integer value
long A 64-bit (8-byte) integer value
byte An 8-bit (1-byte) integer value
float A 32-bit (4-byte) floating-point value
double A 64-bit (8-byte) floating-point value
char A 16-bit character using the Unicode encoding scheme
boolean A true or false value

primitive data types:
int
It is a 32-bit signed two's complement integer data type. It ranges from -2,147,483,648 to
2,147,483,647. This data type is used for integer values. However for wider range of values
use long.

byte
The byte data type is an 8-bit signed two's complement integer. It ranges from -128 to127
(inclusive). We can save memory in large arrays using byte. We can also use byte instead of
int to increase the limit of the code.

short
The short data type is a 16-bit signed two's complement integer. It ranges from -32,768 to
32,767. short is used to save memory in large arrays.

long
The long data type is a 64-bit signed two's complement integer. It ranges from -
9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this data type with larger
range of values.

float
The float data type is a single-precision 32-bit IEEE 754 floating point. It ranges from
1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Use a float
(instead of double) to save memory in large arrays. We do not use this data type for the exact
values such as currency. For that we have to use java.math.BigDecimal class.

double
This data type is a double-precision 64-bit IEEE 754 floating point. It ranges from
4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). This
data type is generally the default choice for decimal values.

boolean
The boolean data type is 1-bit and has only two values: true and false. We use this data type
for conditional statements. true and false are not the same as True and False. They are defined
constants of the language.
char
The char data type is a single 16-bit, unsigned Unicode character. It ranges from 0 to 65,535.
They are not same as ints, shorts etc.
/* Program on Datatypes */
class datatypes
{
public static void main(String []args)
{
int a=457647657;
byte b=12;
short c=435;
long d=345;
float g=3.5f;
double f=345.6;
char k='a';
boolean h=false;
System.out.println("Integer="+a);
System.out.println("Byte="+b);
System.out.println("Short="+c);
System.out.println("Long="+d);
System.out.println("Float="+g);
System.out.println("Double="+f);
System.out.println("Character="+k);
if(h==true)
System.out.println("Boolean value is true");
else
System.out.println("Boolean value is false");
}
}
Output:
E:\sysvol>javac datatypes.java
E:\sysvol>java datatypes
Integer=457647657
Byte=12
Short=435
Long=345
Float=3.5
Double=345.6
Character=a
Boolean value is false
Reference data types :
Reference types are types that are defined by the language java API rather than by the
language itself.
• The memory location associated with a reference tpes variable contains an address
(called pointer) that indicates the memory location of the actual object.

CONSTANTS



Constants are the fixed values that do not change during the execution of a program. Java
supports several types of constants.

Integer Constant
An integer constant refer to a sequence of digits. There are 3 types namely:
Decimal Integer ex:123 -321 0 654321
octal Integer ex:037 0 0435 0551
hexadecimal integer ex:0X2 0X9F 0Xbcd 0x


COMMAND LINE ARGUMENTS



Command Line arguments are parameters that are supplied to the application program at the
time of invoking it for execution.
/* Program to find the average of 3 numbers */
class average
{
public static void main(String []args)
{
int s1=Integer.parseInt(args[0]);
int s2=Integer.parseInt(args[1]);
int s3=Integer.parseInt(args[2]);
int total=s1+s2+s3;
double avg=total/4;
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println("Total= " +total);
System.out.println("Average="+avg);
}
}
Output:
E:\javaprograms>javac average.java
E:\javaprograms>java average 50 60 70
50
60
70
Total= 180
Average=45.0

Tuesday, 7 August 2018

JAVA VIRTUAL MACHINE



When a Java program is compiled it is converted to bytecode, which is then executed by the
Java Interpreter by translating the bytecode into machine instructions. Program in Java
runtime environment, which is used to interpret bytecode, is called Java Virtual Machine.
Any machine for which java interpreter is available can execute this bytecode. That’s why
java is called as Machine Independent and Architecture Neutral. The JVM plays the main
role to making Java portable. Java is Machine Independent and Architecture Neutral



IMPLEMENTING A JAVA PROGRAM



Steps to be followed to implement a Java Program:
Creating the program
Compiling the program
Running the program

Creating the program
We can create a program using any text editor.
Class Sample
{
public static void main(String args[])
{
System.out.println(“ HELLO “);
}
}
We must save this program with the filename Sample.java ensuring that the filename and
classname should be same. This file is called as source file. If a program contains multiple
classes, the filename must be the classname of the class containing the main method.

Compiling the program
C:\> javac Sample.java
The javac compiler creates a file called Sample.class that contains the bytecode version of the
program.

Running the program
C:\> java Sample
Now the interpreter looks for the main method in the program and begins execution from
there.

JAVA TOKENS



Smallest individual units in a program are known as Tokens. The complier recognized them
for building up expressions and statements. Java languages include 5 types of Tokens. They
are:
# Reserved Keywords
# Identifiers
# Literals
# Operators
# Separators

Keywords:
A keyword is a word that has special meaning defined by the Java programming language.
The program shown earlier in Listing 1-1 uses four keywords:public, class, static, and void.
In all, Java has 51 keywords. They’re listed in alphabetical order in Table 1-1. abstract do if
package synchronized boolean double implements private this break else import protected
throw byte extends instanceof public throws case false int return transient catch final
interface short true char finally long static try class float native strictfp void


Identifiers:
An identifier is a word that you make up to refer to a Java programming element by
name. Although you can assign identifiers to many different types of Java elements, they’re
most commonly used for the following elements:
Classes, such as the HelloApp class in Listing 1-1
Methods, such as the main method in Listing 1-1
Variables and fields, which hold data used by your program
Parameters, which pass data values to methods

Comments:
A comment is a bit of text that provides explanations of your code. Comments are completely
ignored by the compiler, so you can place any text you wish in a comment. Using plenty of
comments in your programs is a good idea to explain what your program does and how it
works.
Java has three basic types of comments:
end-of-line comments
traditional comment
Multi comments
JavaDoc comments.

End-of-line comments (single Line comments):
An end-of-line comment begins with the sequence // and ends at the end of the line. You can
place an end-of-line comment at the end of any line.
Everything you type after the // is ignored by the compiler. For example:
total = total * discountPercent; // calculate the discounted total
If you want, you can also place end-of-line comments on separate lines,
like this:
// calculate the discounted total
total = total * discountPercent;
You can place end-of-line comments in the middle of statements that span
two or more lines. For example:
total = (total * discountPercent) // apply the discount first
+ salesTax; // then add the sales tax

Traditional comments (Multi Line comments):
A traditional comment begins with the sequence /* and ends with the sequence */ and can
span multiple lines. For example:
/* HelloApp sample program.
This program demonstrates the basic structure
that all Java programs must follow. */
A traditional comment can begin and end anywhere on a line. If you want, you can even
sandwich a comment between other Java programming elements, like this:
x = (y + /* a strange place for a comment */ 5) / z;
Usually, traditional comments appear on separate lines. One common use for traditional
comments is to place a block of comment lines at the beginning of a class to indicate
information about the class such as what the class does, who wrote it, and so on. However,
that type of comment is usually better coded as a JavaDoc comment, as described in the next
section.
You may be tempted to temporarily comment out a range of lines by placing
/* in front of the first line in the range and */ after the last line in the range.
However, that can get you in trouble if the range of lines you try to comment
out includes a traditional comment. That’s because traditional comments
can’t be nested. For example, the following code won’t compile:
/*
int x, y, z;
y = 10;
z = 5;
x = (y + /* a strange place for a comment */ 5) / z;
*/
Here, I tried to comment out a range of lines that already included a traditional comment.
Unfortunately, the */ sequence near the end of the fifth line is interpreted as the end of the
traditional comment that begins in the first line. Then, when the compiler encounters the */
sequence in line 6, it generates an error message.

Multi Comments (Comments with comments or Nested comments):
Here, comments with in comments, nested comments. It can be represented with
/** Multi comments or Comments with in comments or Nested comments */

JavaDoc comments:
JavaDoc comments are actually a special type of traditional comment that you can use to
automatically create Web-based documentation for your programs. Because you’ll have a
better appreciation of JavaDoc comments when you know more about object-oriented
programming, I devoted a section in Book III, Chapter 8 to creating and using JavaDoc
comments.