Java Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

JAVA

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.

A local variable cannot be defined with "static" keyword.

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

BYTE --------1 BYTE


CHAR ,SHORT ---2 BYTES

INT ,FLOAT ------4 BYTES

LONG,DOUBLE ----8 BYTES

Access Modifiers in Java


There are four types of Java access modifiers:

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);
}
}

public class MyClass {


public static void main(String args[]) {
int i,n=2;
Scanner sc= new Scanner(System.in);
A obj =new A();
obj.rollno=sc.nextInt();
/*for(i=0;i<n;i++)
{
obj.names[i]=sc.nextLine(); //To get Array Input.
}*/
System.out.println("ROLL NO = " + obj.rollno);
for(i=0;i<n;i++)
{
System.out.println("NAME = " + obj.names[i]);
}
obj.display();
}
}

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:

1. datatype arrayName[] = new datatype[size];


Eg: int arr[]=new int[5];
2D ARRAY INPUT:

1. datatype arrayName[][] = new datatype[size][size];


Eg: int arr[][]=new int[3][3];
String Array Format: //Same format for int

1. String[] strAr1=new String[] {"Ani", "Sam", "Joe"}; //inline initialization


2. String[] strAr2 = {"Ani", "Sam", " Joe"};
3. String[] strAr3= new String[3];
strAr3[0]= "Ani";
strAr3[1]= "Sam";
strAr3[2]= "Joe";

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.

It is a special type of method which is used to initialize the object.

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

Rules for creating Java constructor


There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

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.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

1) Java static variable


If you declare any variable as static, it is known as a static variable.
o The static variable can be used to refer to the common property of all objects
(which is not unique for each object), for example, the company name of
employees, college name of students, etc.
o Changes in variable will be reflected.
o The static variable gets memory only once in the class area at the time of class
loading.

Example of static variable


1. //Java Program to demonstrate the use of static variable
2. class Student{
3. int rollno;//instance variable
4. String name;
5. static String college ="ITS";//static variable
6. //constructor
7. Student(int r, String n){
8. rollno = r;
9. name = n;
10. }
11. //method to display the values
12. void display (){System.out.println(rollno+" "+name+" "+college);}
13. }
14. //Test class to show the values of objects
15. public class TestStaticVariable1{
16. public static void main(String args[]){
17. Student s1 = new Student(111,"Karan");
18. Student s2 = new Student(222,"Aryan");
19. //we can change the college of all objects by the single line of code
20. //Student.college="BBDIT";
21. s1.display();
22. s2.display();
23. }
24. }

Output:

111 Karan ITS


222 Aryan ITS
2) Java static method
If you apply static keyword with any method, it is known as static method.

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.

Example of static method


1. //Java Program to demonstrate the use of a static method.
2. class Student{
3. int rollno;
4. String name;
5. static String college = "ITS";
6. //static method to change the value of static variable
7. static void change(){
8. college = "BBDIT";
9. }
10. //constructor to initialize the variable
11. Student(int r, String n){
12. rollno = r;
13. name = n;
14. }
15. //method to display values
16. void display(){System.out.println(rollno+" "+name+" "+college);}
17. }
18. //Test class to create and display the values of object
19. public class TestStaticMethod{
20. public static void main(String args[]){
21. Student.change();//calling change method
22. //creating objects
23. Student s1 = new Student(111,"Karan");
24. Student s2 = new Student(222,"Aryan");
25. Student s3 = new Student(333,"Sonoo");
26. //calling display method
27. s1.display();
28. s2.display();
29. s3.display();
30. }
31. }
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

3) Java static block


o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading.

Example of static block


1. class A2{
2. static{System.out.println("static block is invoked");}
3. public static void main(String args[]){
4. System.out.println("Hello main");
5. }
6. }
Output:static block is invoked
Hello main

2.this keyword in Java


There can be a lot of usage of Java this keyword. In Java, this is a reference
variable that refers to the current object.

1.this can be used to refer current class instance variable.

Student(int rollno,String name,float fee){


this.rollno=rollno;
this.name=name;
this.fee=fee;
2.this can be used to invoke current class method (implicitly)

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

4.this can be passed as an argument in the method call.

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.

3.Java new Keyword


The Java new keyword is used to create an instance of the class. In other words, it
instantiates a class by allocating memory for a new object and returning a reference
to that memory. We can also use the new keyword to create the array object.

4.Final Keyword In Java


The final keyword in java is used to restrict the user. The java final keyword can be
used in many context. Final can be:

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 :

If you make any method as final, you cannot override it.

3. Final Class:

If you make any class as final, you cannot extend it.

5.Super Keyword in Java

1. super can be used to refer immediate parent class instance variable.

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();

3. super() can be used to invoke immediate parent class constructor.---super()


directly calls parent class constructor.

4.Java OOPs Concepts:

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).

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Types of inheritance in java


