Java Basics
Java Basics
Let’s try to understand basics of any programing language before moving to Java:
1. Data Types
2. Variables
3. Operators
4. Conditional Statements
5. Control Statements (loops)
6. Arrays
7. Functions / Methods
Data Types:
Data types are used to allocate memory and specify what type of data you are using in the program.
All the data types are keywords which are having built in meaning. Below are the few data types in Java.
1. int: which is used to store integer value and it will not accept any decimal value. It allocates 4
bytes of memory.
2. long: which is used to store integer value and it will not accept any decimal value. It allocates 8
bytes of memory
3. float: which is used to store decimal value. It allocates 4 bytes of memory
4. double: which is used to store decimal value. It allocates 8 bytes of memory
5. char: which is used to store single character and it use to take only one byte.
6. Short: which use to take 2 bytes of memory and stores integer value.
7. Boolean: which takes only true or false
8. Byte: which takes only byte memory
String: is not a data type but it is predefined class. It allows to store set of characters.
Variables: Variables are nothing but in which data is stored. It is nothing but memory location name by
which you can refer your data.
datatype variablename=value
int b=20
int c=a+b
1. Should start with lower case and first letter of the second word should start with captial letter.
i.e. firstName, orderNumber
2. Can start with _ (under score)
3. Can start with $
4. First letter cannot be a capital letter
5. It can contain numbers but not in the middle
6. No other special symbols allowed
Operators:
1. Arithmetic:
a. +
b. -
c. *
d. /
e. % (moduls) which gives remainder
2. Relation Operator:
a. >
b. <
c. >=
d. <=
e. !=
4. Concatenation Operator:
int b=10
a+b=Ashok10
b+a=10Ashok
5. Logical Operators
a. &&(And operator)
b. ||(OR operator)
c. ! (logical not operator)
Conditional statements: are used to execute set of statements based on the condition satisfaction.
1. if
2. else
3. else if
4. nested if
if:
Syn: if(condition)
statements;
if-else:
syn: if(condition)
statements;
else
statements;
}
else-if
syn: if(condition)
statements;
else if(condition)
statements;
else
statements;
If(conditions)
If(condition)
Statements;
}
Switch: Unlike if-then and if-then-else statements, the switch statement can have a number of possible
execution paths. A switch works with the byte, short, char, and int.
Syn:
Switch(expression)
case “a”:
statements;
break;
case “b”:
statements;
break;
default:
statements;
Note: Here “break” is a keyword which breaks the block in which it is used. Here it comes outside switch
after executing any of the case statements. If we do not write break here it will continue to execute
remaining case statements also.
Control statements (loops): are used to execute set of statements as per defined number of times. All
the programming languages have below 3 types of loops.
1. while
2. for
3. do-while
While Loop:
Syntax:
initialization;
while (condition)
statements;
Example:
int i=1;
while(i<=10)
statements;
i++ OR i=i+1;
From above code statements inside the loop will be repeated for 10 times.
You can implement an infinite loop using the while statement as follows:
boolean b=true;
while (b){
if(login==)
b=false
Note: You need to make sure make b value set to false to avoid infinite loop
For Loop:
Syntax:
statements;
Example:
Statements;
do-while syn:
do
statements;
}while(condition);
The difference between do-while and while is that do-while evaluates its expression at the bottom of the
loop instead of the top. Therefore, the statements within the do block are always executed at least once
Example:
do
Statements;
}while(i<=10);
Arrays: Arrays are nothing but set of similar elements stored in single variable.
If we take normal variable (int x;) it will take / store only one value at a time and we cannot store more
than one value.
Let’s say I would like to write a program where I want to store student rule numbers for college in which
there are 1000 students available. If I use normal variable I have to declare thousand variables like
below:
int rolno1=1;
int rolno2=2;
int rolno3=3
And it goes on till
int rolno1000=1000;
Here you are spending more time in declaring variable rather than writing actual program. So to avoid
this we can go for using arrays where you can declare only one array variable and store 1000 values in
this variable.
Declaration of Arrays:
From above line we are declaring rolno variable as an array and we specifying size as 1000 which means
rolno variable can be used to store 1000 values in one array variable.
We are using “new” here new is a key word which basically used to allocate the memory. We will discuss
about “new” key word in coming topics in detail.
In above we understand that we have allocated size of array as 1000 and we can story 1000 integer
values in the variable called rolno.
Let’s assign values for array: arrays index always starts with zero
rolno[0]=1;
rolno[1]=2;
rolno[2]=3;
rolno[3]=4;
rolno[999]=1000;
Since arrays starts with indexing zero last value will be stored always size – 1 which is 1000-1= 999
Types of array
Methods / Functions: Method is a set or group of statements which can be used to repeat any number
of times. Methods are written for specific task / purpose. Methods have following:
1. Method declaration (it is not required from java and C++ & needed in C language)
2. Method calling (goes to method definition), if we don’t call function definition will not be executed
3. Method definition (here you write the code for which purpose method is written)
Code
Void add()
Code
Types of functions
1. Pre-defined: These functions are which are already defined and we can reuse these functions.
Example: main
2. User defined: Which we are going to define / write to our self
OOPS: If any programming language that supports below futures then that language is known as OOPS
language.
1. Class
2. Object
3. Polymorphism
4. Inheritance
5. Encapsulation
Installation of Java:
1. Open http://www.oracle.com/technetwork/java/javase/downloads/index.html
2. Click on JDK Download
1. What is Class
2. What is Object
3. Constructors
4. Polymorphism
a. Method Overloading
b. Method Overriding
5. Constructor Overloading
6. Static Variables / Methods / Block
7. Inheritance & Types of Inheritance
8. Super & This
9. Abstract class & Abstract methods
10. Interfaces
11. Packages
12. Access Modifiers
13. Exception Handling
14. Collections Interfaces
15. Final, Finalize and finally
16. Strings
Class:
A class is a group of data members and functions which has common properties.
Data members(variables)
Data functions
String steering;
String break;
int wheels;
void run()
void reverseGear()
Objects:
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc.
It can be physical or logical.
Constructor is a special type of method which has same name of the class. Constructor is invoked at the
time of object creation and no need to call the constructors like functions. Constructors will not return a
value not even void also.
Types of constructors:
Default Constructor:
Constructor that have no parameter is known as default constructor.
Syntax of default constructor:
class_name()
Initilization statements;
Parameterized constructor:
Initialization statements;
Means many forms. More than one method will have same name.
Compile time polymorphism: is achieved using method overloading and constructor overloading
Method overloading:
If a class have multiple methods by same name but different parameters, it is known as Method
Overloading.
Suppose you have to perform addition of the given numbers but there can be any number of arguments,
if you write the method such as add1(int,int) for two parameters, and add2(int,int,int) for three
parameters then it may be difficult for you as well as other programmers to understand the behavior of
the method because its name differs. So, we perform method overloading to figure out the program
quickly.
Advantages of method overloading: Method overloading increases the readability of the program
Method Overloading is not possible by changing the return type of the method
Yes, by method overloading. You can have any number of main methods in a class by method
overloading.
Constructor Overloading:
Constructor overloading is a technique in Java in which a class can have any number of constructors that
differ in parameter lists. The compiler differentiates these constructors by taking into account the number
of parameters in the list and their type.
Run time polymorphism: is achieved using method overloading and this concept is implemented using
inheritance. We will discuss this once inheritance is completed.
Static key word in java:
The static keyword is used in java mainly for memory management. We may apply static keyword with
variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the
class.
Static variable:
The static variable can be used to refer the common property of all objects (that is not unique for each
object) e.g. company name of employees,college name of students etc.
The static variable gets memory only once in class area at the time of class loading.
Suppose there are 500 students in my college, now all inx x xstance data members will get
memory each time when object is created. All student have its unique rollno and name so instance data
member is good. Here, college refers to the common property of all objects.If we make it static,this field
will get memory only once
Static method:
If you apply static keyword with any method, it is known as static method
A static method can be invoked without the need for creating an instance of a class.Static methods called
by classname. ex classname.methodName();
Static method can access only static data member and can change the value of it.
The static method cannot use non static data member or call non-static method directly.
this and super keywords cannot be used in static context.
Static block:
Because object is not required to call static method if it were non-static method, jvm create object first
then call main() method that will lead the problem of extra memory allocation
Inheritance:
Inheritance is a mechanism in which one object acquires all the properties and behaviors of parent
object.
The idea behind inheritance is that you can create new classes that are built upon existing classes. When
you inherit from an existing class, you reuse (or inherit) methods and fields, and you add new methods
and fields to adapt your new class to new situations.
Syntax of Inheritance
The keyword extends indicates that you are making a new class that derives from an existing class. In
the terminology of Java, a class that is inherited is called a superclass. The new class is called a subclass.
Types of Inheritance
1. Single
2. Multilevel
3. Multiple
4. Hybrid
Java does not support multiple inheritance however it can implemented using Interfaces.
Single Inheritance:
class Father
Multilevel Inheritance:
class GrandFather
}
Using Super:
When invoking a superclass version of an overridden method the super keyword is used.
Interfaces:
The interface is a mechanism to achieve fully abstraction in java. There can be only abstract methods in
the interface. It is used to achieve fully abstraction and multiple inheritance in Java
The java compiler adds public and abstract keywords before the interface method and public, static and
final keywords before data members.
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as
multiple inheritance.
Note: A class implements interface but One interface extends another interface
Package in Java:
Package can be categorized in two form, built-in package and user-defined package. There are many
built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Advantage of Package:
•Package is used to categorize the classes and interfaces so that they can be easily maintained.
Creation of Package:
Class Example
There are three ways to access the package from outside the package.
1.import packagename.*; It will import all the class and interfaces to this package. It is recommended
not to use this as it will impact on performance as it as to load all the class.
2.import packagename.classname;
Using packagename.*:
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to the
current package.
Using packagename.classname:
If you import package.classname then only declared class of this package will be accessible.
If you use fully qualified name then only declared class of this package will be accessible. Now there is no
need to import. But you need to use fully qualified name every time when you are accessing the class or
interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.
Access Modifiers:
The access modifiers specifies accessibility (scope) of a datamember, method, constructor or class.
1.private
2.default
3.protected
4.public
Private:
class A
System.out.println("Hello java");
A obj=new A();
If you make any class constructor private, you cannot create the instance (object) of that class from
outside the class. For example:
class A
private A(){
}//private constructor
public class B
If you don't use any modifier, it is treated as default by default. The default modifier is accessible only
within package.
In this example, we have created two packages pack1 and pack2. We are accessing the A class from
outside its package, since A class is not public, so it cannot be accessed from outside the package.
//save by A.java
package pack1;
class A
void method1(){System.out.println("Hello");}
//save by B.java
package pack2;
import pack1.*;
class B
In the above example, the scope of class A and its method method1() is default so it cannot be accessed
from outside the package.
Protected:
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't be
applied on the class.
In this example, we have created the two packages pack1 and pack2. The A class of pack package is
public, so can be accessed from outside the package. But msg method of this package is declared as
protected, so it can be accessed from outside the class only through inheritance.
//save by A.java
package pack1;
public class A
System.out.println("Hello");
//save by B.java
package pack2;
import pack1.*;
class B extends A
obj.method1();
Output:Hello
Public:
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
//save by A.java
package pack;
public class A
System.out.println("Hello");
//save by B.java
package mypack;
import pack.*;
class B
obj.msg();
The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to
handle the run time errors so that normal flow of the application can be maintained.
Exception
The core advantage of exception handling is that normal flow of the application is maintained. Exception
normally disrupts the normal flow of the application that is why we use exception handling. Let's take a
scenario:
1.statement 1;
2.statement 2;
3.statement 3;
4.statement 4;
5.statement 5;
6.statement 6;
7.statement 7;
8.statement 8;
9.statement 9;
10.statement 10;
Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest of
the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception handling, rest
of the code will be executed. That is why we use exception handling.
Types of Exception:
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
Checked exceptions: A checked exception is an exception that is typically a user error or a problem that
cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be
found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
Runtime exceptions: A runtime exception is an exception that occurs that probably could have been
avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the
time of compilation.
Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer. Errors are typically ignored in your code because you can rarely do anything about an error.
For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of
compilation.
There are given some scenarios where unchecked exceptions can occur. They are as follows:
1. Scenario where Arithmetic Exception occurs: If we divide any number by zero, there occurs an
Arithmetic Exception.
2. Scenario where NullPointerException occurs: If we have null value in any variable, performing
any operation by the variable occurs an NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
3. Scenario where NumberFormatException occurs: The wrong formatting of any value, may occur
NumberFormatException. Suppose I have a string variable that have characters, converting this
variable into digit will occur NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4. Scenario where ArrayIndexOutOfBoundsException occurs: If you are inserting any value in the
wrong index, it would result ArrayIndexOutOfBoundsException as shown below:
a[10]=50; //ArrayIndexOutOfBoundsException
Five keywords used in Exception handling:
1.try
2.catch
3.finally
4.throw
5.throws
try
statements;20/0
catch(Exception_class_Name reference)
try
statements;
finally
Rules:
At a time only one Exception is occurred and at a time only one catch block is executed.
All catch blocks must be ordered from most specific to most general i.e. catch for
ArithmeticException must come before catch for Exception.
Finally block:
The finally block is a block that is always executed. It is mainly used to perform some important tasks
such as closing connection, stream etc.
finally block can be used to put "cleanup" code such as closing a file,closing connection etc
Note: For each try block there can be more catch blocks, but you can have only one finally block.
Note: The finally block will not be executed if program exits(either by calling System.exit() or by causing
a fatal error that causes the process to abort).
Throw:
The throw keyword is used to explicitly throw an exception. The throw keyword is mainly used to throw
custom exception.
Throws keyword
The throws keyword is used to declare an exception. It gives an information to the programmer that
there may occur an exception so it is better for the programmer to provide the exception handling code
so that normal flow can be maintained.
statements;
All the operations that you perform on a data such as searching, sorting, insertion, manipulation,
deletion etc. can be performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
Collection framework represents a unified architecture for storing and manipulating group of
objects. It has:
Let us see the hierarchy of collection framework.The java.util package contains all the classes
and interfaces for Collection framework.
Methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
There are only three methods in the Iterator interface. They are:
Java ArrayList class uses a dynamic array for storing the elements. It extends AbstractList class
and implements List interface.
Java ArrayList allows random access because array works at the index basis.
In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any
element is removed from the array list.
LIST ARRAYLIST
List is an Interface. ArrayList is a Class.
List interface extends the Collection ArrayList extends AbstractList class and
framework. implements List interface.
List cannot be instantiated. ArrayList can be instantiated.
List interface is used to create a list ArrayList class is used to create a
of elements(objects) which are dynamic array that contains objects.
associated with their index numbers.
Set Interface
Set Interface in Java is present in java.util package. It extends the Collection interface. It
represents the unordered set of elements which doesn't allow us to store the duplicate
items. We can store at most one null value in Set. Set is implemented by HashSet,
LinkedHashSet, and TreeSet.
1. Set<data-type> s1 = new HashSet<data-type>();
2. Set<data-type> s2 = new LinkedHashSet<data-type>();
3. Set<data-type> s3 = new TreeSet<data-type>();
HashSet
HashSet class implements Set Interface. It represents the collection that uses a hash table
for storage. Hashing is used to store the elements in the HashSet. It contains unique items.
Set Interface
Set Interface in Java is present in java.util package. It extends the Collection interface. It
represents the unordered set of elements which doesn't allow us to store the duplicate
items. We can store at most one null value in Set. Set is implemented by HashSet,
LinkedHashSet, and TreeSet.
1. Set<data-type> s1 = new HashSet<data-type>();
2. Set<data-type> s2 = new LinkedHashSet<data-type>();
3. Set<data-type> s3 = new TreeSet<data-type>();
HashSet
HashSet class implements Set Interface. It represents the collection that uses a hash table
for storage. Hashing is used to store the elements in the HashSet. It contains unique items.
Final variable:
If you make any variable as final, you cannot change the value of final variable (It will be constant).
Final method:
Final class:
The final keyword in java is used to restrict the user. The final keyword can be used in many context.
Final can be
Final variable
Final method
Final class
The final keyword can be applied with the variables, a final variable that have no value it is called blank
final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final
variable can be static also which will be initialized in the static block only. We will have detailed learning
of these. Let's first learn the basics of final keyword.
Strings:
No Method Description
.
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.
5 String substring(int beginIndex) returns
substring for
given begin
index.
6 String substring(int beginIndex, int endIndex) returns
substring for
given begin
index and end
index.
7 boolean contains(CharSequence s) returns true or
false after
matching the
sequence of
char value.
8 static String join(CharSequence delimiter, CharSequence... returns a joined
elements) string.
9 static String join(CharSequence delimiter, Iterable<? extends returns a joined
CharSequence> elements) string.
10 boolean equals(Object another) checks the
equality of
string with the
given object.
11 boolean isEmpty() checks if string
is empty.
12 String concat(String str) concatenates
the specified
string.
13 String replace(char old, char new) replaces all
occurrences of
the specified
char value.
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.
16 String[] split(String regex) returns a split
string matching
regex.
17 String[] split(String regex, int limit) returns a split
string matching
regex and limit.
18 String intern() returns an
interned string.
19 int indexOf(int ch) returns the
specified char
value index.
20 int indexOf(int ch, int fromIndex) returns the
specified char
value index
starting with
given index.
21 int indexOf(String substring) returns the
specified
substring index.
22 int indexOf(String substring, int fromIndex) returns the
specified
substring index
starting with
given index.
23 String toLowerCase() returns a string
in lowercase.
24 String toLowerCase(Locale l) returns a string
in lowercase
using specified
locale.
25 String toUpperCase() returns a string
in uppercase.
26 String toUpperCase(Locale l) returns a string
in uppercase
using specified
locale.
27 String trim() removes
beginning and
ending spaces
of this string.
28 static String valueOf(int value) converts given
type into string.
It is an
overloaded
method.