Lecture 1
Lecture 1
Lecture 1
Introduction to JAVA
1) Standalone Application
Standalone applications are also known as desktop applications or window-based applications. These are
traditional software that we need to install on every machine. Examples of standalone application are Media
player, antivirus, etc. AWT and Swing are used in Java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates a dynamic page is called a web application.
Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web
applications in Java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called enterprise
application. It has advantages of the high-level security, load balancing, and clustering. In Java, EJB is used
for creating enterprise applications.
4) Mobile Application
An application which is created for mobile devices is called a mobile application. Currently, Android and Java
ME are used for creating mobile applications.
Java is an Object Oriented
language
Object oriented programming is a way of organizing programs as
collection of objects, each of which represents an instance of a class.
4 main concepts of Object Oriented programming are:
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism
Object-Oriented Programming is a
methodology or paradigm to design a program
using classes and objects.
Object means a real-world entity such as a pen, chair, table,
computer, watch, etc. An Object can be defined as an instance of a
class. An object contains an address and takes up some space in
memory. Objects can communicate without knowing the details of
each other's data or code.
Class: Collection of objects is called class. It is a logical entity. A class can also be defined as a
blueprint from which you can create an individual object. Class doesn't consume any space.
Inheritance: When one object acquires all the properties and behaviors of a parent object, it
is known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
Polymorphism: If one task is performed in different ways, it is known as polymorphism. For
example: to convince the customer differently, to draw something, for example, shape,
triangle, rectangle, etc.
In Java, we use method overloading and method overriding to achieve polymorphism.
Abstraction: Hiding internal details and showing functionality is known as abstraction. For
example phone call, we don't know the internal processing. In Java, we use abstract class and
interface to achieve abstraction.
Encapsulation: Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines. A java class is
the example of encapsulation. Java bean is the fully encapsulated class because all the data
members are private here.
What is the difference between an object-
oriented programming language and
object-based programming language?
Mainly used for C++ is mainly used for system Java is mainly used for application programming. It is widely used in window,
programming. web-based, enterprise and mobile applications.
Design Goal C++ was designed for systems and Java was designed and created as an interpreter for printing systems but
applications programming. It was an later extended as a support network computing. It was designed with a goal
extension of of being easy to use and accessible to a broader audience.
C programming language.
Goto C++ supports the goto statement. Java doesn't support the goto statement.
Multiple inheritance C++ supports multiple inheritance. Java doesn't support multiple inheritance through class. It can be achieved
by interfaces in java.
Operator Overloading C++ supports operator overloading. Java doesn't support operator overloading.
Pointers C++ supports pointers. You can Java supports pointer internally. However, you can't write the pointer
write pointer program in C++. program in java. It means java has restricted pointer support in java.
Compiler and Interpreter C++ uses compiler only. C++ is Java uses compiler and interpreter both. Java source code is converted into
compiled and run using the compiler bytecode at compilation time. The interpreter executes this bytecode at
which converts source code into runtime and produces output. Java is interpreted that is why it is platform
machine code so, C++ is platform independent.
dependent.
Call by Value and Call by C++ supports both call by value and call by Java supports call by value only. There is no call
reference reference. by reference in java.
Structure and Union C++ supports structures and unions. Java doesn't support structures and unions.
Thread Support C++ doesn't have built-in support for threads. It Java has built-in thread support.
relies on third-party libraries for thread support.
Documentation comment C++ doesn't support documentation comment. Java supports documentation comment (/** ...
*/) to create documentation for java source
code.
Virtual Keyword C++ supports virtual keyword so that we can decide Java has no virtual keyword. We can override
whether or not override a function. all non-static methods by default. In other
words, non-static methods are virtual by
default.
unsigned right shift >>> C++ doesn't support >>> operator. Java supports unsigned right shift >>>
operator that fills zero at the top for the
negative numbers. For positive numbers, it
works same like >> operator.
Inheritance Tree C++ creates a new inheritance tree always. Java uses a single inheritance tree always
because all classes are the child of Object class
in java. The object class is the root of the
inheritance tree in java.
About Java programs, it is very important to keep in mind the following points.
Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would
have different meaning in Java.
Class Names − For all class names the first letter should be in Upper Case. If several
words are used to form a name of the class, each inner word's first letter should be in
Upper Case. Example: class MyFirstJavaClass
Method Names − All method names should start with a Lower Case letter. If several
words are used to form the name of the method, then each inner word's first letter should
be in Upper Case. Example: public void myMethodName()
Program File Name − Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case
sensitive) and append '.java' to the end of the name (if the file name and the class name
do not match, your program will not compile).
But please make a note that in case you do not have a public class present in the file then file name
can be different than class name. It is also not mandatory to have a public class in the file.
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved
as 'MyFirstJavaProgram.java'
public static void main(String args[]) − Java program processing starts from the
Java Identifiers
All Java components require names. Names used for classes, variables, and
methods are called identifiers.
In Java, there are several points to remember about identifiers. They are as
follows −
All identifiers should begin with a letter (A to Z or a to z), currency
character ($) or an underscore (_).
After the first character, identifiers can have any combination of characters.
A key word cannot be used as an identifier.
Most importantly, identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of illegal identifiers: 123abc, -salary.
Java Modifiers
volatile while
File compilation and execution
Step 2: Compile the source code using java compiler, which will
create bytecode file with .class extension
Step 3: Class loader reads both the user defined and library classes
into the memory for execution
Step 4: Bytecode verifier validates all the bytecodes are valid and
do not violate java’s security restrictions.
Step 5: JVM reads bytecodes and translates into machine code for
execution. While execution of the program the code will interact to
the operating system and hardware.
5 phases of java programs
Edit
Compile
Loading
Verify
Execute
JVM Architecture
How JVM Works
Class Loader: The class loader reads the .class file and save the byte code in the method
area.
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
Comments in Java
Java supports single-line and multi-line comments very similar to C and C++. All characters
available inside any comment are ignored by Java compiler.
Example
public class MyFirstJavaProgram {
/* This is my first java program.
* This will print 'Hello World' as the output
* This is an example of multi-line comments.
*/
public static void main(String []args) {
// This is an example of single line comment
/* This is also an example of single line comment. */
System.out.println("Hello World"); } }
Output
Hello World
JAVA Datatypes
There are two data types available in Java −
Primitive Data Types
Reference/Object Data Types
Primitive Data Types
Java variables
There are three kinds of variables in Java −
Local variables: Local variables are declared in methods, constructors, or
blocks. Local variables are created when the method, constructor or block is
entered and the variable will be destroyed once it exits the method,
constructor, or block.
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
}
}
Output: 22
21
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);
System.out.println(~b);
System.out.println(!c);
System.out.println(!d);
}}
class OperatorExample{
public static void main(String args[]){
System.out.println(10*10/5+3-1*4/2);
}}
Output: 21
Type Casting in Java
Type casting is used to convert an object or variable of one type into
another.
Syntax: dataType variableName = (dataType)
variableToConvert;
There are two casting directions: narrowing (larger to smaller type)
and widening (smaller to larger type). Widening can be done
automatically (for example, int to double), but narrowing must be
done explicitly (like double to int).
Widening or Automatic Type Conversion: Widening conversion
takes place when two data types are automatically converted. This
happens when:
1. The two data types are compatible.
2. When we assign value of a smaller data type to a
bigger data type.
Example:
class Test
{
public static void main(String[] args)
{
int i = 100;
//automatic type conversion
long l = i;
//automatic type conversion
float f = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f); } }
Output: Int value 100
Long value 100
Float value 100.0
Narrowing or Explicit Conversion
If we want to assign a value of larger data type to a smaller data type we perform
explicit type casting or narrowing.
This is useful for incompatible data types where automatic conversion cannot be
done.
Here, target-type specifies the desired type to convert the specified value to.
Example:
//Java program to illustrate incompatible data
// type for explicit type conversion
public class Test
{
public static void main(String[] argv)
{
char ch = 'c';
int num = 88;
ch = num;
}
}
Output:error: incompatible types: possible lossy conversion from int to
char
ch = num;
^
1 error
Explicit Conversion
//Java program to illustrate explicit type conversion
class Test
{ public static void main(String[] args)
{ double d = 100.04;
//explicit type casting
long l = (long)d;
//explicit type casting
int i = (int)l;
System.out.println("Double value "+d);
//fractional part lost
System.out.println("Long value "+l);
//fractional part lost
System.out.println("Int value "+i); } }
class ForLoopExample {
public static void main(String args[]){
for(int i=10; i>1; i--){
System.out.println("The value of i is: "+i);
}
}
}
Output: The value of i is: 10
The value of i is: 9
The value of i is: 8
The value of i is: 7
The value of i is: 6
The value of i is: 5
The value of i is: 4
The value of i is: 3
The value of i is: 2
For loop example to iterate an array:
Here we are iterating and displaying array elements using the for loop.
class ForLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
//i starts with 0 as array index starts with 0 too
for(int i=0; i<arr.length; i++){
System.out.println(arr[i]);
}
}
} Output: 2
11
45
9
Enhanced For loop
Enhanced for loop is useful when you want to iterate
Array/Collections, it is easy to write and understand.
class ForLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
for (int num : arr) {
System.out.println(num);
}
}
Output
} :2
11
45
9
Practice for loop
Write a Java Program to find sum of natural numbers using for loop.
Write a Java Program to find factorial of a number using loops.
Write a Java Program to print Fibonacci Series using for loop.
While Loop
class WhileLoopExample {
public static void main(String args[]){
int i=10;
while(i>1){
System.out.println(i);
i--;
} } }
Output:10
5
Practice while loop
2. Multidimensional Array
Creating an array
Creation of an array involves three steps:
1. Declaring the array.
2. Creating memory locations.
3. Putting values into the memory locations.
1. Syntax for declaring an one dimensional array
type var-name[];
OR
type[] var-name;
2. Creating memory locations.
Java allows us to create array using new operator only.
arrayname=new type[size];
The above statement does two things −
It creates an array using new type[Size].
It assigns the reference of the newly created array to the variable arrayname
Putting values into memory locations:
Type[] arrayname = {value0, value1, ..., valuek};
Example of array
/Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array Output:10
20
System.out.println(a[i]); 70
}} 40
50
Multidimensional Arrays
279
361
742
Passing Arrays to Methods
class Test {
// Driver method
public static void main(String args[])
{
int arr[] = {3, 1, 2, 5, 4};
// passing array to method m1
sum(arr); }
public static void sum(int[] arr) {
// getting sum of array values
int sum = 0;
for (int i = 0; i < arr.length; i++) Output: sum of array values : 15
sum+=arr[i];
System.out.println("sum of array values : " + sum); } }
Returning Arrays from Methods
class Test {
// Driver method
public static void main(String args[])
{
int arr[] = m1();
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i]+" "); }
public static int[] m1()
{ // returning array
return new int[]{1,2,3}; Output: 1 2 3
} }
Some methods use in Array
length
copyOf(original array, length)
sort(array)
reverse(array)
copyOfRange(original array, from, to)
equals(array1, array 2)
fill(array , value)
toString(array)
String
1 char charAt(int index) returns char value for the particular index
2 int length() returns string length
3 static String format(String format, Object... args) returns a formatted string.
4 static String format(Locale l, String format, Object... args) returns formatted string with given locale.
9 static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) returns a joined string.
10 boolean equals(Object another) checks the equality of string with the given object.
14 String replace(CharSequence old, CharSequence new) replaces all occurrences of the specified
CharSequence.
15 static String equalsIgnoreCase(String another) compares another string. It doesn't check case.
20 int indexOf(int ch, int fromIndex) returns the specified char value index starting with given index.
22 int indexOf(String substring, int fromIndex) returns the specified substring index starting with given index.
28 static String valueOf(int value) converts given type into string. It is an overloaded method.