Note: Multiple inheritance is not supported in Java through class.

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:

a)Method Overloading in Java(compile time


polymorphism)
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments

static int add(int a,int b){return a+b;} //add(10,11);


static int add(int a,int b,int c){return a+b+c;} // add(10,11,12);
2. By changing the data type

static int add(int a, int b){return a+b;} // add(10,11);


static double add(double a, double b){return a+b;} // add(10.1,11.2);

Method Overloading is not possible by changing the return


type of method only?
In java, method overloading is not possible by changing the return type of the method only
because of ambiguity. Let's see how ambiguity may occur:

static double add(int a,int b){return a+b;} //add(10,20)→ ambiguity error


b)Method Overriding(Runtime polymorphism)
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a method which
is already provided by its superclass.

Example of method overriding:


class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}

Output:

Bike is running safely

Can we override static method?

No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we


will learn it later.

Why can we not override static method?

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.

Static Binding and Dynamic Binding


1. Static Binding (also known as Early Binding).

Dog d1=new Dog();

2. Dynamic Binding (also known as Late Binding).

Animal a=new Dog();

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.

Advantage of Encapsulation in Java


• By providing only a setter or getter method, you can make the class read-
only or write-only. In other words, you can skip the getter or setter methods.
• It provides you the control over the data. Suppose you want to set the value
of id which should be greater than 100 only, you can write the logic inside the
setter method. You can write the logic not to store the negative numbers in
the setter methods.
• It is a way to achieve data hiding in Java because other class will not be able
to access the data through the private data members.
• The encapsulate class is easy to test. So, it is better for unit testing.

Simple Example of Encapsulation in Java


File: Student.java

//A Java class which is a fully encapsulated class.


//It has a private data member and getter and setter methods.
package com.javatpoint;
public class Student{
//private data member
private String name;
//getter method for name
public String getName(){
return name;
}
//setter method for name
public void setName(String name){
this.name=name
}
}

File: Test.java

//A Java class to test the encapsulated class.


package com.javatpoint;
class Test{
public static void main(String[] args){
//creating instance of the encapsulated class
Student s=new Student();
//setting value in the name member
s.setName("vijay");
//getting value of the name member
System.out.println(s.getName());
}
}

d) Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.

Abstract class in Java

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.

abstract class Bike{


Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
bike is created
running safely..
gear changed

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.

Java Interface also represents the IS-A relationship.Features of Java - Javatpoint

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

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

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it
is known as multiple inheritance.

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");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();

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.

1. Java try...catch block


The try-catch block is used to handle exceptions in Java. Here's the syntax
of try...catch block:
public class TryCatchExample2 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

2. Java finally block


In Java, the finally block is always executed no matter whether there is an
exception or not.

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...");
}
}

3.Java throw keyword


The Java throw keyword is used to explicitly throw an exception.

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.

public class TestThrow1{


static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}

Output:

Exception in thread main java.lang.ArithmeticException:not valid

4.Java throws keyword


The Java throws keyword is used to declare an exception.

return_type method_name() throws exception_class_name{ //method body


}
Case1: You handle the exception
o In case you handle the exception, the code will be executed fine whether exception
occurs during the program or not.

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...

Case2: You declare the exception


o A)In case you declare the exception, if exception does not occur, the code will be
executed fine.
o B)In case you declare the exception if exception occures, an exception will be thrown
at runtime because throws does not handle the exception.

A)Program if exception does not occur


import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();

System.out.println("normal flow...");
}
}
Output:device operation performed
normal flow...

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs

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

3) A scenario where NumberFormatException occurs

The wrong formatting of any value may occur NumberFormatException. Suppose I


have a string variable that has characters, converting this variable into digit will occur
NumberFormatException.

1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException
IOException
import java.io.*;

class GFG {

// Define BufferedReader object


static BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));

// If you delete 'throws IOException'


// you will get an error
public static void main(String[] args)
throws IOException
{
int a = Integer.parseInt(br.readLine());
int b = Integer.parseInt(br.readLine());
System.out.println(a + b);
}
}

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;
}

Finalize is used to perform clean up processing just before object is garbage


collected and it is a method.

