Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
24 views5 pages

Java

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 5

1 OOPs Principles: Encapsulation, Inheritance and Polymorphism are the basic principles of

anyobject oriented programming language.


Encapsulation is the mechanism to bind the data and code working on that data into a single
entity. It provides the security for the data by avoiding outside manipulations. In Java, encapsulation
is achieved using classes. A class is a collection of data and code. An object is an instance of a
class. Specifically, the data or variables inside the class are called as member variables or
instance variables or data members.
Inheritance allows us to have code re-usability. It is a process by which one object can acquire
the properties of another object. It supports the concept of hierarchical classification. For example,
consider a large group of animals having few of the abstract attributes like size, intelligence, skeletal
structure etc. and having behavioral aspects like eating, breathing etc. Mammals have all the
properties of Animals and also have their own specific features like type of teeth, mammary glands
etc. that make them different from Reptiles. Similarly, Cats and Dogs have all the characteristics of
mammals, yet with few features which are unique for themselves.
Polymorphism can be thought of as one interface, multiple methods. It is a feature that allows
one interface to be used for a general class of actions. The specific action is determined by the
exact nature of the situation. Consider an example of performing stack operation on three different
types of data viz. integer, floating-point and characters.

A strongly-typed programming language is one in which each type of data (such as integer,
character, hexadecimal, packed decimal, and so forth) is predefined as part of the programming
language and all constants or variables defined for a given program must be described with one of
the data types. Certain operations may be allowable only with certain data types.
In other words, every variable has a type, every expression has a type, and every type is strictly
defined. And, all assignments, whether explicit or via parameter passing in method calls, are
checked for type compatibility. There are no automatic coercions or conversions of conflicting types
as in some languages.
The Java compiler checks all expressions and parameters to ensure that the types are compatible.
Any type mismatches are errors that must be corrected before the compiler will finish compiling the
class.
These features of Java make it a strongly typed language.
2 Lexical issues
Whitespace : In Java, whitespace is a space, tab or newline. Usually, a space is used to separate
tokens; tab and newline are used for indentation.
Identifiers : Identifiers are used for class names, method names, and variable names. An identifier
may be any sequence of uppercase and lowercase letters, numbers, or the underscore and dollar-
sign characters. They must not begin with a number. As Java is case-sensitive, Avg is a different
identifier than avg.
Examples of valid identifiers: Avg, sum1, $x, sum_sq etc.
Examples of invalid identifiers: 2sum, sum-sq, x/y etc.
Literals : A constant value in Java is created by using a literal representation of it. For example, 25
(an integer literal), 4.5 (a floating point value), ‘p’ (a character constant, “Hello World” (a string
value).
Comments : There are three types of comments defined by Java. Two of these are well-know viz.
single-line comment ( starting with //), multiline comment (enclosed within /* and */). The third
type of comment viz. documentation comment is used to produce an HTML file that documents
your program. The documentation comment begins with a /** and ends with a */.
Separators : In Java, there are a few characters that are used as separators. The most commonly
used separator in Java is the semicolon which is used to terminate statements.
Keywords : There are 50 keywords currently defined in the Java language as shown in the
following table. These keywords, combined with the syntax of the operators and separators, form
the foundation of the Java language. These keywords cannot be used as names for a variable,
class, or method.
3 The working of a Java program by taking an example –
Illustration of F Java Program
class Prg1
{
public static void main(String args[ ])
{
System.out.println(“Hello World!!!”);
}
}
Save this program as Prg1.java. A java program source code is a text file containing one or more
class definitions is called as compilation unit and the extension of this file name should be .java.
To compile above program, use the following statement in the command prompt –
javac Prg1.java

Now, the javac compiler creates a file Prg1.class containing bytecode version of the program,
which can be understandable by JVM. To run the program, we have to use Java application
launcher called java.
That is, use the command –
java Prg1
The output of the program will now be displayed as –
Hello World!!!
the terminologies used in the above program now –
class is the keyword to declare a class.
Prg1 is the name of the class.
main() is name of the method from which the program execution starts.
public is a keyword indicating the access specifier of the method. must be declared as public as it
needs to be called from outside the class.
static The keyword static allows main() to be called without having to instantiate a particular
instance of the class. This is necessary since main() is called by the java Virtual Machine before
any objects are made.
void indicates that main() method is not returning anything.
String args[ ] The main() method takes an array of String objects as a command-line argument.
System is a predefined class (present in java.lang package) which gives access to the system.
out is a static final (means not inheritable) field (ie, variable)in System class System.out.
println is a public method in PrintStream class to print the data values.
4 Data types integers and floating point.

Integers:
Java defines four integer types viz. byte, short, int and long. All these are signed numbers and
Java does not support unsigned numbers. The width of an integer type should not be thought of
as the amount of storage it consumes, but rather as the behaviour it defines for variables and
expressions of that type.
byte : This is the smallest integer type. Variables of type byte are especially useful when you are
working with a stream of data from a network or file. They are also useful when you are working
with raw binary data that may not be directly compatible with Java’s other built-in types. Byte
variables are declared by use of the byte keyword. For example,
byte b, c;
short : It is probably the least-used Java type. Here are some examples of short variable
declarations:
short s;
short t;
int : The most commonly used integer type is int. In addition to other uses, variables of type int are
commonly employed to control loops and to index arrays.
long : It is useful for those occasions where an int type is not large enough to hold the desired
value. The range of a long is quite large.

Floating –Point Types:


There are two kinds
of floating-point types, float and double, which represent single- and double- precision numbers,
respectively.
float : The type float specifies a single-precision value that uses 32 bits of storage.
double : Double precision is actually faster than single precision on some modern processors
that have been optimized for high-speed mathematical calculations.

5 The Scope and Lifetime of Variables


Java allows variables to be declared within any block. A block is begun with an opening
curly brace and ended by a closing curly brace. A block defines a scope. A scope determines what
objects are visible to other parts of your program. It also determines the lifetime of those objects.
Many other computer languages define two general categories of scopes: global and local.
However, these traditional scopes do not fit well with Java’s strict, object-oriented model. As a
general rule, variables declared inside a scope are not visible (that is, accessible) to code that is
defined outside that scope. Thus, when you declare a variable within a scope, you are localizing that
variable and protecting it from unauthorized access and/or modification.

Scope Program
class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}

The output generated by this program:

X and y: 10 20

X is 200

Lifetime Program
class LifeTime {
public static void main(String args[]) {
int x;
for(x = 0; x < 3; x++) {
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}
The output generated by this program:
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100

6 Type conversion and casting in JAVA


It is quite common in a program to assign value of one type to a variable of nother type. If two types
are compatible, Java performs implicit type conversion. For example, int to long is always
possible. But, whenever the types at two sides of an assignment operator are not compatible, then
Java will not do the conversion implicitly. For that, we need to go for explicit type conversion or
type casting.
Java’s Automatic Conversions
When one type of data is assigned to another type of variable, an automatic type conversion will
take place if the following two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place. For example, the int type
is always large enough to hold all valid byte values, so no explicit cast statement is required. For
widening conversions, the numeric types, including integer and floating-point types, are compatible
with each other.
Type Promotion Rules
Java defines several type promotion rules that apply to expressions. They are as follows:
All byte, short, and char values are promoted to int.
If one operand is a long, the whole expression is promoted to long.
If one operand is a float, the entire expression is promoted to float.
If any of the operands is double, the result is double.
ii) Program
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}

This program generates the following output:


Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67

7 Char type demo program:


class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}

This program displays the output:


ch1 and ch2: X Y

8 Boolean Type demo program


class BoolTest {
public static void main(String args[]) {
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
if(b) System.out.println("This is executed.");
b = false;
if(b) System.out.println("This is not executed.");
System.out.println("10 > 9 is " + (10 > 9));
}
}
The output generated by this program:
b is false
b is true
This is executed.
10 > 9 is true

9 2D array example.
10 Irregular Array example.
11 Write a java program to find the average of given numbers (90.4,93.5,98.9,89.6,56.8)
by initializing the array
12 Write a java program to initialize 3-Dimensional matrix (3 by 4 by 5).

You might also like