Wednesday, 25 March 2015

Programming Constructs, Control Structures in JAVA

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
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
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). You can use a short to save memory in large arrays.
 int: By default, the int data type is a 32-bit signed two's complement integer. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer.
long: The long data type is a 64-bit two's complement integer. In Java SE 8 and later, you can use thelong data type to represent an unsigned 64-bit long.
 float: The float data type is a single-precision 32-bit IEEE 754 floating point.
 double: The double data type is a double-precision 64-bit IEEE 754 floating point.
 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).

====>>> Click Here to see the sample example -1 

Java Language Keywords:-


Here is a list of keywords in the Java programming language. You cannot use any of the following as identifiers in your programs. The keywords const and goto are reserved, even though they are not currently used. true,false, and null might seem like keywords, but they are actually literals; you cannot use them as identifiers in your programs.
Abstract
continue
for
new
switch
assert***
default
goto*
package
synchronized
Boolean
do
if
private
this
Break
double
implements
protected
throw
Byte
else
import
public
throws
Case
enum****
instanceof
return
transient
Catch
extends
int
short
try
Char
final
interface
static
void
Class
finally
long
strictfp**
volatile
const*
float
native
super
while

*

not used
**

added in 1.2
***

added in 1.4
****

added in 5.0
Naming Conventions:-
Naming conventions make programs more understandable by making them easier to read. They can also give information about the function of the identifier-for example, whether it's a constant, package, or class-which can be helpful in understanding the code.
Identifier Type
les for Naming
Examples
Packages
The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981.
Subsequent components of the package name vary according to an organization's own internal naming conventions. Such conventions might specify that certain directory name components be division, department, project, machine, or login names.
Java.io
Java.lang
com.sun.eng
com.apple.quicktime.v2
edu.cmu.cs.bovik.cheese
Classes
Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations (unless the   abbreviation is much more widely used than the long form, such as URL or HTML).


class Image;
Interfaces
Interface names should be capitalized like class names.

interface Storing;
Methods
Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.
run(); 
runFast();
getBackground();
Variables
Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed.
Variable names should be short yet meaningful. The choice of a variable name should be mnemonic- that is, designed to indicate to the casual observer the intent of its use. One-character variable names should be avoided except for temporary "throwaway" variables. Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters.


int i;
char c;
float myWidth;
Constants
The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_"). (ANSI constants should be avoided, for ease of debugging.)
static final int MIN_WIDTH = 4;
static final int MAX_WIDTH = 999;
static final int GET_THE_CPU = 1;

 

Assignment, Arithmetic, and Unary Operators


The Simple Assignment Operator

One of the most common operators that you'll encounter is the simple assignment operator "=". it assigns the value on its right to the operand on its left:
 int cadence = 0;
 int speed = 0;
 int gear = 1;
The Arithmetic Operators
The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. The only symbol that might look new to you is "%", which divides one operand by another and returns the remainder as its result.
The Unary Operators
The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.
Equality, Relational, and Conditional Operators

The Equality and Relational Operators

The equality and relational operators determine if one operand is greater than, less than, equal to, or not equal to another operand. The majority of these operators will probably look familiar to you as well. Keep in mind that you must use "==", not "=", when testing if two primitive values are equal.
The Conditional Operators
The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.

Summary of Operators

The following quick reference summarizes the operators supported by the Java programming language.

Simple Assignment Operator

=       Simple assignment operator

Arithmetic Operators

+       Additive operator (also used
        for String concatenation)
-       Subtraction operator
*       Multiplication operator
/       Division operator
%       Remainder operator 

Unary Operators

+       Unary plus operator; indicates positive value (numbers are  positive without this, however)
-       Unary minus operator; negates  an expression
++      Increment operator; increments a value by 1
--      Decrement operator; decrements a value by 1
!       Logical complement operator;inverts the value of a Boolean 

Equality and Relational Operators

==      Equal to
!=      Not equal to
>       Greater than
>=      Greater than or equal to
<       Less than
<=      Less than or equal to 

Conditional Operators

&&      Conditional-AND
||          Conditional-OR
?:      Ternary (shorthand for if-then-else statement) 

Type Comparison Operator

instanceof      Compares an object to  a specified type  

Bitwise and Bit Shift Operators

~       Unary bitwise complement
<<      Signed left shift
>>      Signed right shift
>>>     Unsigned right shift
&       Bitwise AND
^       Bitwise exclusive OR
|       Bitwise inclusive OR


=====>>>> Click Here to see the sample Example-2
 

Java Escape Characters:- 

