Introduction To Java Programming
Introduction To Java Programming
Platform independence - Many languages are compatible with only one platform. Java was
specifically designed so that it would run on any computer, regardless if it was running Windows,
Linux, Mac, Unix or any of the other operating systems.
Simple and easy to use - Java's creators tried to design it so code could be written
efficiently and easily.
Multi-functional - Java can produce many applications from command-line programs to
applets to Swing windows (basically, sophisticated graphical user interfaces).
Java does have some drawbacks. Since it has automated garbage collection, it can tend to use
more memory than other similar languages. There are often implementation differences on different
platforms, which have led to Java being described as a "write once, test everywhere" system
1).Path is an environment variable which is used by the operating system to find the
executables.
Classpath is an environment variable which is used by the Java compiler to find the
path, of classes.ie in J2EE we give the path of jar files.
2).PATH is nothing but setting up an environment for operating system. Operating
System will look in this PATH for executables.
Classpath is nothing but setting up the environment for Java. Java will use to find
compiled classes
3).Path refers to the system while classpath refers to the Developing Envornment.
PATH
Once you installed Java on your machine, it is required to Set the PATH environment
variable to conveniently run the executable (javac.exe, java.exe, javadoc.exe, and so
on) from any directory without having to type the full path of the command, such as:
C:\javac TestClass.java
Otherwise, you need to specify the full path every time you run it, such as:
C:\Java\jdk1.7.0\bin\javac TestClass.java
CLASSPATH
Classpath is system environment variable used by the Java compiler and JVM.
Java compiler and JVM is used Classpath to determine the location of required class
files.
C:\Program Files\Java\jdk1.6.0\bin
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism
Simple
Java is considered as one of simple language because it does not have complex
features like Operator overloading, Multiple inheritance, pointers and Explicit
memory allocation.
Robust Language
Robust means reliable. Java programming language is developed in a way that
puts a lot of emphasis on early checking for possible errors, that’s why java
compiler is able to detect errors that are not easy to detect in other programming
languages. The main features of java that makes it robust are garbage collection,
Exception Handling and memory allocation.
Secure
We don’t have pointers and we cannot access out of bound arrays (you get
ArrayIndexOutOfBoundsException if you try to do so) in java. That’s why several
security flaws like stack corruption or buffer overflow is impossible to exploit in
Java.
Java is distributed
Using java programming language we can create distributed applications.
RMI(Remote Method Invocation) and EJB(Enterprise Java Beans) are used for
creating distributed applications in java. In simple words: The java programs can
be distributed on more than one systems that are connected to each other using
internet connection. Objects on one JVM (java virtual machine) can execute
procedures on a remote JVM.
Multithreading
Java supports multithreading. Multithreading is a Java feature that allows
concurrent execution of two or more parts of a program for maximum utilization
of CPU.
Portable
As discussed above, 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.
When we write a program in Java, firstly, the compiler compiles that program and a
bytecode is generated for that piece of code. When we wish to run this .class file on
any other platform, we can do so. After the first compilation, the byte code
generated is now run by the Java Virtual Machine and not the processor in
consideration. This essentially means that we only need to have basic java
installation on any platforms that we want to run our code on. Resources required
to run the bytecode are made available by theJava Virtual Machine, which calls the
processor to allocate the required resources. JVM's are stack-based so they stack
implementation to read the codes.
Advantage of Java Bytecode
Platform independence is one of the soul reasons for which James Gosling started
the formation of java and it is this implementation of bytecode which helps us to
achieve this. Hence bytecode is a very important component of any java
program.The set of instructions for the JVM may differ from system to system but
all can interpret the bytecode. A point to keep in mind is that bytecodes are non-
runnable codes and rely on the availability of an interpreter to execute and thus the
JVM comes into play.
JVM Architecture
Method Area: There is only one method area in a JVM which is shared among all the classes. This holds the class
level information of each .class file.
Heap: Heap is a part of JVM memory where objects are allocated. JVM creates a Class object for each .class file.
Stack: Stack is a also a part of JVM memory but unlike Heap, it is used for storing temporary variables.
PC Registers: This keeps the track of which instruction has been executed and which one is going to be executed.
Since instructions are executed by threads, each thread has a separate PC register.
Native Method stack: A native method can access the runtime data areas of the virtual machine.
Native Method interface: It enables java code to call or be called by native applications. Native applications are
programs that are specific to the hardware and OS of a system.
Garbage collection: A class instance is explicitly created by the java code and after use it is automatically destroyed
by garbage collection for memory management.
JVM Vs JRE Vs JDK
JRE: JRE is the environment within which the java virtual machine runs. JRE
contains Java virtual Machine(JVM), class libraries, and other files excluding
development tools such as compiler and debugger.
Which means you can run the code in JRE but you can’t develop and compile the
code in JRE.
JVM: As we discussed above, JVM runs the program by using class, libraries
and files provided by JRE.
JDK: JDK is a superset of JRE, it contains everything that JRE has along with development tools such as compiler,
debugger etc.
JDK vs JRE vs JVM
Let’s look at some of the important difference between JDK, JRE, and JVM.
1. JDK is for development purpose whereas JRE is for running the java
programs.
2. JDK and JRE both contains JVM so that we can run our java program.
3. JVM is the heart of java programming language and provides platform
independence.
Disadvantages
1- Performance
Java programs take much longer time to run compared to C/C++.
2- Memory
Since Java Programs run on top of Java Virtual Machine, it consumes more
memory.
3- Cost
Since memory and processing requirements higher, hardware cost increases.
4. Low level programming
There is no support for low level programming in Java, like pointers are missing.
5- Garbage collection
There is no control over garbage collection in Java. That is programmer does not
have any right to control the garbage collection. Java does not provide functions like
delete(), free().
1. Variable Declaration
2. Variable Initialization
Variable Declaration:
To declare a variable, you must specify the data type & give the variable a unique name.
int a,b,c;
float pi;
double d;
char a;
Variable Initialization:
To initialize a variable, you must assign it a valid value.
Types of variables
In Java, there are three types of variables:
1. Local Variables
2. Instance Variables
3. Static Variables
1) Local Variables
Local Variables are a variable that are declared inside the body of a method.
2) Instance Variables
Instance variables are defined without the STATIC keyword .They are defined Outside a method declaration. They
are Object specific and are known as instance variables.
3) Static Variables
Static variables are initialized only once, at the start of the program execution. These variables should be initialized
first, before the initialization of any instance variables.
Data Types in Java (Data type defines the values that a variable can take)
Data types classify the different values to be stored in the variable. In java, there are two types of data types:
Primitive Data Types are predefined and available within the Java language. Primitive values do not share state with
other primitive values.
There are 8 primitive types: byte, short, int, long, char, float, double, and boolean Integer data types
Java Data Types
Byte 0 1 byte
Short 0 2 bytes
Int 0 4 bytes
Long 0L 8 bytes
har data type in Java is 2 bytes because it uses UNICODE character set. UNICODE is a character set which covers
all known scripts and language in the world
class JavaExample {
public static void main(String[] args) {
byte num;
num = 113;
System.out.println(num);
}
}
Output:
113
short:
This is greater than byte in terms of size and less than integer. Its range is -32,768 to 32767.
Default size of this data type: 2 byte
Try the same program by assigning value assigning 150 value to variable num, you would get type mismatch error because
the value 150 is out of the range of byte data type. The range of byte as I mentioned above is -128 to 127.
class JavaExample {
public static void main(String[] args) {
short num;
num = 150;
System.out.println(num);
}
}
Output:
150
long:
Used when int is not large enough to hold the value, it has wider range than int data type, ranging from
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
class JavaExample {
public static void main(String[] args) {
-12332252626
class JavaExample {
public static void main(String[] args) {
char ch = 'Z';
System.out.println(ch);
}
}
Output:
Z
boolean: holds either true of false.
class JavaExample {
public static void main(String[] args) {
boolean b = false;
System.out.println(b);
}
}
Output:
false
class JavaExample {
public static void main(String[] args) {
19.98
Strings: String is a sequence of characters. But in Java, a string is an object that represents a sequence of characters.
The java.lang.String class is used to create a string object.
Arrays: Arrays in Java are homogeneous data structures implemented in Java as objects. Arrays store one or more values of a
specific data type and provide indexed access to store the same. A specific element in an array is accessed by its index.
Identifiers in Java
All Java components require names. Name used for classes, methods, interfaces and variables are called Identifier. Identifier must
follow some rules. Here are the rules:
All identifiers must start with either a letter( a to z or A to Z ) or currency character($) or an underscore.
After the first character, an identifier can have any combination of characters.
Java keywords cannot be used as an identifier.
Identifiers in Java are case sensitive, foo and Foo are two different identifiers.
Some valid identifiers are: int a, class Car, float amount etc. ////////////int char; invalid identifier
Or
int score;
Here, score is a variable (an identifier). You cannot use keywords as variable names. It's because keywords have
predefined meanings. For example,
int float;
The above code is wrong. It's because float is a keyword and cannot be used as a variable name.
score
level
highestScore
number1
convertToString
class
float
1number
Highest Score
@pple
Other Rules
Whitespaces are not allowed------Similarly, you cannot use symbols such as @ , # , and
so on------It can have a sequence of letters and digits. However, it must begin
with a letter, $ or _ . The first letter of an identifier cannot be a digit.
Constants in java
A constant is a variable whose value cannot change once it has been assigned. Java doesn't
have built-in support for constants.
A constant can make our program more easily read and understood by others. In addition, a
constant is cached by the JVM as well as our application, so using a constant can improve
performance.
A constant variable is the one whose value is fixed and only one copy of it exists in the program.
Once you declare a constant variable and assign value to it, you cannot change its value again
throughout the program.
You can create a constant in c language using the constant keyword (one way to create it) as
const int a=100;
Unlike in C language constants are not supported in Java(directly). But, you can still create a constant by
declaring a variable static and final.
Static − Once you declare a variable static they will be loaded in to the memory at the compile time i.e.
only one copy of them is available and The static modifier causes the variable to be available without an
instance of it’s defining class being loaded.
The static modifier is mainly used for memory management
It also allows the variable to be available without loading any instance of the class in which it is defined.
Final − once you declare a variable final you cannot modify its value again. The final modifier means that
the value of a variable cannot change. Once the value is assigned to a variable, a different value cannot
be reassigned to the same variable.
Therefore, you can create a constant in Java by declaring the instance variable static and final.
To make any variable a constant, we must use ‘static’ and ‘final’ modifiers.
Why constants?
Constants make your program more easy to read and understand when read by others.
Using a constant also improves performance, as constants are cached by both the JVM and your
application.
Operator and Expression
An operator is a character that represents an action, for example + is an arithmetic operator that
represents addition,
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into
the following groups −
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Binary OR Operator
(A | B) will give 61
| (bitwise or) copies a bit if it exists in
which is 0011 1101
either operand.
Called Logical OR
Operator. If any of the
|| (logical or) two operands are non- (A || B) is true
zero, then the condition
becomes true.
C <<= 2
is same
<<= Left shift AND assignment operator.
as C = C
<< 2
C >>= 2
is same
>>= Right shift AND assignment operator.
as C = C
>> 2
C &= 2 is
&= Bitwise AND assignment operator. same as
C=C&2
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three operands
and is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should
be assigned to the variable. The operator is written as −
Variable x = (expression) ? value if true : value if false
Category Operator
Postfix expression++ expression--
Multiplicative */%
Additive +-
Equality == !=
Bitwise XOR ^
Bitwise OR |
Logical OR ||
Conditional ?:
Types of Expressions
While an expression frequently produces a result, it doesn't always. There are three
types of expressions in Java:
(1 + 1)
(v = 10)
Java Statements
In Java, each statement is a complete unit of execution. For example,
int score =10*2;
Means that you can construct statements using expression but not vice a versa.
Type Casting (Type conversion )
The process of converting the value of one data type( int, float, double etc. ) in to another data type
is known as typecasting. It has two types as follow
Example:
class tc {
public static void main(String[] args) {
int num = 10;
System.out.println("The integer data type value is: " + num);
Output
The double data type value, after automatic conversion is: 10.0
In the above example, we are assigning the int type variable named num to a double type variable
named data .
Here, the Java first converts the int type data into the double type. And then assign it to
the double variable.
Example:
class tc2 {
public static void main(String[] args) {
double num = 10.99;
System.out.println("The double value: " + num);
Output
Data will be lost and the integer value, after conversion is: 10
In the above example, we are assigning the double type variable named num to an int type variable
named data .
Notice the line
Here, the int keyword inside the parenthesis indicates that that the num variable is converted into
the int type.
Control Flow
Packages
A package in Java is used to group related classes. Think of it as a folder in a file
directory. We use packages to avoid name conflicts, and to write a better
maintainable code. Packages are divided into two categories:
Syntax
Import a Class
If you find a class you want to use, for example, the Scanner class, which is used to get user
input, write the following code:
Example
import java.util.Scanner;
To use the Scanner class, create an object of the class and use any of the available methods found in
the Scanner class documentation. In our example, we will use the nextLine() method, which is used
to read a complete line:
Example
import java.util.Scanner;
class MyClass {
System.out.println("Enter username");
Import a Package
There are many packages to choose from. In the previous example, we used
the Scanner class from the java.util package. This package also contains date and time
facilities, random-number generator and other utility classes.
To import a whole package, end the sentence with an asterisk sign (*). The following
example will import ALL the classes in the java.util package:
Example
import java.util.*;
java.lang -
It Provides classes that are fundamental to the design of the Java programming
language such as String, Math, and basic runtime support for processes.
java.util -
It Provides the collections framework, formatted printing and scanning, array
manipulation utilities, event model, date and time facilities, internationalization, and
miscellaneous utility classes.
Java.lang is the default Package for the Java Program All the Classes available in
java.lang package will be available without importing the package. Whereas java.util is
not the default Package in order the use the java.util package i.e (Collection Framework)
you must have to import it to the current Program i.e import java.util.*
1.java.lang.Object
2.java.lang.String
5.java.lang.Byte
6.java.lang.Short
7.java.lang.Integer
8.java.lang.Long
9.java.lang.Boolean
10.java.lang.Double
11.java.lang.Character
12.java.lang.Runtime
13.java.lang.System
15.java.lang.Math
16.java.lang.Exception
1.java.util.Collection (interface)
2.java.util.List(Interface)
3.java.util.Set(interface)
4.java.util.ArrayList
5.java.util.Vector
6.java.util.LinkedList
Java.util.*;
Unlike some of the StrictMath class numeric methods, all implementations of the equivalent function of
Math class can't define to return the bit-for-bit same results. This relaxation permits implementation
with better-performance where strict reproducibility is not required.
For other arithmetic operations like increment, decrement, divide, absolute value, and negation
overflow occur only with a specific minimum or maximum value. It should be checked against the
maximum and minimum value as appropriate.
Example
public class JavaMathExample1
{
public static void main(String[] args)
{
double x = 28;
double y = 4;
// return the maximum of two numbers
System.out.println("Maximum number of x and y is: " +Math.max(x, y));
// return the square root of y
System.out.println("Square root of y is: " + Math.sqrt(y));
//returns 28 power of 4 i.e. 28*28*28*28
System.out.println("Power of x and y is: " + Math.pow(x, y));
// return the logarithm of given value
System.out.println("Logarithm of x is: " + Math.log(x));
System.out.println("Logarithm of y is: " + Math.log(y));
// return the logarithm of given value when base is 10
System.out.println("log10 of x is: " + Math.log10(x));
System.out.println("log10 of y is: " + Math.log10(y));
// return the log of x + 1
System.out.println("log1p of x is: " +Math.log1p(x));
// return a power of 2
System.out.println("exp of a is: " +Math.exp(x));
// return (a power of 2)-1
System.out.println("expm1 of a is: " +Math.expm1(x));
}
}
Output:
Math.pow() It returns the value of first argument raised to the power to second argument.
Math.random() It returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
Package java.text
Provides classes for handling text, dates, numbers, and messages in a manner independent of
natural languages.
Every locale has four default formats for formatting and parsing dates. They are called SHORT, MEDIUM, LONG,
and FULL. The SHORT format consists entirely of numbers while the FULL format contains most of the date
components. There is also a default format called DEFAULT and is the same as MEDIUM.
If the example is run in a different locale, the output will not be the same:
import java.text.DateFormat;
import java.util.*;
// Format
Date date = new Date();
String s = DateFormat.getDateInstance(DateFormat.SHORT).format(date);
s = DateFormat.getDateInstance(DateFormat.MEDIUM).format(date);
s = DateFormat.getDateInstance(DateFormat.LONG).format(date);
s = DateFormat.getDateInstance(DateFormat.FULL).format(date);
s = DateFormat.getDateInstance().format(date);
s = DateFormat.getDateInstance(DateFormat.DEFAULT).format(date);
}
Java I/O(i.o package)
The package java.io contains the classes that handle fundamental input and output
operations in Java. The I/O classes can be grouped as follows:
Java test
dir abc.txt
jnucs
To create a directory
class testdd
int count=0;
File f= new File("F:\\COVID Notes\\PIJ");
String[] s = f.list();
for(String s1 : s)
count++;
System.out.println(s1);
class testdd
int count=0;
String[] s = f.list();
for(String s1 : s)
count++;
System.out.println(s1);
class testdd
int count=0;
String[] s = f.list();
for(String s1 : s)
if(s1.isDirectory())
{
count++;
System.out.println(s1);