Java Notes
Java Notes
Java Notes
1.JAVA BASICS
2.CONSTRUCTOR
3.KEYWORDS[STATIC,THIS,NEW,FINAL,SUPER]
4.OOPS +INTERFACE
5.EXCEPTION HANDLING
6.MULTITHREADING
7.JAVA I/O +Packages
8.JAVA STRING
9.JAVA JDBC
10.JAVA COLLECTIONS
1.What is Java
Java is a programming language and a platform. Java is a high level, robust, object-
oriented and secure programming language.
Java Variables
There are three types of variables in Java:
o local variable
o instance variable
o static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use
this variable only within that method and the other methods in the class aren't even
aware that the variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an
instance variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared
among instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can
create a single copy of the static variable and share it among all the instances of the
class. Memory allocation for static variables happens only once when the class is
loaded in the memory.
Data Types in Java
Boolean ----1BIT
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 in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, /
etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
SAMPLE PROGRAM:
import java.util.*;
class A
{
int rollno;
String names[] =new String[]{"PRIYA","Surya"};
int mark=100;
public void display()
{
System.out.println("Mark ="+mark);
}
}
INPUT FORMAT:
char c = sc.next().charAt(0);
int num =sc.nextInt();
int float =sc.nextFloat();//Same format for other datatypes.
String name =sc.nextLine();
1D ARRAY INPUT:
2. Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the
object is allocated in the memory.
Every time an object is created using the new() keyword, at least one constructor is
called.
Types of constructors
1. Default Constructor
2. Parameterized Constructor
1. Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
1. class Bike1{
2. //creating a default constructor
3. Bike1(){System.out.println("Bike is created");}
4. //main method
5. public static void main(String args[]){
6. //calling a default constructor
7. Bike1 b=new Bike1();
8. }
9. }
Output:
Bike is created
2. Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.
1. class Student4{
2. int id;
3. String name;
4. //creating a parameterized constructor
5. Student4(int i,String n){
6. id = i;
7. name = n;
8. }
9. //method to display the values
10. void display(){System.out.println(id+" "+name);}
11.
12. public static void main(String args[]){
13. //creating objects and passing values
14. Student4 s1 = new Student4(111,"Karan");
15. Student4 s2 = new Student4(222,"Aryan");
16. //calling method to display the values of object
17. s1.display();
18. s2.display();
19. }
20. }
//METHOD OVERLOADING ALSO SUPPORTED IN CONSTRUCTOR
3.KEYWORDS
1.STATIC KEYWORD:
The static keyword in Java is used for memory management mainly. We can apply
static keyword with variables, methods, blocks and nested classes. The static keyword
belongs to the class than an instance of the class.
Output:
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
3.this() can be used to invoke current class constructor.
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
Output:
hello a
10
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
5.this can be passed as argument in the constructor call.
6.this can be used to return the current class instance from the method.
1. Final Variable :
If you make any variable as final, you cannot change the value of final variable(It will
be constant).
2. Final Method :
3. Final Class:
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
2. super can be used to invoke immediate parent class method.
super.parentclassmethod();
1.Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
When one class inherits multiple classes, it is known as multiple inheritance. For
Example:
EXAMPLE:
1.SINGLE INHERITANCE:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
2.MULTIPLE INHERITANCE:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
3.HIERARCHICAL INHERITANCE:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
2.Polymorphism in Java:
Output:
It is because the static method is bound with class whereas instance method is bound with an
object. Static belongs to the class area, and an instance belongs to the heap area.
Java instanceof:
The java instanceof operator is used to test whether the object is an instance of the
specified type (class or subclass or interface).
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true
}
}
c) Encapsulation in Java
Encapsulation in Java is a process of wrapping code and data together into a single
unit.
We can create a fully encapsulated class in Java by making all the data members of the
class private. Now we can use setter and getter methods to set and get the data in it.
File: Test.java
d) Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
A class which is declared as abstract is known as an abstract class. It can have abstract
and non-abstract methods. It needs to be extended and its method implemented. It
cannot be instantiated.
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.
interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g. get
Drawable()
d.draw();
}}
Output:
drawing circle
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
OUTPUT:
Output:Hello
Welcome
5.Exception Handling
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
Types of Java Exceptions
1. Checked Exception -----Throwable class except RuntimeException
2. Unchecked Exception-----RuntimeException
3. Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
We can throw either checked or uncheked exception in java by throw keyword. The
throw keyword is mainly used to throw custom exception. We will see custom
exceptions later.
Output:
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
}
}
Output:exception handled
normal flow...
System.out.println("normal flow...");
}
}
Output:device operation performed
normal flow...
1. int a=50/0;//ArithmeticException
If we have a null value in any variable, performing any operation on the variable throws
a NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:
class GFG {
SQLException
private String getOriginalTaskId(final String taskId) {
String sql = String.format("SELECT original_task_id FROM %s WHERE task_id = '%s'
and state='%s' LIMIT 1", TABLE_JOB_STATUS_TRACE_LOG, taskId, State.TASK_STAGING);
String result = "";
try (
Connection conn = dataSource.getConnection();
PreparedStatement preparedStatement = conn.prepareStatement(sql);
ResultSet resultSet = preparedStatement.executeQuery()
) {
if (resultSet.next()) {
return resultSet.getString("original_task_id");
}
} catch (final SQLException ex) {
log.error(ex.getMessage());
}
return result;
}
Final is used to apply restrictions on class, method and variable. Final class can't be
inherited, final method can't be overridden and final variable value can't be changed and it
is a keyword.
6.Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously.
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Output:
2.6M
Prime Ministers of India | List of Prime Minister of India (1947-2020)
Success...
testout.txt
Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented
data .
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt"); //Welcome
int i=fin.read();
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Output:
Java ByteArrayInputStream
Let's see a simple example of java ByteArrayInputStream class to read byte array as input stream.
package com.javatpoint;
import java.io.*;
public class ReadExample {
public static void main(String[] args) throws IOException {
byte[] buf = { 35, 36, 37, 38 };
// Create the new byte array input stream
ByteArrayInputStream byt = new ByteArrayInputStream(buf);
int k = 0;
while ((k = byt.read()) != -1) {
//Conversion of a byte into character
char ch = (char) k;
System.out.println("ASCII value of Character is:" + k + "; Special character is: " + ch);
}
}
}
Output:
Types of packages:
Built-in Packages
These packages consist of a large number of classes which are a part of Java API.
Some of the commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which
defines primitive data types, math operations).
This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures
like Linked List, Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical
user interfaces (like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.
User-defined packages
These are the packages that are defined by the user.
First we create a directory myPackage (name should be same as the name
of the package). Then create the MyClass inside the directory with the first
statement being the package names.
8)Java String
In Java, string is basically an object that represents sequence of char values.
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
compareTo() method
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
String methods:-
1. charAt(): The java string charAt() method returns a char value at the
given index number.
String name="javatpoint";
char ch=name.charAt(4);//returns the char value at the 4th index
System.out.println(ch); //OUTPUT: t
2.concat()
The java string concat() method combines specified string at the end of this string. It
returns combined string. It is like appending another string.
3.contains()
3.endsWith()
String s1="java by javatpoint";
System.out.println(s1.endsWith("t")); //true
System.out.println(s1.endsWith("point")); //true
4.String format()
The java string format() method returns the formatted string by given locale, format
and arguments.
String name="sonoo";
String sf1=String.format("name is %s",name);
String sf2=String.format("value is %f",32.33434);
String sf3=String.format("value is %32.12f",32.33434);
OUTPUT:
name is sonoo
value is 32.334340
value is 32.334340000000
String s2="python";
System.out.println("string length is: "+s1.length());
5.length()
System.out.println("string length is: "+s1.length());//10 is the length of javatpoint s
tring
6.replace()
String replaceString=s1.replace('a','e');//replaces all occurrences of 'a' to 'e'
7.split()
String s1="java string split method by javatpoint";
String[] words=s1.split("\\s");//splits the string based on whitespace
//using java foreach loop to print elements of string array
8.substring()
String s1="javatpoint";
System.out.println(s1.substring(2,4));//returns va
System.out.println(s1.substring(2));//returns vatpoint
9.toCharArray(),toLowerCase()/toUpperCase
String s1="hello";
char[] ch=s1.toCharArray();
for(int i=0;i<ch.length;i++){
System.out.print(ch[i]);
String s1=" HELLO ";
String s1lower=s1.toLowerCase(); //hello
10.valueOf()
The java string valueOf() method converts different types of values into string.
int value=30;
String s1=String.valueOf(value);
System.out.println(s1+10);//concatenating string with 10
9.Java JDBC
1) Register the driver class
The forName() method of Class class is used to register the driver class. This method is used to d
driver class.
10.Collections in Java
The Collection in Java is a framework that provides an architecture to
store and manipulate the group of objects.
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data
structure in which we can store the ordered collection of objects. It can have duplicate
values.
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types.
LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to
store the elements. It can store the duplicate elements.
Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It is
synchronized
1. Vector<String> v=new Vector<String>();
Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure,
Output:
Ayush
Garvit
Amit
Ashish
Queue Interface
Queue interface maintains the first-in-first-out order. It can be defined as an ordered
list that is used to hold the elements which are about to be processed.
ArrayDeque
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque.
Unlike queue, we can add or delete the elements from both the ends.
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.
LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set Interface.
TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Like
HashSet, TreeSet also contains unique elements.