Escape Sequence
Character Value
\b
Backspace
\t
Horizontal tab
\n
Newline
\f
Form feed
\r
Carriage return
\"
Double quote
\'
Single quote
\\
Backslash
\xxx
The Latin-1 character with the encoding xxx, where xxx is an octal (base 8) number between 000 and 377. The forms \x and \xx are also legal, as in'\0', but are not recommended because they can cause difficulties in string constants where the escape sequence is followed by a regular digit.
\uxxxx
The Unicode character with encoding xxxx, where xxxx is four hexadecimal digits. Unicode escapes can appear anywhere in a Java program, not only in character and string literals.

 

Converting Primitive Types:-

 Primitive types and objects are very different things in Java, and you can’t automatically cast between the two.
As an alternative, the java.lang package includes classes that correspond to each primitive data type:Float, Boolean, Byte, and so on. Most of these classes have the same names as the data types, except that the class names begin with a capital letter (Short instead of short, Double instead ofdouble, and the like). Also, two classes have names that differ from the corresponding data type:Character is used for char variables, and Integer is used for int variables.

String str=”65789”
int  num1= Integer.parseInt(Str);

=====>>>  Click Here to see sample Example-4

Type Casting

Casts of primitive types are most often used to convert floating-point values to integers. 
int i = 13;
byte b = (byte) i;   // Force the int to be converted to a byte
i = (int) 13.456;    // Force this double literal to the int 13 

Associativity and precedence of operators:-


Table gives the rules determining the associativity and precedence of all the operators in C. Associativity means whether an expression like x R y R z (where R is a operator such as + or <=) should be evaluated `left-to-right' i.e. as (x R y) R z or `right-to-left' i.e. as x R (y R z). Precedence determines how an expression like x R y S z should be evaluated (now R and S are different operators). If R has higher precedence than S, it will be evaluated as (x R y) S z, while if S has higher precedence than R it will be treated as x R (y S z).
The associativity and precedence of the operators in C.
Operators in order of precedence
Associativity
(), [], ->, .
left to right
!, ~, ++, -, - (unary), * (indirection), & (address-of), sizeof, casts
right to left
* (multiplication), /, %
left to right
+, - (subtraction)
left to right
«, »
left to right
<, <=, >=, >
left to right
==, !=
left to right
& (bitwise and)
left to right
^
left to right
|
left to right
&&
left to right
||
left to right
?:
right to left
=, +=, -= etc.
right to left
,
left to right

A class can contain any of the following variable types:-
Local variables: Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
Instance variables: Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
Class variables: Class variables are variables declared with in a class, outside any method, with the static keyword.
 Constructors:
         ·       When discussing about classes, one of the most important sub topic would be constructors.                Every class has a constructor. If we do not explicitly write a constructor for a class the Java                   compiler builds a default constructor for that class.
       ·  Each time a new object is created, at least one constructor will be invoked. The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor.
·         Arrays:-
An array is a set of values where each value is identified by an index. You can make an array of ints, doubles, or any other type, but all the values in an array have to have the same type.
Syntactically, arrays types look like other Java types except they are followed by []. For example, int[] is the type "array of integers" and double[] is the type "array of doubles."
You can declare variables with these types in the usual ways:
    int[] count; 
    double[] values; 

Until you initialize these variables, they are set to null. To create the array itself, use the new command.
    count = new int[4]; 
    values = new double[size]; 

The first assignment makes count refer to an array of 4 integers; the second makes values refer to an array of doubles. The number of elements in values depends on size. You can use any integer expression as an array size.
The following figure shows how arrays are represented in state diagrams:



The large numbers inside the boxes are the elements of the array. The small numbers outside the boxes are the indices used to identify each box. When you allocate a new array, the elements are initialized to zero.

Copying arrays

When you copy an array variable, remember that you are copying a reference to the array. For example:
    double[] a = new double [3]; 
    double[] b = a; 

This code creates one array of three doubles, and sets two different variables to refer to it. This situation is a form of aliasing.

 

====>>> Click Here to see the sample Example-5 


Command-Line Arguments:-

A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched.
The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run.
The arguments passed from the console can be received in the java program and it can be used as an input.
So, it provides a convenient way to check the behavior of the program for the different values. You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.

Simple example of command-line argument in java

The Echo class example displays each of its command-line arguments on a line by itself:

public class Echo {
    public static void main (String[] args) {
        for (String s: args) {
            System.out.println(s);
        }
    }
}

The following example shows how a user might run Echo. User input is in italics.
C:\javabysasidhar> java Echo Drink Hot Java
Drink
Hot
Java

This simple application displays each of its command line arguments on a line by itself:
class Echo {
    public static void main (String args[]) {
        for (int i = 0; i < args.length; i++)
            System.out.println(args[i]);
    }
}

=====> Click Here to see the sample Example - 4

C:\javabysasidhar> java Echo Drink Hot Java
Drink
Hot
Java

No comments:

Post a Comment