Finally is used to place important code, it will be executed whether exception is


handled or not and it is a block.

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.

Life cycle of a Thread

1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

How to create thread


There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

1) Java Thread Example by extending Thread class


class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output:thread is running...

2) Java Thread Example by implementing Runnable


interface
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output:thread is running...

Commonly used methods of Thread class:


o public void run(): is used to perform action for a thread.
o public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
o public void sleep(long miliseconds): Causes the currently executing thread to sleep
o public void join(): waits for a thread to die.
o public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
o public int getPriority(): returns the priority of the thread.
o public int setPriority(int priority): changes the priority of the thread.
o public String getName(): returns the name of the thread.
o public void setName(String name): changes the name of the thread.
o public Thread currentThread(): returns the reference of currently executing thread.
o public int getId(): returns the id of the thread.
o public Thread.State getState(): returns the state of the thread.
o public boolean isAlive(): tests if the thread is alive.
o public void yield(): causes the currently executing thread object to temporarily pause and allow ot
o public void suspend(): is used to suspend the thread(depricated).
o public void resume(): is used to resume the suspended thread(depricated).
o public void stop(): is used to stop the thread(depricated).
o public boolean isDaemon(): tests if the thread is a daemon thread.
o public void setDaemon(boolean b): marks the thread as daemon or user thread.
o public void interrupt(): interrupts the thread.
o public boolean isInterrupted(): tests if the thread has been interrupted.
o public static boolean interrupted(): tests if the current thread has been interrupted.
7)Java I/O Tutorial
Java I/O (Input and Output) is used to process the input and produce the output.

Java FileOutputStream Class:-

Java FileOutputStream is an output stream used for writing data to a file.

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...

The content of a text file testout.txt is set with the data A.

testout.txt

Java FileInputStream Class

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 BufferedInput/OutputStream Class


Java BufferedInputStream class is used to read information from stream.

It internally uses buffer mechanism to make the performance fast.

Java FileReader Class

Java FileReader class is used to read data from the file.

It returns data in byte format like FileInputStream class.

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:

ASCII value of Character is:35; Special character is: #


ASCII value of Character is:36; Special character is: $
ASCII value of Character is:37; Special character is: %
ASCII value of Character is:38; Special character is: &

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.

How to create a string object?


There are two ways to create String object:

o By string literal ---POOL CONSTANT


String s="welcome";
2.By new keyword------HEAP MEMORY

String s3=new String("example");

Immutable String in Java


String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
String s="Sachin";
s=s.concat(" Tendulkar"); // Sachin Tendulkar

o public boolean equals(Object another) compares this string


o public boolean equalsIgnoreCase(String another) compares this string ignoring case.
o The == operator compares references not 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.

String s1="java string";


s1.concat("is immutable");
System.out.println(s1); //java string
s1=s1.concat(" is immutable so assign it explicitly");
System.out.println(s1); //java string is immutable so assign it explicitly

3.contains()

String name="what do you know about me";


System.out.println(name.contains("about")); //true
System.out.println(name.contains("hello")); //false

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.

Syntax of forName() method


1. public static void forName(String className)throws ClassNotFoundExceptio
n
2) Create the connection object
The getConnection() method of DriverManager class is used to establish connection with the data

Syntax of getConnection() method


1. 1) public static Connection getConnection(String url)throws SQLException
2. 2) public static Connection getConnection(String url,String name,String passw
ord)
3. throws SQLException
Example to establish connection with the Oracle database
1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");

3) Create the Statement object


The createStatement() method of Connection interface is used to create statement. The object of stat
to execute queries with the database.

Syntax of createStatement() method


1. public Statement createStatement()throws SQLException
Example to create the statement object
1. Statement stmt=con.createStatement();

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to the database. This
object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method


1. public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
1. ResultSet rs=stmt.executeQuery("select * from emp");
2.
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically.

The close() method of Connection interface is used to close the connection.

Syntax of close() method


1. public void close()throws SQLException
Example to close connection
1. con.close();

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.

ArrayList<String> list=new ArrayList<String>();//Creating arraylist


list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());

LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to
store the elements. It can store the duplicate elements.

LinkedList<String> al=new LinkedList<String>();


al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());

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,

Stack<String> stack = new Stack<String>();


stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());

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.

1. PriorityQueue<String> queue=new PriorityQueue<String>();

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.

1. Deque<String> deque = new ArrayDeque<String>();

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.

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>();
Eg: HashSet<String> set=new HashSet<String>();
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.

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.

You might also like