Unit - 1 Basics of Java
Unit - 1 Basics of Java
BASICS OF JAVA
INTRODUCTION
● Java was developed by James Gosling in 1991 at Sun Microsystems which is now
subset of Oracle.
● The language was initially called ‘Oak’, but was renamed as ‘Java’ in 1995.
● Java is both programming language and a platform.
● A platform is a hardware or software where the programs run.
● Most platforms can be described as a combination of the operating system and
underlying hardware. The Java platform differs from most other platforms in that it's a
software-only platform that runs on top of other hardware-based platforms.
● Java platform has two components:
○ Java Virtual Machine(JVM)
○ Application Programming Interface
INTRODUCTION
Uses of java
● It is used for developing Android Apps
● Helps you to create Enterprise Software
● Wide range of Mobile java Applications
● Scientific Computing Applications
● Use for Big Data Analytics
● Java Programming of Hardware devices
● Used for Server-Side Technologies like Apache, JBoss, GlassFish,
etc.
OOP v/s POP
Procedural Oriented Programming Object Oriented Programming
In POP, program is divided into small In OOP, program is divided into parts
parts called functions. called objects.
POP does not have any access OOP has access specifiers named Public,
specifier. Private, Protected, etc.
In POP, Data can move freely from In OOP, objects can move and
function to function in the system. communicate with each other through
member functions.
OOP v/s POP
To add new data and function in POP OOP provides an easy way to add new
is not so easy. data and function.
In POP, Most function uses Global data In OOP, data can not move easily from
for sharing that can be accessed freely function to function, it can be kept public
from function to function in the system. or private so we can control the access of
data.
POP does not have any proper way for OOP provides Data Hiding so
hiding data so it is less secure. provides more security.
JDK contains tools required to write Java program & JRE to execute them. It
includes compiler, Java application launcher, Appletviewer etc.
NOTE: Compiler converts source code to the bytecode & App Launcher opens JRE,
loads the necessary class & execute its main method
Java Runtime Environment
JRE is a piece of software that is designed to run other software. It contains
the class libraries, loader class & JVM.
JRE does not include any tool for java development like debugger, compiler
etc. It uses important package classes like math, swing, util, lang, awt &
runtime libraries.
NOTE: For developing the java programs we need JDK but to run java
program only JRE is needed
Working of JRE
The JRE combines the Java code that you create by using the JDK with
additional built-in code called libraries. It then creates a JVM instance, or local
copy, that finally runs the Java programs.
JVMs are available for multiple operating systems, and the JRE generates a
single copy of your Java code that runs on all types of JVMs.
In this way, the JRE facilitates platform independence for Java applications.
You can write them once and run them anywhere.
Java Virtual Machine
JVM is an engine that provides a runtime environment to drive a java code or application. It is
a part of JRE which converts bytecode to machine language.
Bytecode: Computer object code that an interpreter converts into binary machine code so it
can be read by a computer’s hardware processors.
JVM provides the platform independent way to execute java source code. When we compile
java program, the bytecode is generated. Bytecode is an intermediary language between java
source & the host system.
JVM comes with JIT(just-in-time) compiler that converts java source code into low level
language.
NOTE: Although JVM provides platform independent way to execute source code but
itself is platform dependent. It also allocate & deallocate the memory space
Java compiler Byte code
Java Source
(javac)
code
Byte code
loaded into
JVM
Java
Host System Interpreter
JVM
JVM Architecture
JVM Architecture
1. Class Loader:
The class loader is a subsystem used for loading class files. It performs three major functions
viz. Loading, Linking, and Initialization.
2. Method Area:
JVM Method Area stores class structures like metadata, the constant runtime pool, and the
code for methods.
3. Heap:
All the Objects, their related instance variables, and arrays are stored in the heap. This
memory is common and shared across multiple threads.
JVM Architecture
4. JVM Language Stack:
Java language Stacks store local variables, and it’s partial results. Each thread has its own JVM
stack, created simultaneously as the thread is created. A new frame is created whenever a method is
invoked, and it is deleted when method invocation process is complete.
6. Execution Engine:
Native method stacks hold the instruction of native code depends on the native library. It is written in
another language instead of Java.
JVM Architecture
7. Execution engine:
It is a type of software used to test hardware, software, or complete systems. The test
execution engine never carries any information about the tested product.
● J2EE(Enterprise Edition):
Java SE plus various APIs useful for multi-tier client–server enterprise applications.
● J2SE(Standard Edition):
For general-purpose use on desktop PCs, servers and similar devices.
● Java FX:
JavaFX is a platform for developing rich internet applications using a lightweight user-interface
API.
Syntax
class Classname{
public static void main(String args[ ]){
System.out.println();
}
}
The main() method
The main() method holds significant importance in Java programming as it acts as the entry
point for the program's execution, allowing it to be run from the command line or any Java
runtime environment.
While compiling a Java program, the presence of a main() method is not strictly required, but
during execution, the JVM searches for this method and initiates program execution from
there.
The main() method in Java must have a public access modifier, enabling it to be accessed from
outside the class.
Being a static method, it can be called without creating an instance of the class.
Additionally, it does not return any value and accepts a String array as a parameter, allowing
command-line arguments to be passed to the program.
The main() method
● The modifiers public and static can be written in either order (static public or
public static), but the convention is to use public static as shown in syntax.
● You can define a main() method with any access modifier or with/without static
keyword, but then it is not a valid main() method, as the main method which the
JVM uses as an entry-point should be defined as such.
● You can name the argument anything you want, but most developers choose "args"
or "argv"
● You can write a program without defining a main() it gets compiled without
compilation errors. But when you execute it, a run time error is generated saying
"Main method not found".
The main() method
● Public: The main() method in Java has a public access specifier, making it globally accessible.
This is crucial because the Java Runtime Environment (JRE) calls this method from outside of
your current class. It's essential to keep the main() method public; otherwise, access restrictions
will prevent it from being executed by any program.
● Static: The main() method in Java must be declared as static. By making the main() method
static, it can be invoked directly by the JVM without the need to create an instance of the class.
This is essential because the JVM needs a starting point to execute the program, and it does so
by calling the main() method without instantiating the class.
The main() method
● Void: The main() method in Java is declared with a return type of "void" to indicate that it does
not return any value. The purpose of the main() method is to serve as the entry point for the Java
program, and it is invoked by the Java Virtual Machine (JVM) to start the execution of the
program.
● Main: It's just the name of method or a function name. This name is fixed and as it's called by
the JVM as entry point for an application. It's not a keyword.
Structure of System.out.println()
System.out.println() is a method in Java or a statement that is used to display a
message, data, or string on the screen as the output. It displays the arguments
that are passed to it.
● System: This is the final class that is defined in java.lang package.
● out: This is an instance of PrintStream type, and the access specifiers are
final and public.
● println(): This is a method in the PrintStream class.
We can also use print() method to print the arguments. But it prints the
output without adding the new line.
Simple Program
class Classname{
public static void main(String args[ ]){
System.out.println(“Hello World”);
}
}
OUTPUT:
DATA TYPES
● Data Types in Java are defined as specifiers that allocate different sizes
and types of values that can be stored in the variable or an identifier.
● Java is a static-typed language that means the data type of the variable is
known at compile time.
● The type of the variable determines its value & operations.
● Datatypes in JAVA are categorized into:
○ Primitive Data-type
○ Non-primitive Data-type
Primitive Data-types
Primitive Data Types are predefined and available within the Java language.
Primitive values do not share state with other primitive values.
The byte is the smallest data type among all the integer data types. It is an
8-bit signed two’s complement integer. It stores whole numbers ranging
from -128 to 127. Its size is 1 byte.
This data-type is also similar to the integer datatype. However it’s 2 times
smaller than the integer datatype. Its minimum range is -32,768 and
maximum range is 32,767. It has a size of 2bytes.
int is used for storing integer values. Its size is 4 bytes and has a default
value of 0.
The maximum values of integer is 2^31 and the minimum value is -2^31.
It can be used to store integer values unless there is a need for storing
numbers larger or smaller than the limits.
It is a floating-point data type that stores the values, including their decimal
precision. It is not used for precise data such as currency or research data.
The double data type is similar to float. The difference between the two is that is
double twice the float in the case of decimal precision. It is used for decimal values
just like float and should not be used for precise values. In java the double is the
default floating data-type.
Example: int a;
a = 5;
OR
int a= 5;
Variables
class demo{
void method() {
}
Rules for Variable declaration
Rules to Declare a Variable
1. A variable name can consist of Capital letters A-Z, lowercase letters a-z digits 0-9, and
two special characters such as _ underscore and $ dollar sign.
2. The first character must not be a digit.
3. Blank spaces cannot be used in variable names.
4. Java keywords cannot be used as variable names.
5. Variable names are case-sensitive.
6. There is no limit on the length of a variable name but by convention, it should be
between 4 to 15 chars.
7. Variable names always should exist on the left-hand side of assignment operators.
Type Conversion & Type Casting
● A significant part of programming involves playing around with data.
While performing some tasks, situations might arise where the data type
has to be changed from one type to another.
● For example, while calculating the area of a circle using Pi, we get a
decimal number, and that needs to be converted to integer if we desire to
obtain the answer in integer format.
● Since Java is strongly typed, one often needs to convert from one data
type to another. The programmer or the compiler can easily do this by
using type casting and type conversion concepts.
Type Conversion
Type conversion is a process in which the data type is automatically converted
into another data type. The compiler does this automatic conversion at compile
time.
For type conversion to take place, the destination data type must be larger than the
source type.
This type of type conversion is also called Widening Type Conversion/ Implicit
Conversion/ Casting Down. In this case, as the lower data types with smaller
sizes are converted into higher ones with a larger size, there is no chance of data
loss.
Type Conversion
Type Conversion
class Main {
int a= 10;
float b=a;
}
Type Casting
Type casting is a process in which the programmer manually converts one data
type into another data type. For this the casting operator (), the parenthesis is used.
Unlike type conversion, the source data type must be larger than the destination
type in type casting. The below flow chart has to be followed for successful type
casting.
Type casting is also called Narrowing Type Casting/ Explicit Conversion/ Casting
Up. In this case, as the higher data types with a larger size are converted into lower
ones with a smaller size, there is a chance of data loss. This is the reason that this
type of conversion does not happen automatically.
Type Casting
Type Casting
class Main {
float a= 10.56f;
int b=a;
}
Reserved Words/Keywords
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
Operators
● An operator is a symbol that performs an operation. An operator acts on
variables called operands.
● We can divide all the Java operators into the following groups:
○ Arithmetic Operators
○ Relational Operators
○ Bitwise Operators
○ Logical Operators
○ Assignment Operators
○ Special Operators
Operators: Arithmetic Operators
Operators: Assignment Operators
Operators: Unary Operators
Operators: Relational Operators
Operators: Logical/ Short Circuit Operators
Operators: Bitwise Operators
Operators: Ternary/ Conditional Operators
○ switch statement
if statement
if statement performs a task depending on whether a condition is true or
false.
Syntax: if(condition){ Example:
int a=5;
//statements if(a> 10){
System.out.println(“Given condition is true”)
} }
OUTPUT
do-while loop
● do…while loop repeats a group of statements as long as condition is
true.
● In do...while loop, the statements are executed first and then the
condition is tested.
● do…while loop is also called as exit control loop.
● Syntax: do{
//statements;
} while (condition);
do-while loop: Example
OUTPUT
for loop
● The for loop is also same as do…while or while loop, but it is more
compact syntactically.
● The for loop executes a group of statements as long as a condition is
true.
● Syntax: for (initialisation; condition; inc/dec)
{
//Statements;
}
for loop: Example
OUTPUT
Jump Statement
● Java supports three jump statements:
○ break
○ continue
○ return.
OUTPUT
Continue statement
● This statement is useful to continue the next repetition of a loop/
iteration.
● When continue is executed, subsequent statements inside the loop
are not executed.
● Syntax: continue;
Continue: Example
OUTPUT
Return statement
● return statement is useful to terminate a method and come back to the
calling method.
● return statement in main method terminates the application.
● return statement can be used to return some value from a method to a
calling method.
● Syntax:
return; (or)
return value; // value may be of any type
Return: Example
OUTPUT
Array
● An array represents a group of elements of same data type. Arrays are
generally categorized into two types:
○ Single Dimensional arrays (or 1 Dimensional arrays)
○ Multi-Dimensional arrays (or 2 Dimensional arrays, 3 Dimensional
arrays, …)
● Creating an array
○ Declare an array
○ Create memory location
○ Putting values to memory locations
Declaring array variable
To declare an array, write the data type, followed by a set of square
brackets[ ], followed by the identifier name.
double[] myList;
or
double myList[];
Array Creation
To create array, write the new keyword, followed by the square[ ] brackets
containing the number of elements you want to have in array.
For Example:
int arr[ ]; //declaration
Or
Example:
It works on the basis of elements and not the index. It returns element one by one in
the defined variable.
Syntax:
//statement
}
Example
OUTPUT
Multi-dimensional array
A multidimensional array is an array of arrays. That is, each element of a
multidimensional array is an array itself.
For example:
int[][] arr={{1,2,3},{4,5,6}}
To access the elements of the arr array, specify two indexes: one for the array,
and one for the element inside that array.
Multi-dimensional array: using for loop
OUTPUT
Multi-dimensional array: using for each loop
OUTPUT
Jagged array
Jagged array are the multidimensional arrays with different size
Jagged array
Jagged array
OUTPUT
Advantages & disadvantages of array
Advantages:
1. Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.
String
● Strings are very important in the world of programming languages as they
are used to process long textual/symbolic information.
● Strings are considered fundamental data types in almost all programming
languages. These languages use character arrays to process long textual
information.
● In java, string class is provided to work with strings along with the facility
of character arrays.
● The strings are immutable as once an object of the String class is created
& initialized with some value, it cannot be changed.
String
● To handle string data in Java, we require objects of the String class.
● The String class is included in the java.lang package. Therefore each class
can use the String class without importing any package.
● Example: String str = “Hello”
Operation on String
The string class in java provides various methods that enable you to perform
various tasks like:
1. Convert a string into a character
2. Convert numbers into strings
3. Search strings
4. Create substrings
5. Change the case of string
6. Get a string length
7. Compare strings
length() method
● The length method returns the length of the a string. This method
calculates all the characters, symbols & numbers enclosed in double
quotes (“”).
● The method returns an integer value
toLowerCase()
The toLowerCase() method returns a string after converting all uppercase letters of the
invoking string into lowercase.
Syntax: stringname.toLowerCase()
toUpperCase()
The toUpperCase() method returns a string after converting all lowercase letters of the
invoking string into Uppercase.
Syntax: stringname.toUpperCase()
substring()
● This method returns a new String instance that is a substring of the
original String instance.
● The substring() method is available in the following two forms:
1. substring(int begin)
It takes a single parameter, which creates a new string that begins at
the index specified by the argument value & ends at the last
character of the string.
Example:
String str = “EDUCATION”
system.out.println(str.substring(4));
substring()
2. substring(int begin, int end)
This takes two parameters, the starting index and the ending index.
The character at the start index is included in substring but the
character at the end index is not.
Example:
String str = “EDUCATION”
System.out.println(str.substring(3,6));
concat()
We can concatenate strings in two ways
● Using addition(+)operator
● Using concat() method.
Example:
String str = “Hello”
String str1 = “Java”
System.out.println(str+str1);
System.out.println(str.concat(str1));
equals & equalsIgnoreCase()
● These methods are used for comparing two strings.
● equals() compare the positions of the individual characters in a string.
● The equalsIgnoreCase() method does the same but ignores the case of
characters
● Example:
String str = “Java is oopl”
String str1 = “JAVA IS OOPL”
System.out.println(str.equals(str1));
System.out.println(str.equalsIgnoreCase(str1));
Example
Example
OUTPUT
Stringbuffer
● StringBuffer class gives the facility to create a sequence of characters with mutable
(modifiable) attributes.
● Syntax:
StringBuffer str = new StringBuffer();
● The various StringBuffer methods are:
1. length()
2. capacity()
3. reverse()
4. append()
5. insert()
6. delete()
7. deleteCharAt()
8. replace()
length()
It defines the number of characters in the String.
Example:
Example:
StringBuffer str = new StringBuffer(“Hello");
str.append(“java");
System.out.println(str);
str.append(0);
System.out.println(str);
insert()
The insert() method is used to insert the string into the previously defined
string at a particular indexed position.
In the insert method as a parameter, we provide two-argument, first is the
index and second is the string.
Example:
StringBuffer stringName = new StringBuffer(" Welcome");
System.out.println(stringName);
stringName.insert(8, " to java");
System.out.println(stringName);
reverse()
The reverse() method reverses all the characters of the object of the
StringBuffer class. And, as an output, this method returns or gives the
reversed String object.
Example:
StringBuffer sb = new StringBuffer("Welcome to Java");
System.out.println("Original String: " + sb);
stringName.reverse();
System.out.println("Reversed String: " + sb);
delete()
The delete() method deletes a sequence of characters from the StringBuffer
object.
Syntax:
stringName.delete(int startIndex, int endIndex)
Example:
StringBuffer sb= new StringBuffer(“welcometojava");
System.out.println("Original String: " + sb);
myString.delete(0, 4);
System.out.println("String after deleting sequence of characters: " + sb);
deleteCharAt()
The deleteCharAt() method deletes only the character at the specified index.
Syntax:
stringName.deleteCharAt(int index)
Example:
StringBuffer sb= new StringBuffer(“Welcome to java");
System.out.println("Original String: " + sb);
myString.deleteCharAt(7);
System.out.println("Resulting String " + sb);
replace()
The replace() method of the StringBuffer class replaces a sequence of
characters with another sequence of characters.
Syntax:
stringName.replace(int startIndex, int endIndex, String string)
Example:
StringBuffer s = new StringBuffer(“Welcome to java");
System.out.println("Original String: " + s);
s.replace(12, 15, "Tutorial");
System.out.println("Resulting String after replacing: " + s);
Example
Example
Command line arguments
● Sometimes we need to pass information into a program while it is
running. This can be accomplished by passing command line arguments
to main()
● The information passed is stored in the string array passed to the main()
method and it is stored as a string. It is the information that directly
follows the program’s name on the command line when it is running.
●
Example-1
OUTPUT:
Example-2
OUTPUT:
varargs
If we don't know how many argument we will have to pass in the method,
varargs is the better approach.
The varargs allows the method to accept zero or multiple arguments. Before
varargs either we use overloaded method or take an array as the method
parameter but it was not considered good because it leads to the
maintenance problem.
Example:
OUTPUT:
Wrapper Class
● In java, wrapper classes are used to convert primitive types into class
objects.
● Basically, generic classes only work with objects and don't support
primitives. As a result, if we want to work with them, we have to convert
primitive values into wrapper objects.
● Each primitive type has corresponding wrapper classes.
● All wrapper classes belongs to the java.lang package
Wrapper Class
Need of Wrapper Class
● Whenever the primitive types are required as an object, wrapper classes can be used.
Wrapper classes also include methods to unwrap the object and give back the data type.
● In java.util package, the classes handle only objects. In this case wrapper class are helpful
as they convert primitive data type to objects.
● In the Collection framework, Data Structures such as ArrayList store data only as objects
and not the primitive types.
● Wrapper classes have methods that support object creation from other object types
such as string.
● Wrapper classes are also used for synchronization in multithreading. As in
synchronization process, we try to achieve that the shared resource will be used by only
one thread at a time. Objects are needed for this.
Wrapper Class
Creating wrapper object:
● Syntax:
ClassName object = ClassName.valueOf(argument);
● Example:
int a= 10;
Integer num= Integer.valueOf(a);
Wrapper class methods
Autoboxing
Autoboxing is when the Java compiler performs the automatic conversion of
the primitive data types to the object of their corresponding wrapper classes.
For example, converting an int to Integer, a double to Double, etc.
If you print any object, Java compiler internally invokes the toString() method
on the object. So overriding the toString() method, returns the desired output,
it can be the state of an object etc. depending on your implementation.
toString() method
parseXXX() method
parseXXX() method is use to convert String to a primitive type.
parseXXX() method