Академический Документы
Профессиональный Документы
Культура Документы
Overview of Java
Java is an object-oriented programming language with its own runtime
environment.
Java is a programming language and a platform. Java is a high level, robust,
secured and object-oriented programming language.
Platform: Any hardware or software environment in which a program
runs is known as a platform. Since Java has its own runtime environment
(JRE) and API, it is called platform.
Java was developed by Sun Microsystems Inc. in 1991, later acquired by Oracle
Corporation. It was conceived by James Gosling and Patrick Naughton. It took
.in
18 months to develop the first working version. (The initial name was Oak but it
was renamed to Java in 1995 as OAK was a registered trademark of another
Tech company).
Java programs are platform independent which means they can be run on any
Java code that runs on one platform does not need to be recompiled to run on
another platform, it’s called “Write Once, Run Anywhere” (WORA).
w
Java Virtual Machine (JVM) executes Java code, but is written in platform
specific languages such as C/C++/ASM etc. JVM is not written in Java and hence
w
.in
Applets – This is another type of Java program that used within a web page
to add many new features to a web browser.
J2EE – The software Java 2 Enterprise Edition are used by various
another. ac
companies to transfer data based on XML structured documents between one
machine or server such as media player, antivirus etc. AWT and Swing are
used in Java for creating standalone application.
Enterprise Application: An application that is distributed in nature, such
as banking applications etc. It has the advantage of high level security, load
balancing and clustering. In java, EJB is used for creating enterprise
applications.
Mobile Application: Java is used to create application for mobile devices.
Currently Java ME is used for creating applications for small devices.
.in
resources.
ac
tu
.v
w
neutral object file format which makes the compiled code to be executable
on many processors, with the presence of java runtime system.
w
Portable – Java code that is written on one machine can run on another
machine. The platform independent byte code can be carried to any
platform for execution that makes java code portable.
Multi-threaded – With Java’s multi-threaded feature it is enabled a
program to perform several tasks simultaneously.
High Performance – With the use of Just-In-Time compilers Java
enables high performance.
To write java programs, you will need a text editor. There are even more
sophisticated IDE available.
Notepad – On Windows machine you can use any simple text editor like
Notepad, TextPad.
Netbeans – is a Java IDE that is open source and free which can be
downloaded from https://www.netbeans.org/index.html.
Eclipse – A Java IDE developed by the open-source community and can be
downloaded from https://www.eclipse.org/.
Environment Setup and Java Program Structure
.in
Before Installation and setting up of environment variable, let us know about Java
SE Development Kit (JDK). It contains
1. JDK (Java Development Kit)
2. JRE (Java Run Time Environment)
3. JVM (Java Virtual Machine)
Java Development Kit (JDK)
ac
tu
JDK contains everything that will be required to develop and run Java
application.
.v
JDK includes a complete JRE (Java Runtime Environment) plus tools for
Developing, Debugging, and Monitoring Java applications. JDK is needed to
develop Java applications and Applets as well as run them. It contains
w
o Archiver (jar)
o Documentation Generator (java doc)
javac: javac is the compiler for the Java programming language, it’s used
to compile .java file.
Example: c:\> javac TestFile.java
java: command is used to compile a java program, it creates a class file
which can be run by using java command.
Example: c:\> java TestFile.class
.in
Java Virtual Machine (JVM)
The Java Virtual Machine is called JVM, is an abstract computing machine or
virtual machine interface that drives the java code.
ac
Mostly in other Programming Languages, compiler produce code for a
particular system but Java compiler produces Bytecode for a JVM.
Bytecode is an intermediary language between Java source and the host
tu
system.
JVM interprets the bytecode to OS specific instructions.
.v
The JVM is the heart of the Java language’s developed based on "write-once, run-
anywhere" principle.
w
.in
Let us create HelloWorld.java program,
class HelloWorld
{
{ ac
public static void main(String args[])
System.out.println("HelloWorld!!!");
tu
}
}
In the above program,
.v
visible to all.
static is a keyword, if we declare any method as static, it is known as
w
method.
void is the return type of the method, it means it doesn't return any value.
main represents beginning of the program.
String[] args is used for command line argument.
System.out.println() is used print statement.
Note: Name of the file & name of a class must be same.
How to Compile and Execute java program
To Compile: javac helloWorld.java
To Execute: java helloWorld
.in
int
long
float
double
char
ac
tu
boolean
The following should be understood for every data type:
.v
.in
Keyword: char
Example: char ch = 'A';
Short
ac
Minimum Value can be represented: '\u0000' (0)
Maximum Value can be represented: '\uffff' (65,535)
tu
Allocated Memory Size: 2 bytes or 16 bits
Default value: Zero
.v
Keyword: short
Example: short s = 1000;
w
.in
Keyword: long
Example: long b = 100000L;
Double
ac
Minimum Value can be represented: -9223372036854775808
Maximum Value can be represented: 9223372036854775807
tu
Allocated Memory Size: 8 bytes or 16 bits
Default value: 0.0d
.v
Keyword: double
Example: double d = 3.1428571
w
.in
for goto if implements import
Identifiers
w
Identifiers are the names given for variables, classes, functions, objects, packages,
interfaces in Java program.
w
Literals (Constants)
It is sequence of characters (includes letters, digits, special characters) that
represent constant values to be stored in variable. There are five types of literals,
namely
.in
Integer Literals
Integers are whole numbers do not contain fractional part.
ac
The sign + & - is used to denote positive and negative numbers respectively.
The integer literals are classified into following categories
▪ Decimal Literals (Base 10 Numbers)
tu
It is a combination of digits between 0 to 9.
The sign + and - is used to denote positive and negative numbers
.v
respectively.
Ex: 10, 200, 20000 etc. are valid decimal literals.
w
.in
▪ By default floating point literal is double.
▪ The suffix “D” or “d” is appended to value to designate data type as
double.
▪ Example: double d = 3.1428571d
Character Literals
ac
It is a single 16-bit Unicode character.
tu
Character literals are enclosed in single quotes.
Example: char ch = 'A';
.v
Character Unicode
w
Value
A '\u0041'
w
a '\u0061'
w
0 '\u0030'
String Literals
It is sequence of characters.
String literals should be enclosed in double quotes.
Example: String str = “Hello”;
.in
Separator Name Use
,
Period
Comma ac
Separate packages, access class members
Arrays
w
.in
size → size of the array
Example: int[] array1 = new int[10];
In the above example, array1 holds 10 values.
Array Initialization
ac
Initialization is a method in which array is declared and values are assigned to
array at the same line.
tu
Method 1
Example: int array1[] = {31, 28, 31, 30, 31, 30, 31, 31};
.v
w
.in
Output:
data_type[][] variable_name; OR
data_type [][]variable_name; OR
w
data_type variable_name[][];
Memory allocation to array
w
Where
w
.in
};
for(int i = 0; i<3; i++)
{
ac
for(int j=0; j<3; j++)
{
tu
System.out.print("\t"+array1[i][j]);
}
.v
System.out.println();
}
w
}
}
w
Output:
w
Method 2
Example: int[][] array1 = new int[][]
{ {31, 28, 31},
{30, 31, 30},
{31, 31, 30}
};
.in
System.out.print("\t"+array1[i][j]);
}
}
}
ac
System.out.println();
tu
}
Output:
.v
w
Assigning Values
w
.in
Operators and Expressions
An operator is a symbol that specifies the type of operation to be performed on
variables or values.
an operator tells the direction to evaluate terms i.e. either from left-to-right or
right-to-left. For Example: c=a*b-d/20;
Here * and / are equal priority, so operators are evaluated from left-to-right.
w
Java provides a rich set of operators to manipulate variables. We can divide all the
Java operators into the following groups:
w
Arithmetic Operators
Arithmetic
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc. Operators
.in
Multiplication * 1 L→R
Division / 1 L→R
Remainder
Addition
%
+
ac 1
2
L→R
L→R
tu
Subtraction - 2 L→R
.v
The arithmetic operators can acts on integer and real number. So based on the type
of the operands arithmetic expressions are divided into 3 modes, namely
1. Integer mode arithmetic expression
w
.in
Program 5: To perform arithmetic operations.
public class Addition {
public static void main(String args[]) {
int a = 10;
ac
tu
int b = 20;
int c = 25;
.v
int d = 25;
System.out.println("a + b = " + (a + b) );
w
System.out.println("a - b = " + (a - b) );
System.out.println("a * b = " + (a * b) );
w
System.out.println("b / a = " + (b / a) );
System.out.println("b % a = " + (b % a) );
w
System.out.println("c % a = " + (c % a) );
System.out.println("a++ = " + (a++) );
System.out.println("b-- = " + (a--) );
System.out.println("d++ = " + (d++) );
System.out.println("++d = " + (++d) );
}
}
Output:
.in
Lesser than or equal to <= 1 L→R
Equal to
Not equal to
==
!=
ac 2
2
L→R
L→R
tu
.v
int b = 20;
System.out.println("a == b = " + (a == b) );
w
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
Output:
NOT ~ 1 L→R
.in
Right Shift >> 2 L→R
And
>>>
&
ac 2
3
L→R
L→R
tu
XOR ^ 4 L→R
.v
OR | 5 L→R
The result of bitwise AND is 1, when both bits are 1 otherwise result is 0.
w
.in
variable → int or char data type variable
shift operator → <<
nob → number of bits to be shifted
Example: int a = 64, b;
b = a << 1; Answer?
ac
tu
Right shift operator (>>)
The right shift operator shifts data by a specified number of bit positions
.v
towards right.
The shifted bits are filled by MSB.
w
.in
int c = 0;
c = a & b; /* 12 = 0000 1100 */
c = a | b; ac
System.out.println("a & b = " + c );
/* 61 = 0011 1101 */
System.out.println("a | b = " + c );
tu
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );
.v
A B A&&B A||B !A
.in
Program 8: To perform logical operations.
public class Logical_Operators {
ac
public static void main(String args[]) {
boolean a = true;
tu
boolean b = false;
System.out.println("a && b = " + (a&&b));
.v
}
}
w
Output:
w
Logical Expressions
An expression involving operands which are bind together with suitable
logical operators is called as logical operators.
Example: (a > b && a > c), (a > b || a > c)
Assignment Operator
The operator which is used to assign the data or result of an expression in to
a variable is called assignment operator.
.in
Example: a = 40;
a = b + c;
2. Shorthand assignment operator
ac
It is a compact way of writing expressions in an assignment statement.
Syntax: <variable> <operator>= <expression>;
tu
where
variable → is a valid C identifier.
.v
.in
}
Operators Precedence
Operators
[]
Operation
Array Index
ac Priority Associativity
tu
() Method Call 1 L→R
.v
. Member Access
~ Bitwise Negation
w
++a
--a
+ Unary Plus
3 R→L
- Unary Minus
! Logical NOT
new
* Multiplication
/ Division 4 L→R
% Remainder
Addition or String
+
Concatenation
5 L→R
- Subtraction
.in
>> Right Shift 6 L→R
>>>
<
Unsigned Right Shift
Lesser than ac
tu
<= Lesser than or equal to
== Is equal to
8 L→R
w
!= Not equal to
| Bitwise OR 11 L→R
|| Logical OR 13 L→R
== Assignment
15 R→L
*=, /=, %=, +=, -=, &=,
Short Assignment
^=, |=, <<=, >>=, >>>=
Type Casting
The process of conversion of data type of an operand is called as type
conversion.
For example, if operands in an expression are of different data types, then all
operands must be converted into single data type before evaluating an
.in
expression.
There are two types of type conversion, namely
1. Implicit Conversion (Promotion or Widening)
2. Explicit Conversion (Narrowing)
Implicit Type Conversion
ac
The process of conversion of data from lower rank to higher rank
tu
automatically.
Here, Automatic Type casting takes place when,
.v
{
public static void main(String[] args)
w
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
.in
Program 11: To perform Explicit type conversion.
public class Implicit
{
ac
public static void main(String[] args)
{
tu
double d = 100.04;
long l = (long)d; //explicit type casting required
.v
}
}
w
Control Statements
These statements control the flow of execution of the program based upon
conditions. Java supports two control statements, namely
1. if
2. switch
if statement
It is a conditional statement, which executes or skips set of instructions based upon
result of the evaluated condition.
.in
if( condition )
{
statement1;
}
statement2;
ac
tu
where
if -> is a keyword, must be written in lower case
condition -> logical expression results in either TRUE or FALSE
.v
if( a == 10 )
System.out.println("a equal to 10");
if( b == 20 )
System.out.println("b is equal to 20");
}
}
if-else
It is called as two way selection.
If condition evaluates to true, then statements belongs to if part are executed.
.in
statement 4;
}
Where
ac
if & else -> are keywords, must be written in lower case
condition -> a logical expression evaluates to either TRUE or FALSE
tu
statement 1 & 2 -> may be simple or compound statement, executed when
condition is TRUE
statement 3 & 4 -> may be simple or compound statement, executed when
.v
condition is FALSE
Program 14: To find smallest of two numbers.
w
.in
}
else
{
}
ac
statement2;
tu
}
else
.v
{
statement3;
w
}
Program 15: To find largest of three numbers.
w
.in
{
System.out.println("C is largest among A &
B\n");
}
}
}
ac
tu
}
Output:
.v
w
w
else-if ladder
Checks condition in else part.
w
.in
staement3;
}
else
{
statement4;
ac
tu
}
where
.v
If the result of logical expression given in if is FALSE, control will enters into
else part.
Checks one more conditions given in else if, if the result is TRUE then
executes immediately following simple or compound statements, then comes
out of entire else- if ladder.
If none of the condition is TRUE, then statements in else part will be
executed.
.in
System.out.println("Average\n");
else if(ht>175 && ht <180)
System.out.println("Tall\n");
tu
else
System.out.println("Abnormal\n");
.v
}
}
w
Output:
w
w
Switch statement
It is a conditional statement used to select one case depending upon the value
of expression.
It is also called as multi-way decision or selection.
.in
}
where
ac
switch, case, break, default -> are keywords must be written in lower case
choice/expression -> must be integer or character, we can also give expression
and it should produce valid integer result.
tu
block-> may be simple or compound statements belongs to particular case.
In the above syntax,
.v
If break statement is not used, then subsequent cases will be executed till it
encounters break statement.
After executing the break statement of particular case label, then control
comes out of the switch body.
If the value of the choice or expression do not matches to any of the case
label, then the statements given in default will be executed.
.in
System.out.println("Enter your choice\n");
choice = in.nextInt();
switch(choice)
{
ac
case 1: res = a + b;
tu
System.out.println("Addition of two numbers
is" +res +"\n");
break;
.v
case 2: res = a - b;
System.out.println("Subtraction of two
w
case 3: res = a * b;
System.out.println("Subtraction of two
w
.in
Java's iterative statements are
1. for
2. while
3. do-while
while
ac
tu
It repeatedly executes simple or block statement until condition is true.
Syntax
.v
while( expression )
{
w
statements;
}
w
where
while -> is a keyword must be written in lower case
w
.in
statements;
}while( expression );
where
ac
do & while -> is a keyword must be written in lower case
statements -> may be simple or compound statement
tu
expression -> is a logical expression that results in either TRUE or FALSE
Program 19: To print numbers from 10 to 20 using do-while
.v
int x = 10;
do{
w
System.out.print("value of x : " + x );
x++;
w
System.out.print("\n");
}while( x < 20 );
}
}
for
it is also called as counter-controlled loop / pre-test loop.
It is a conditional control statement, executes a set of statement repeatedly
for known number of times.
where
for -> is a keyword must be written in lower case
exp1 -> initializes the loop index before the loop begins
exp2 -> is a conditional expression that tests whether the loop index reached
the fixed value
exp3 -> modifies the loop index after every iteration or post condition
.in
statements -> may be a simple or a compound statement
Working of for loop
First expression exp1 is evaluated. It is executed at the beginning of the for
ac
loop, exp1 is evaluated only once in the for loop.
Then, exp2 is evaluated to TRUE or FALSE. If the result of exp2 is FALSE,
then control comes out of for loop.
tu
If the result of exp2 is TRUE, then the body of the loop will be executed. After
executing the body of the loop control goes back to the exp3 is evaluated
followed by exp2.
.v
Again exp2 is evaluated to TRUE or FALSE, and loop repeats till result of
exp2 becomes FALSE.
w
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
Output:
.in
int[] array1 = new int[] {5, 6, 7, 8, 9};
for(int x: array1)
{
ac
System.out.println(x);
tu
}
}
}
.v
{4,5,6}
};
/* Printing Array Elements using nested for loop
for(int i = 0; i<2; i++)
for(int j = 0; j<3; j++)
System.out.println(a[i][j]);*/
.in
3. return
Break
It can be used to terminate statements in switch.
It can be used as a form of goto.
Program 23: To use break in for loop.
ac
It can be used to exit from loops like for, while, do-while.
tu
public class Break {
public static void main(String[] args) {
.v
for(int i = 1; ; i++)
{
w
if(i == 11)
break;
w
System.out.println(i);
w
}
}
}
Output:
int i = 1;
while(true)
{
if (i == 11)
break;
System.out.println(i);
i++;
.in
}
}
}
Output:
ac
tu
.v
{
public static void main(String args[])
w
{
int i=10;
w
one:
{
two:
{
System.out.println("Statement before
break");
if(i==10)
{
break two;
.in
Continue
It skips statements in an iteration and continues with the next iteration.
ac
It transfers control to the conditional statement.
Program 26: To print odd numbers from 1 to 10 using continue statement.
public class Continue {
tu
public static void main(String[] args) {
for(int i=1; i<=10; i++)
.v
{
if(i%2 == 0)
w
continue;
System.out.println(i);
w
}
}
w
Return statement
It is used to transfer control from called function to calling function.
It also terminates execution of program.
Program 27: To print numbers from 1 to 10 using return statement.
public class Return {
public static void main(String[] args) {
.in
ac
tu
.v
w
w
w