Computer Network
Computer Network
2. Platform independent
Programs written by user are called source code and executable program is called object code. Object
can be executed by computer and object is specific to a particular CPU. So it cannot be executed on
different platform. Java removes this limitation. When java program is compiled java compiler
produces on object file which contains bytecode. This byte codes are not machine/CPU specific, it can
be interpreted by JVM (Java Virtual Machine).so that code can be run on any JVM of computer
system. The Same byte codes can be executed by any JVM on any platform. Thus java is platform
independent.
3. Portable
Java program can be easily moved from one computer system to another, anywhere and anytime.
Changes /upgrade in OS .processors and system resources will not force any changes in java program.
We can also download applet from a remote computer onto our local system via internet and execute
it locally.
Java provides Write Once Run Anywhere (WORA), which makes the java language portable provided
that the system must have interpreter for the JVM . Java also has the standard data size irrespective of
operating system or the processor .These features make the java as a portable language.
4. Object oriented
Almost everything in java is an object. All program code and data reside within object and classes.
Object model in java is simple and easy to extend. Java comes with extensive set of classes, arranged
in packages that we can use in our program by inheritance. Java is true (pure) object oriented
language because object is the outer most level of data structure in java. Everything in java is object
even the primitive data types can also be converted into object by using the wrapper class.
6. Distributed
Java is designed as distributed language for creating applications on networks. Java applications can
open and access remote objects on internet .These multiple programmers at multiple remote locations
to collaborate and work together on a single project.
7. Simple
Java is small and simple. Many features of C and C++ those are redundant or sources of unreliable
code are not part of java. It doesn’t support pointer, pre-processor , header files, goto statement and
other It eliminates operator overloads, multiple inheritance, thus java is simplified version of C++. It
includes automatic storage management, typically using a garbage collector, to avoid safety problems
of explicit de-allocation of memory references.
9. High performance
High performance ,by intermediate byte code Multithreading enhances the overall execution speed of
java program
2. Java components: Java Virtual Machine (JVM), Java Runtime Environment (JRE),
JDK (Java Development Kit). Importance of byte code and Garbage Collection
2.1 Java Virtual Machine (JVM)
All language compilers translates source code into machine code for a specific computer. Java is
platform independent or machine neutral!!! Java compiler produces an intermediate code (byte code or
virtual machine code ) for a machine that does not exist. that machine is Java Virtual Machine(JVM).
JVM exists only inside the computer memory. JVM is a simulated computer within the computer and
does all major functions of real computer.
JIT (JUST IN TIME COMPILER) JVM includes optional JIT. JIT dynamically compiles byte code into
executable code. It takes byte code ,compiles them into machine code(native code) for machine. It
compiles program on a method by method basis just before they are called. JIT is faster than JVM.
2.2 JRE (JAVA RUNTIME ENVIRONMENT)
JRE consists of JVM and the program on the other . It runs code compiled for JVM by:
1. Loading the .class files
2. Verifying byte code
3. Executing the code
It is a collection of tools that are used for developing and running java program. JDK includes applet
viewer (for viewing java applets)
1. javac (java compiler)
2. java (java interpreter)
3. javap (java disassembler)
4. javah (for C header files)
5. javadoc (for creating HTML documents)
6. jdb (java debugger)
The Java Development Kit (JDK) is one of three core technology packages used in Java programming,
along with the JVM (Java Virtual Machine) and the JRE (Java Runtime Environment). It's important to
differentiate between these three technologies and understand how they're connected:
The JVM is the runtime that hosts running programs.
The JRE is the on-disk part of Java that creates the JVM and loads programs into them.
The JDK provides the tools necessary to write Java programs that can be executed and run by the JVM
and JRE.
Garbage Collection:
Garbage collection in Java is the process by which Java programs perform automatic memory
management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for
short. When Java programs run on the JVM, objects are created on the heap, which is a portion of
memory dedicated to the program. Eventually, some objects will no longer be needed. The garbage
collector finds these unused objects and deletes them to free up memory.
2. It makes java memory-efficient because the garbage collector removes the unreferenced objects
from heap memory.
3. It is automatically done by the garbage collector(a part of JVM), so we don’t need extra effort.
We recommend that only the latest JDK be installed. Although it is possible to install multiple versions
of JDK / JRE simultaneously, it is messy.
If you have an older version(s) of JDK/JRE in your system, uninstall ALL of them. Go to control panel
and uninstall java.
Visit https://www.oracle.com/java/technologies/javase-downloads.html
Click on download button for JDK version you want to install. Ex. JDK 11.
Click on the checkbox to "Accept License Agreement".
Choose the JDK for your operating system, i.e., "Windows". Download the ".exe" installer.
Execute the downloaded installer which will install both the JDK and JRE.
In the "C:\Program Files\Java\jdk-11.0.{v }" directory, where {v} denotes the update number, JDK is
installed by default. Accept the defaults and follow the JDK installation instructions on the screen.
Open command prompt and type java -version. If you get the version info, Java is installed correctly and
PATH is also set correctly.
Go to start menu-->System-->Advanced-->Environment Variables. Check if both PATH and
JAVA_HOME are set correctly.
Import Statements:
The package contains the many predefined classes and interfaces. If we want to use any class of a
particular package, we need to import that class. The import statement represents the class stored in the
other package. We use the import keyword to import the class. It is written before the class declaration
and after the package statement. We use the import statement in two ways, either import a specific class
or import all classes of a particular package. In a Java program, we can use multiple import statements
Interface Section:
It is an optional section. We can create an interface in this section if required. We use
the interface keyword to create an interface. An interface is a slightly different from the class. It contains
only constants and method declarations. Another difference is that it cannot be instantiated. We can use
interface in classes by using the implements keyword. An interface can also be used with other
interfaces by using the extends keyword.
Class Definition:
In this section, we define the class. It is vital part of a Java program. Without the class, we cannot create
any Java program. A Java program may conation more than one class definition. We use
the class keyword to define the class. The class is a blueprint of a Java program. It contains information
about user-defined methods, variables, and constants. Every Java program has at least one class that
contains the main() method.
Main Method Class:
In this section, we define the main() method. It is essential for all Java programs. Because the execution
of all Java programs starts from the main() method. In other words, it is an entry point of the class. It
must be inside the class. Inside the main method, we create objects and call the methods. We use the
following statement to define the main() method:
For example:
public class Student //class definition
{
public static void main(String args[])
{
//statements
}
}
Comment Syntax:
we use comments. The comments may be single-line, multi-line, and documentation comments.
1. Single-line Comment: It starts with a pair of forwarding slash (//). For example:
//First Java Program
2. Multi-line Comment: It starts with a /* and ends with */. We write between these two symbols. For
example:
/*It is an example of
3. multiline comment*/
Documentation Comment: It starts with the delimiter (/**) and ends with */. For example:
/**It is an example of documentation comment*/
4. Primitive Data Types : byte, short, int, long, float, double, char, Boolean
A primitive data type specifies the size and type of variable values, and it has no additional methods.
There are eight primitive data types in Java:
1.byte type
The byte data type can have values from -128 to 127 (8-bit signed two's complement integer).
If it's certain that the value of a variable will be within -128 to 127, then it is used instead of int to save
memory.
Default value: 0
2. short type
The short data type in Java can have values from -32768 to 32767 (16-bit signed two's complement
integer).
If it's certain that the value of a variable will be within -32768 and 32767, then it is used instead of other
integer data types (int, long).
Default value: 0
3. int type
The int data type can have values from -231 to 231-1 (32-bit signed two's complement integer).
If you are using Java 8 or later, you can use an unsigned 32-bit integer. This will have a minimum value
of 0 and a maximum value of 232-1. To learn more, visit How to use the unsigned integer in java 8?
Default value: 0
4. long type
The long data type can have values from -263 to 263-1 (64-bit signed two's complement integer).
If you are using Java 8 or later, you can use an unsigned 64-bit integer with a minimum value of 0 and a
maximum value of 264-1.
Default value: 0
5. double type
6. float type
The float data type is a single-precision 32-bit floating-point. Learn more about single-precision and
double-precision floating-point if you are interested.
It should never be used for precise values such as currency.
Default value: 0.0 (0.0f)
7. boolean type
The boolean data type has two possible values, either true or false.
Default value: false.
They are usually used for true/false conditions.
8. char type
The char data type use to store character & string value.
Default value: null
5. Identifiers, Declarations of constants & variables, Type Conversion and Type Casting,
Scope of variables
Identifiers:
Identifiers in Java are symbolic names used for identification. They can be a class name, variable name,
method name, package name, constant name, and more. However, In Java, There are some reserved
words that can not be used as an identifier.
Following are some rules and conventions for declaring identifiers:
A valid identifier must have characters [A-Z] or [a-z] or numbers [0-9], and underscore(_) or a dollar
sign ($). for example, @javatpoint is not a valid identifier because it contains a special character which
is @.
There should not be any space in an identifier. For example, java tpoint is an invalid identifier.
An identifier should not contain a number at the starting. For example, 123javatpoint is an invalid
identifier.
An identifier should be of length 4-15 letters only. However, there is no limit on its length. But, it is
good to follow the standard conventions.
We can't use the Java reserved keywords as an identifier such as int, float, double, char, etc. For
example, int double is an invalid identifier in Java.
An identifier should not be any query language keywords such as SELECT, FROM, COUNT, DELETE,
etc.
Following are some examples of valid identifiers in Java:
TestVariable
testvariable
a
i
Test_Variable
_testvariable
$testvariable
sum_of_array
TESTVARIABLE
jtp123
Declarations of constants
Constants in Java are used when a ‘static‘ value or a permanent value for a variable has to be
implemented. Java doesn’t directly support constants. To make any variable a constant, we must use
‘static’ and ‘final’ modifiers in the following manner:
Syntax to assign a constant value in java:
static final datatype identifier_name = constant;
The static modifier causes the variable to be available without an instance of it’s defining class being
loaded
The final modifier makes the variable unchangeable
Example : static final int MIN_AGE = 18;
Variables:
A variable is a location in memory (storage area) to hold data.
To indicate the storage area, each variable should be given a unique name (identifier). Learn more
about Java identifiers.
1. Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size type:
Example:
public class Test
{
public static void main(String[] args)
{
int m = 9;
double d = m; // Automatic casting: int to double
System.out.println(m); // Outputs 9
System.out.println(d); // Outputs 9.0
}
}
2. Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses in front of the value:
Example
public class Test
{
public static void main(String[] args)
{
double d = 9.78d;
int m = (int) d; // Manual casting: double to int
Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for
each value.
Type of Array
1. One Dimensional Array
2. MultiDimensional Array
System.out.println(cars[0]);
// Outputs Volvo
Array Length
To find out how many elements an array has, use the length property:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
2. Multidimensional Arrays
A multidimensional array is an array of arrays.
Multidimensional arrays are useful when you want to store data as a tabular form, like a table with rows
and columns.
To create a two-dimensional array, add each array within its own set of curly braces:
Example:
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers is now an array with two arrays as its elements.
Access Elements
To access the elements of the myNumbers array, specify two indexes: one for the array, and one for the
element inside that array. This example accesses the third element (2) in the second array (1) of
myNumbers:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
System.out.println(myNumbers[1][2]);
+ Addition
- Subtraction
* Multiplication
/ Division
= a = b; a = b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;
~ Bitwise Complement
^ Bitwise exclusive OR
8. Decision & Control Statements: Selection Statement (if, if...else, switch), Loops (while,
do-while, for), Jump
1. The if Statement
Use the if statement to specify a block of Java code to be executed if a condition is true.
Syntax:
if (condition) {
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
Example below, we test two values to find out if 20 is greater than 18. If the condition is true, print some
text:
Use the else statement to specify a block of code to be executed if the condition is false.
Syntax
if (condition)
{
// block of code to be executed if the condition is true
}
else
Prepared By: VPMP POLYTECHNIC, Department of Computer Engineering Page 18
Subject Name: Advanced Object Oriented Programming Unit No: 1 Subject Code: 4340701
{
// block of code to be executed if the condition is false
}
Example
int time = 20;
if (time < 18)
{
System.out.println("Good day.");
}
else
{
System.out.println("Good evening.");
}
Use the else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1)
{
// block of code to be executed if condition1 is true
}
else if (condition2)
{
// block of code to be executed if the condition1 is false and condition2 is true
}
else
{
// block of code to be executed if the condition1 is false and condition2 is false
}
Example
int time = 22;
if (time < 10)
{
System.out.println("Good morning.");
}
else if (time < 18)
{
System.out.println("Good day.");
}
else
{
System.out.println("Good evening.");
}
Instead of writing many if..else statements, you can use the switch statement.
The switch statement selects one of many code blocks to be executed:
Syntax
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
The break and default keywords are optional, and will be described later in this chapter
The example below uses the weekday number to calculate the weekday name:
Example
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
Loops
1.While Loop
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code more readable.
The while loop loops through a block of code as long as a specified condition is true:
Syntax
while (condition)
{
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less
than 5:
Example
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Statement 3 is executed (every time) after the code block has been executed.
The example below will print the numbers 0 to 4:
Example
for (int i = 0; i < 5; i++)
{
System.out.println(i);
}
Jump Statement
1. Java Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to
"jump out" of a switch statement.
The break statement can also be used to jump out of a loop.
This example stops the loop when i is equal to 4:
Example
for (int i = 0; i < 10; i++) {
if (i == 4)
{
break;
}
System.out.println(i);
}
2. Java Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues
with the next iteration in the loop.
This example skips the value of 4:
Example
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
continue;
}
System.out.println(i);
}