Professional Documents
Culture Documents
Java Basic
Java Basic
It can be shown that anything solvable using one of these paradigms can
be solved using the others; however, certain types of problems lend
themselves more naturally to specific paradigms.
1. Imperative Paradigm
“First do this and next do that”
This statement describes the spirit of the imperative paradigm.
The order of the steps is crucial, because a given step will have different
consequences depending on the current values of variables when the step is
executed.
Popular programming languages are imperative. There are two reasons for
such popularity:
Disadvantages
3. Functional
The Functional Programming paradigm views all subprograms as
functions in the mathematical sense-informally, they take in arguments and
return a single solution.
The solution returned is based entirely on the input, and the time at which
a function is called has no relevance.
4. Object-Oriented
Object Oriented Programming (OOP) is a paradigm in which real-world
objects are each viewed as seperate entities having their own state which is
modified only by built in procedures, called methods.
Objects are organized into classes, from which they inherit methods and
equivalent variables. The object-oriented paradigm provides key benefits
of reusable code and code extensibility.
Modern Programming Era begins with: C
The C language shook the computer world. The creation of C was a direct
result of the need for a structured, efficient, high-level language that could
replace assembly code when creating systems programs.
Evolution of OO Methodology
During the late 1970s and early 1980s, C became the dominant computer
programming language, and it is still widely used today. Since C is a
successful and useful language, you might ask why a need for something
else existed. The answer is complexity.
Simula
The introduction of Simula-67 brought with it the first true programming
object, classes, and a form of inheritance; therefore, Simula is an
important milestone in any discussion on O-O programming languages.
Smalltalk
Many consider that the first truly O-O language was Smalltalk, developed
at the Learning Research Group at Xerox's Palo Alto Research Center in
the early 1970s.
C++:
C++ was invented by Bjarne Stroustrup in 1979, while he was working at
Bell Laboratories in Murray Hill, New Jersey. Stroustrup initially called
the new language “C with Classes.” However, in 1983, the name was
changed to C++.
C# .NET
Microsoft responded to the popularity of Java by producing a version of
Java called Visual J++.
As you know, all computer programs consist of two elements: code and
data. Furthermore, a program can be conceptually organized around its
code or around its data.
That is, some programs are written around “what is happening” and others
are written around “who is being affected.”
These are the two paradigms that govern how a program is constructed.
The first way is called the process-oriented model.
Each object holds data and code to operate the data. Object can interact
without having to identify the details of each other’s data or code. It is
sufficient to identify the type of message received and the type of reply
returned by the objects. Another example of object is CAR.
The complete set of data and code of an object can be made a user defined
data type with the help of class. The objects are variable of type class.
[Representation of class]
3. Data Abstraction
Data abstraction refers to the act of representing important description
without including the background details or explanations.
Classes use the concept of abstraction and are defined as a list of abstract
attributes such as size, cost and functions operate on these attributes.
They summarize all the important properties of the objects that are to be
created.
4. Data Encapsulation
Data Encapsulation means wrapping of data and functions into a single
unit (i.e. class). It is most useful feature of class. The data is not easy to
get to the outside world and only those functions which are enclosed in
the class can access it.
These functions provide the boundary between Object’s data and program.
This insulation of data from direct access by the program is called as Data
hiding.
[Encapsulation]
5. Inheritance
Inheritance is the process by which objects of one class can get the
properties of objects of another class. Inheritance means one class of
objects inherits the data and behaviors from another class.
7. Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed
in response to the call. Dynamic binding means that the code related with
a given procedure call is not known until the time of the call at run time.
Dynamic binding is associated with polymorphism and inheritance.
Introduction to Java
You can use Java to write computer applications that play games, store
data or do any of the thousands of other things computer software can do.
This is reason why Java has become a trendy language for programming
on Internet which interconnects different kind of systems worldwide.
Java certifies portability in two ways. First way is, Java compiler generates
the bytecode and that can be executed on any machine. Second way is,
size of primitive data types are machine independent.
3. Object- oriented
Java is truly complete object-oriented language. In Java, almost everything
is an Object. All program code and data exist in objects and classes. Java
comes with an extensive set of classes; organize in packages that can be
used in program by Inheritance. The object model in Java is trouble-free
and easy to enlarge.
Java also includes the concept of exception handling, which detain serious
errors and reduces all kind of threat of crashing the system.
Security is an important feature of Java and this is the strong reason that
programmer use this language for programming on Internet.
The absence of pointers in Java ensures that programs cannot get right of
entry to memory location without proper approval.
5. Distributed
Java is called as Distributed language for construct applications on
networks which can contribute both data and programs.
Java applications can open and access remote objects on Internet easily.
That means multiple programmers at multiple remote locations to work
together on single task.
8. High performance
Java performance is very extraordinary for an interpreted language,
majorly due to the use of intermediate bytecode.
Java can also establish the type of class through the query building it
possible to either dynamically link or abort the program, depending on the
reply.
This machine is called the Java Virtual machine and it exits only inside the
computer memory.
*Following figure shows the process of compilation.
java(Java Interpreter)
As we learn that, we can use any text editor for writing program and
then save that program with “.java” extension. Java compiler convert
the source code or program in bytecode and interpreter convert
“.java” file in “.class” file.
Syntax:
C:\java filename
JAR files are built on the ZIP file format and have the .jar file
extension. Computer users can create or extract JAR files using the
jar command that comes with a JDK
Java Program Structure
Documentation Section
Package Section
Import Section
Interface Section
Class Definitions
DOCUMENTATION SECTION:
It is a set of comment lines giving the name of the program,the
author and the other details,which the programmer would like
to refer.
PACKAGE STATEMENT:
The first statement allowed in Java files is a
package statement.Thisstatement declares a package name and
informs the compiler that the classes defined here belong to this
package.
Exa: package student;
IMPORT STATEMENT:
Similar to #include statement in C.
Ex:import student.test;
This statement instructs the interpreter to load the test class
contained in package student. Using import statement ,we can
access to classes that part of other named packages.
INTERFACE STATEMENT:
Interface like class but includes group of methods declaration.
Used when we want to implement multiple inheritance
feature.
CLASS DEFINITION:
Java program may contain multiple class definition.
Classes are primary feature of Java program.
The classes are used to map real world problems.
As you can see by looking at the program, the name of the class defined
by the program is also Example. Because in Java, all code must reside
inside a class. By convention, the name of that class should match the
name of the file that holds the program(main function).
You should also make sure that the capitalization of the filename matches
the class name. The reason for this is that Java is case-sensitive. This
convention makes it easier to maintain and organize your programs.
Thus, the output of javac is not code that can be directly executed.
To actually run the program, you must use the Java interpreter,
called java.
C:\>java Example
When Java source code is compiled, each individual class is put into
its own output file named after the class and using the .class
extension.
The keyword void simply tells the compiler that main( ) does not
return a value.
The next line of code is shown here. Notice that it occurs inside
main( ).
System.out.println("This is a simple Java program.");
This line outputs the string “This is a simple Java program.” followed
by a new line on the screen. Output is actually accomplished by the
built-in println( ) method. println( ) can be used to display other
types of information, too.
To solve these problems, a new language standard was developed i.e. Unicode
System.
In unicode, character holds 2 byte, so java also uses 2 byte for characters.
lowest value:\u0000
highest value:\uFFFF
To enable a computer system for storing text and numbers which is
understandable by humans, there should be a code that transforms characters
into numbers.
Unicode is a standard of defining the relevant code by using character
encoding. Character encoding is the process for assigning a number for every
character. The central objective of Unicode is to unify different language encoding
schemes in order to avoid confusion among computer systems that uses limited
encoding standards such as ASCII, EBCDIC etc.
Java Unicode:
The evolution of Java was the time when the Unicode standards had been defined
for very smaller character set. Java was designed for using Unicode Transformed
Format (UTF)-16, when the UTF-16 was designed. The ‘char’ data type in Java
originally used for representing 16-bit Unicode. Hence Java uses Unicode
standard
JAVA BASICS
Class variables are similar to instance variables, except their values apply
to all that class’s instances (and to the class itself) rather than having
different values for each object.
Local variables are declared and used inside method definitions. For
example, index counters in loops, as temporary variables, They can also
be used inside blocks ({}).
For Example:
class FamilyMember {
static String surname = “Johnson”;
String name;
int age;
...
}
Instances of the class FamilyMember each have their own values for name
and age. But the class variable surname has only one value for all family
members. Change surname, and all the instances of FamilyMember are
affected.
To access class variables, you use the same dot notation as you do with
instance variables. To get or change the value of the class variable, you can use
either the instance or the name of the class on the left side of the dot. Both the
lines of output in this example print the same value):
FamilyMember dad = new FamilyMember()
System.out.println(“Family’s surname is: “ +
dad.surname);
System.out.println(“Family’s surname is: “ +
FamilyMember.surname);
Declaring Variables
To use any variable in a Java program, you must first declare it. Variable
declarations consist of a type and a variable name:
int myAge;
String myName;
boolean isTired;
You can string together variable names with the same type:
int x, y, z;
String firstName, LastName;
You can also give each variable an initial value when you declare it:
int myAge, mySize, numShoes = 28;
String myName = “Laura”;
boolean isTired = true;
int a = 4, b = 5, c = 6;
Every variable has a type, every expression has a type, and every
type is strictly defined. Second, all assignments, whether explicit or via
parameter passing in method calls, are checked for type compatibility.
Any type mismatches are errors that must be corrected before the
compiler will finish compiling the class.
Java defines eight primary (or elemental) data types: byte, short, int, long,
char, float, double, and boolean. These can be put in four groups:
■ Integers: This group includes byte, short, int, and long, which are
for whole valued signed numbers.
■ Floating-point numbers: This group includes float and double,
which represent numbers with fractional precision.
■ Characters: This group includes char, which represents symbols in
a character set, like letters and numbers.
■ Boolean: This group includes boolean, which is a special type for
representing true/false values.
Integers
All integer types are signed, positive and negative values. Java does not
support unsigned, positive-only integers.
Floating-Point Types
Floating-point numbers, also known as real numbers, are used when
evaluating expressions that require fractional precision. For example,
calculations such as square root, or transcendental such as sine and
cosine, result in a value whose precision requires a floating-point type.
Name Width in Bits Approximate Range
double 64 4.9e–324 to 1.8e+308
float 32 1.4e−045 to 3.4e+038
Characters
In Java, the data type used to store characters is char. In C/C++, char is
an integer type that is 8 bits wide. This is not the case in Java. Instead,
Java uses Unicode to represent characters. Unicode defines a fully
international character set that can represent all of the characters found
in all human languages.
Booleans
Java has a simple type, called boolean, for logical values. It can have only
one of two possible values, true or false. This is the type returned by all
relational operators, such as a < b. boolean is also the type required by the
conditional expressions that govern the control statements such as if and
for.
Symbolic Constants
In Java, you use the keyword final to create a constant.
Syntax:
final type Symbolic_name=value;
For example,
final double CM_PER_INCH = 2.54;
The keyword final indicates that you can assign to the variable once, then
its value is set once and for all. It is customary to name constants in all
upper case. And Do not declare in method.
It is probably more common in Java to want a constant that is available to
multiple methods inside a single class. These are usually called class
constants. You set up a class constant with the keywords static final. Here
is an example of using a class constant:
public class Constants2
{
public static final double CM_PER_INCH = 2.54;;
public static void main(String[] args)
{
double paperWidth = 8.5;
double paperHeight = 11;
System.out.println("Paper size in centimeter: "
+ paperWidth * CM_PER_INCH + " by "
+ paperHeight * CM_PER_INCH);
}
}
In Java, there are two types of constant as follows:
o Numeric Constants:
Integer constant
Real constant
o Character Constants:
Character constant
String constant
Arrays
An array is a group of like-typed variables that are referred to by a common
name. Arrays of any type can be created and may have one or more
dimensions. A specific element in an array is accessed by its index.
One-Dimensional Arrays
A one-dimensional array is, essentially, a list of like-typed variables. To
create an array, you first must create an array variable of the desired type.
The general form of a one dimensional array declaration is:
type var-name[ ];
Here, type declares the base type of the array. The base type determines
the data type of each element that comprises the array.
The base type for the array determines what type of data the array will
hold.
you must allocate using new and assign it to array. new is a special
operator that allocates memory.
To use new to allocate an array, you must specify the type and number of
elements to allocate.
In Java, all arrays are dynamically allocated. Once you have allocated an
array, you can access a specific element in the array by specifying its index
within square brackets. All array indexes start at zero. For example,
month_days[1] = 28;
Arrays can be initialized when they are declared. The array will
automatically be created large enough to hold the number of elements you
specify in the array initializer. There is no need to use new. For example,
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31};
The Java run-time system will check to be sure that all array indexes are
in the correct range. (In this regard, Java is fundamentally different from C/C++,
which provide no run-time boundary checks.)
Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays. To declare
a multidimensional array variable, specify each additional index using another
set of square brackets.
The following program numbers each element in the array from left to
right, top to bottom, and then displays these values:
// Demonstrate a two-dimensional array.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
This program generates the following output:
01234
56789
10 11 12 13 14
15 16 17 18 19
When you allocate memory for a multidimensional array, you need only
specify the memory for the first (leftmost) dimension. You can allocate the
remaining dimensions separately.
For example, this following code allocates memory for the first dimension
of twoD when it is declared. It allocates the second dimension manually.
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
Literals
Literals are used to indicate simple values in your Java programs.
Literal is a programming language term, which essentially means that
what you type is what you get.
For example, if you type 4 in a Java program, you automatically get an
integer with the value 4. If you type ‘a’, you get a character with the value
a.
Number Literals
There are several integer literals. 4, for example, is a decimal integer
literal of type int.
A decimal integer literal larger than an int is automatically of type
long. You also can force a smaller number to a long by appending
an L or l to that number (for example, 4L is a long
integer of value 4).
Negative integers are preceded by a minus sign—for example,
-45.
Integers can also be expressed as octal or hexadecimal: a
leading 0 indicates that a number is octal—for example, 0777
or 0004. A leading 0x (or 0X) means that it is in hex (0xFF,
0XAF45).
Hexadecimal numbers can contain regular digits (0–9) or
upper- or lowercase hex digits (a–f or A–F).
Floating-point literals usually have two parts: the integer part and
the decimal part—for example, 5.677777. Floating-point literals
result in a floating-point number of type double, regardless of the
precision of that number. You can force the number to the type float
by appending the letter f (or F) to that number—for example, 2.56F.
You can use exponents in floating-point literals using the
letter e or E followed by the exponent: 10e45 or .36E-2.
Boolean Literals
Boolean literals consist of the keywords true and false. These
keywords can be used anywhere you need a test or as the only
possible values for boolean variables.
Character Literals
Character literals are expressed by a single character surrounded
by single quotes: ’a’, ’#’, ’3’,and so on.
Characters are stored as 16-bit Unicode characters. Table 3.2 lists
the special codes that can represent nonprintable characters, as well
as characters from the Unicode character set.
Table: Character escape codes.
Escape Meaning
\n Newline
\t Tab
\b Backspace
\r Carriage return
\f Formfeed
\\ Backslash
\’ Single quote
\” Double quote
\ddd Octal
\xdd Hexadecimal
\udddd Unicode character
Note: Java does not include character codes for \a (bell) or \v (vertical tab).
String Literals
A combination of characters is a string. Strings in Java are instances of
the class String.
Strings are not simple arrays of characters as they are in C or C++, but
strings are real objects in Java. They have methods that enable you to
combine, test, and modify strings very easily.
String literals consist of a series of characters inside double quotes:
“Hi, I’m a string literal.”
“” //an empty string
Strings can contain character constants such as newline, tab, and Unicode
characters:
“A string with a \t tab in it”
“Nested strings are \”strings inside of\” other strings”
“This string brought to you by Java\u2122”
Note:In the last example, the Unicode code sequence for \u2122 produces a
trademark symbol (™).
When you use a string literal in your Java program, Java automatically
creates an instance of the class String for you with the value you give it.
However, not all types are compatible, and thus, not all type conversions
are implicitly allowed. For instance, there is no conversion defined from
double to byte. Fortunately, it is still possible to obtain a conversion
between incompatible types.
To do so, you must use a cast, which performs an explicit conversion
between incompatible types.
Although the automatic type conversions are helpful, they will not fulfill
all needs. For example, what if you want to assign an int value to a byte
variable? This conversion will not be performed automatically, because a
byte is smaller than an int.
int a;
byte b;
// ...
b = (byte) a;
Thus, when a floating-point value is assigned to an integer type, the
fractional component is lost.
OPERATORS IN JAVA
Arithmetic Operators
Operator Result
+ Addition
– Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
2:Assignment Operators
+= Addition assignment
–= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
The increment operator increases its operand by one. The decrement operator
decreases its operand by one.
For example, this statement: x = x + 1; can be rewritten like this by use of the
increment operator: x++;
Similarly, this statement: x = x - 1; is equivalent to x--;
These operators are unique in that they can appear both in postfix form and
prefix form. In postfix form, the previous value is obtained for use in the
expression, and then the operand is modified.
For example:
x = 42;
y = ++x;
In this case, y is set to 43 as you would expect, because the
increment occurs before x is assigned to y.
Thus, the line y = ++x; is the equivalent of these two statements:
x = x + 1;
y = x;
However, when written like this,
x = 42;
y = x++;
the value of x is obtained before the increment operator is executed,
so the value of y is 42. Of course, in both cases x is set to 43.
Here, the line y = x++; is the equivalent of these two statements:
y = x;
x = x + 1;
Relational Operators
The relational operators determine the relationship that one operand has
to the other. Specifically, they determine equality and ordering. The
relational operators are shown here:
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Boolean Logical Operators
The Boolean logical operators shown here operate only on boolean
operands. All of the binary logical operators combine two boolean values
to form a resultant boolean value.
Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
The ?: Operator
Java includes a special ternary (three-way) operator that can replace
certain types of if-then-else statements.
The ? has this general form:
expression1 ? expression2 : expression3
Here, expression1 can be any expression that evaluates to a boolean value.
If expression1 is true, then expression2 is evaluated; otherwise,
expression3 is evaluated. The result of the ? operation is that of the
expression evaluated. Both expression2 and expression3 are required to
return the same type, which can’t be void.
Operator Precedence
Operator precedence determines the order in which expressions are
evaluated.
As following table shows, new operator has a highest precedence.
COMMAND LINE ARGUMENTS:
Command line arguments are parameters that are supplied to the
application program at the time of invoking its execution.
They must be supplied at the time of its execution following the file
name.
The number of element in the array args can be getting with the length
parameter.
For example:
class Add
{
public static void main(String args[])
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int c=a+b;
System.out.println(“Addition is=”+c);
}
}
output:
c:\javac Add.java
c:\java Add 5 2
7
CONTROL STATEMNTS
A programming language uses control statements to cause the flow of
execution to advance and branch based on changes to the state of a
program.
Java’s program control statements can be put into the following categories:
selection, iteration, and jump.
Selection statements allow your program to choose different paths
of execution based upon the outcome of an expression or the state of a
variable.
Iteration statements enable program execution to repeat one or
more statements (that is, iteration statements form loops).
Jump statements allow your program to execute in a nonlinear
fashion
Selection Statement:
Selection statement is also called as Decision making statements because
it provides the decision making capabilities to the statements.
In selection statement, there are two types:
if statement
switch statement
These two statements are allows you to control the flow of a program with
their conditions.
if Statement:
The “if statement” is also called as conditional branch statement. It is used
to program execution through two paths.
The syntax of “if statement” is as follows:
Syntax:
if (condition)
{
Statement 1;
...
}
else
{
Statement 2;
...
}
The “if statement” is a commanding decision making statement and is used
to manage the flow of execution of statements. The “if statement” is the
simplest one in decision statements. Above syntax is shows two ways
decision statement and is used in combination with statements.
* switch statement:
In Java, switch statement check the value of given variable or statement
against a list of case values and when the match is found a statement-
block of that case is executed. Switch statement is also called as multiway
decision statement.
Syntax:
switch(condition)// condition means case value
{
case value-1:statement block1;break;
case value-2:statement block2;break;
case value-3:statement block3;break;
…
default:statement block-default;break;
}
statement a;
The condition result can be byte, short, character or an integer. value-
1,value-2,value-3,…are constant and is called as labels. Each of these
values be matchless or unique with the statement. Statement block1,
Statement block2, Statement block3,..are list of statements which contain
one statement or more than one statements.
switch(ch)
{
case 1:System.out.println("Balance is:"+bal);
break;
default:break;
}
}
}
Output:
C:\MCA>javac bankac.java
C:\MCA>java bankac 1
Menu
1:check balance
2:withdraw amount... plz enter choice and amount
3:deposit amount... plz enter choice and amount
4:exit
Balance is:20000
C:\MCA>java bankac 2 2000
Menu
1:check balance
2:withdraw amount... plz enter choice and amount
3:deposit amount... plz enter choice and amount
4:exit
Balance is18000
* Nested switch Statements
You can use a switch as part of the statement sequence of an outer
switch. This is called a nested switch.
Here, the case 1: statement in the inner switch does not conflict
with the case 1: statement in the outer switch. The count variable
is only compared with the list of cases at the outer level. If count is
1, then target is compared with the inner list cases.
Iteration Statement:
Jumps in statement:
Statements or loops perform a set of operartions continually until the
control variable will not satisfy the condition. but if we want to break the
loop when condition will satisy then Java give a permission to jump from
one statement to end of loop or beginning of loop as well as jump out of a
loop.
“break” keyword use for exiting from loop and “continue” keyword use for
continuing the loop.
Following statements shows the exiting from loop by using “break”
statement.
do-while loop:
do
{
if(condition)
{
break;//exit from if loop and do-while loop
}
}
While(condition);
For loop:
for(…………)
{
if(condition)
break; ;//exit from if loop and for loop
}
While loop:
while(…………)
{
If(cond)
break; ;//exit from if loop and while loop
}
For loop:
for(…………)
{
if(…………..)
continue ;// continue the for loop
}
While loop:
while(…………)
{
if(…………..)
continue ;// continue the while loop
}
Return statement:
The last control statement is return. The return statement is
used to explicitly return from a method. That is, it causes program
control to transfer back to the caller of the method.
At any time in a method the return statement can be used to cause
execution to branch back to the caller of the method. Thus, the
return statement immediately terminates the method in which it is
executed.