Java Programming Notes 8
Java Programming Notes 8
● Normally, an array is a collection of similar type of elements which has contiguous memory location.
● Java array is an object which contains elements of a similar type. Additionally, The elements of an array
are stored in a contiguous memory location. It is a data structure where we store similar elements. We can
store only a fixed set of elements in a Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
import java.util.Arrays;
}}
class Test2 {
public static void main(String[] args)
{
String str[] = { "Christ", "University", "Bangalore" };
System.out.println(str.length);
System.out.println(str[0].length);
} class Test4 {
} public
static void main(String[] args)
{
int number = 11;
int NUMBER = 22;
int Number = 33;
System.out.print(number + " ");
System.out.print(NUMBER + " ");
System.out.println(Number);
}
}
class Test1 {
public
static void main(String[] args)
{
int arr[] = { 11, 22, 33 };
System.out.print(arr[-2]);
}
}
class Test2 { class Test2 {
public public
static void main(String[] args) static void main(String[] args)
{ {
int arr[][] = { { 11, 22 }, { 33, 44, 55 } }; int arr[][] = { { 11, 22 }, { 33, 44, 55 } };
for (int i = 0; i < 2; i++) { for (int i = 0; i < 2; i++) {
for (int j = 0; j < arr.length; j++) for (int j = 0; j < arr[i].length; j++)
System.out.print(arr[i][j] + " "); System.out.print(arr[i][j] + " ");
System.out.println(); System.out.println();
} }
} }
} }
Method Overloading in Java
● If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.In short multiple methods with same name but with different signatures.
For example the signature of method add(int a, int b) having two int parameters is different from
signature of method add(int a, int b, int c) having three int parameters.
● This is one of the most popular OOP feature in java, there are several cases where we need more
than one methods with same name. For example let’s say we are writing a java program to find
the sum of input numbers, we need different variants of add method based on the user inputs
such as add(int, int), add(float, float) etc.
In order to overload a method, the parameter list of the methods must differ in either of these:
1. Number of parameters.
For example:
add(int, int)
add(int, float)
3. Sequence of Data type of parameters.
For example:
add(int, float)
add(float, int)
Invalid case of method overloading:
Parameters list doesn’t mean the return type of the method, for example if two methods have
same name, same parameters and have different return type, then this is not a valid method
overloading example. This will throw a compilation error.
Case 1:
int mymethod(int a, int b, float c)
int mymethod(int var1, int var2, float var3)
Case 2:
int mymethod(int a, int b)
int mymethod(float var1, float var2)
Case 3:
Case 4:
Case 5:
class DisplayOverloading
{
int add(int a, int b)
{
int sum = a+b;
return sum;
}
int add(int a, int b, int c)
{
int sum = a+b+c;
return sum;
}}
class JavaExample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
System.out.println(obj.add(10, 20));
System.out.println(obj.add(10, 20, 30));
}}
Example 2: Overloading – Data type of parameters are different
class DisplayOverloading2
{
public int add(int a, int b)
{
int sum = a+b;
return sum;
}
public float add(float a, float b)
{
float sum = a+b;
return sum;
}}
class JavaExample
{
public static void main(String args[])
{
DisplayOverloading2 obj = new DisplayOverloading2();
System.out.println(obj.add(5, 15));
System.out.println(obj.add(5.5f, 2.5f));
}}
Example3: Overloading – Sequence of data type of parameters is different
class DisplayOverloading3
{
public float add(int a, float b)
{
System.out.println("Method with (int, float) param list.");
return a+b;
}
public float add(float a, int b)
{
System.out.println("Method with (float, int) param list.");
return a+b;
}}
class JavaExample
{
public static void main(String args[])
{
DisplayOverloading3 obj = new DisplayOverloading3();
System.out.println(obj.add(10, 10.5f));
System.out.println(obj.add(1.5f, 1));
}}
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.
● It calls a default constructor if there is no constructor available in the class. In such case, Java compiler
provides a default constructor by default.
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
‘this’ in JAVA
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
this: to invoke current class method
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
this() : 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);
}}
class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[]){
A a=new A();
}}
class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno;
this.name=name;
this.course=course; }
Student(int rollno,String name,String course,float fee){
this(rollno,name,course);//reusing constructor
this.fee=fee; }
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
}
class TestThis7{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
}}
class Teak
{
Teak()
{
this(5);
System.out.println("Default Constructor");
}
Teak(int x)
{
this(5,20);
System.out.println(x);
}
Teak(int x,int y)
{
System.out.println(x*y);
}
public static void main(String args[])
{
new Teak();
}}
class Teak
{
Teak()
{
System.out.println("Default Constructor");
}
Teak(int x)
{
this();
System.out.println(x);
}
Teak(int x,int y)
{
this(5);
System.out.println(x*y);
}
public static void main(String args[])
{
new Teak(8,10);
}}
public class MainMethodOverload2
{
//original main() method
public static void main(String args[])
{
MainMethodOverload mmo= new MainMethodOverload ();
//calling overloaded main() method from the original main() method
mmo.main();
}
//overloaded main() method
public static void main()
{
System.out.println("Overloaded main() method invoked");
}
}
public class MainMethodOverload3
{
public static void main(boolean args) {
if (args) {
System.out.println("First overloaded main() method executed");
System.out.println(args);
}}
public static void main(String str) {
System.out.println("Second overloaded main() method executed");
System.out.println(str);
}
public static void main(int args) {
System.out.println("Third overloaded main() method executed");
System.out.println(args);
}
public static void main(String[] args) {
System.out.println("Original main() method executed");
System.out.println("Hello");
MainMethodOverload3.main(true);
MainMethodOverload3.main("mango");
MainMethodOverload3.main(112);
}}
Java – Static Class, Block, Methods and Variables
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:
// static block
static {
System.out.println("Static block initialized.");
b = a * 4;
}
static {
System.out.println("Inside static block");
}
static int m1() {
System.out.println("from m1");
return 20;
}
public static void main(String[] args)
{
System.out.println("Value of a : "+a);
System.out.println("from main");
}
}
class Test
{
static int a = 10;
int b = 20;
static void m1()
{
a = 20;
System.out.println("from m1");
b = 10;
m2();
}
void m2()
{
System.out.println("from m2");
}
public static void main(String[] args)
{
}
}
class Test1 {
public static void main(String[] args)
{
int x = 20;
System.out.println(x);
}
static
{
int x = 10;
System.out.print(x + " ");
}
}
class Test1 {
int x = 10;
public static void main(String[] args)
{
System.out.println(x);
}
static
{
System.out.print(x + " ");
}
}
class Test1 {
int x = 10;
public static void main(String[] args)
{
Test1 t1 = new Test1();
System.out.println(t1.x);
}
static
{
int x = 20;
System.out.print(x + " ");
}
}
class Basic2
{
Basic2()
{
System.out.print("Inside Constructor. "); }
{
System.out.print("Inside the instance block. ");
}
static
{
System.out.print("Inside the static block. ");
} }
class Main
{
public static void main(String argvs[])
{
Basic2 obj = new Basic2();
}}
public class interview
{
public static void main(String[] arr)
{
System.out.println("first main");
}
public static void main(String arr)
{
System.out.println("second main");
}
}
public class Solution{
public static void main(String[] args){
int[] x = {120, 200, 016};
for(int i = 0; i < x.length; i++){
System.out.print(x[i] + "\n" );
}
}
}
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).
The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When
you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add
new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Class: A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived
class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is
also called a base class or a parent class.
Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the
fields and methods of the existing class when you create a new class. You can use the same fields
and methods already defined in the previous class.
The syntax of Java 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();
}}
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given
below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel
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();
}}
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given
below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel
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();
}}
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given
below, Dog and Cat classes inherits the Animal class, so there is 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();
}}
Why multiple inheritance is not supported in java?
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
A a = new A();
System.out.println(a.x);
A a2 = new B();
System.out.println(a2.x);
}
}
class A
{
{
System.out.println(1);
}}
class B extends A
{
{
System.out.println(2);
}}
class C extends B
{
{
System.out.println(3);
}}
public class MainClass
{
public static void main(String[] args)
{
C c = new C();
}}
class A
{
int i = 10;
}
class B extends A
{
int i = 20;
}
System.out.println(a.i);
}
}
Super Keyword in Java
The super keyword in Java is a reference variable which is used to refer
immediate parent class object.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
super is used to invoke parent class constructor.
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
super is 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);
System.out.println(super.color);
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
System.out.println("dog is created");
}
}
class TestSuper4{
public static void main(String args[]){
Dog d=new Dog();
}}
super example: real use
class Person{
int id;
String name;
Person(int id,String name){
this.id=id;
this.name=name;
} }
class Emp extends Person{
float salary;
Emp(int id,String name,float salary){
super(id,name);//reusing parent constructor
this.salary=salary;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
class TestSuper5{
public static void main(String[] args){
Emp e1=new Emp(1,"ankit",45000f);
e1.display();
}}
Abstract class in Java
● A class which is declared with the abstract keyword is known as an abstract class in Java. It can have
abstract and non-abstract methods (method with the body).
● Before learning the Java abstract class, let's understand the abstraction in Java first.
Abstraction in Java
● Abstraction is a process of hiding the implementation details and showing only functionality to the user.
● Another way, it shows only essential things to the user and hides the internal details, for example, sending
SMS where you type the text and send the message. You don't know the internal processing about the
message delivery.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
abstract class Shape{
abstract void draw();
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();
s.draw();
}
}
abstract class Bank{
abstract int getRateOfInterest();
}
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}}
Abstract class having constructor, data member and methods
An abstract class can have a data member, abstract method, method body (non-abstract method), constructor,
and even main() method.
● 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.
● In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method
body.Java Interface also represents the IS-A relationship.
An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in
an interface are declared with the empty body, and all the fields are public, static and final by default. A class
that implements an interface must implement all the methods declared in the interface.
Syntax:
interface <interface_name>{
}
Java Interface Example
In this example, the Printable interface has only one method, and its
implementation is provided in the A6 class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
}
}
Java 8 Default Method in Interface
Since Java 8, we can have method body in interface. But we need to make it default method. Let's see an
example:
File: TestInterfaceDefault.java
interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}
What is Exception Handling
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the unchecked
exception. According to Oracle, there are three types of exceptions:
• Checked Exception
• Unchecked Exception
• Error
Java Exception Keywords
There are 5 keywords which are used in handling exceptions in Java.
Keyword Description
try The "try" keyword is used to specify a block where we should place exception code. The try
block must be followed by either catch or finally. It means, we can't use try block alone.
catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the important code of the program. It is executed
whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It
specifies that there may occur an exception in the method. It is always used with method
signature.
public class TryCatchExample1 {
}
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Common Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur. They are as follows:
}
public class TryCatchExample6 {
public static void main(String[] args) {
int i=50;
int j=0;
int data;
try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block
System.out.println(i/(j+2));
}
} }
public class TryCatchExample8 {
}
// try to handle the ArithmeticException using ArrayIndexOutOfBoundsException
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
public class TryCatchExample9 {
}
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
} }
public class MultipleCatchBlock3 {
try{
int a[]=new int[5];
a[5]=30/0;
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
public class MultipleCatchBlock4 {
try{
String s=null;
System.out.println(s.length());
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
class MultipleCatchBlock5{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){
System.out.println("common task completed");
}
catch(ArithmeticException e){
System.out.println("task1 is completed");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("task 2 completed")
;}
System.out.println("rest of the code...");
} }
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
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...");
}
}
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
super(str); } }
class TestCustomException1
{
static void validate (int age) throws InvalidAgeException{
if(age < 18){
throw new InvalidAgeException("age is not valid to vote");
}
else {
System.out.println("welcome to vote"); } }
public static void main(String args[])
{
try { validate(13); }
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");
System.out.println("Exception occured: " + ex);
}
System.out.println("rest of the code..."); } }
Java Threads
Typically, we can define threads as a subprocess with lightweight with the smallest unit of processes and also has separate
paths of execution. These threads use shared memory but they act independently hence if there is an exception in threads that
do not affect the working of other threads despite them sharing the same memory.
Thread State Transition Diagram
There are two ways to create a thread:
Priority: Priority of each thread lies between 1 to 10. If a thread has a higher priority, it
means that thread has got a better chance of getting picked up by the thread scheduler.
Time of Arrival: Suppose two threads of the same priority enter the runnable state, then
priority cannot be the factor to pick a thread from these two threads. In such a case, arrival
time of thread is considered by the thread scheduler. A thread that arrived first gets the
preference over the other threads.
Thread.sleep() in Java with Examples
The Java Thread class provides the two variant of the sleep() method. First one accepts only an arguments,
whereas the other variant accepts two arguments. The method sleep() is being used to halt the working of a thread
for a given amount of time. The time up to which the thread remains in the sleeping state is known as the sleeping
time of the thread. After the sleeping time is over, the thread starts its execution from where it has left.
t1.start();
t2.start();
}
}
Can we start a thread twice
No. After starting a thread, it can never be started again. If you does so, an
IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will
throw exception.
The join() method in Java is provided by the java.lang.Thread class that permits one thread to wait until the other thread to finish
its execution. Suppose th be the object the class Thread whose thread is doing its execution currently, then the th.join(); statement
ensures that th is finished before the program does the execution of the next statement. When there are more than one thread
invoking the join() method, then it leads to overloading on the join() method that permits the developer or programmer to
mention the waiting period.However, similar to the sleep() method in Java, the join() method is also dependent on the operating
system for the timing, so we should not assume that the join() method waits equal to the time we mention in the parameters. The
following are the three overloaded join() methods.
join(): When the join() method is invoked, the current thread stops its execution and the thread goes into the wait state. The
current thread remains in the wait state until the thread on which the join() method is invoked has achieved its dead state. If
interruption of the thread occurs, then it throws the InterruptedException.
public class Threadjoiningmethod extends Thread{
public void run(){
for(int i=1;i<=4;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}}
public static void main(String args[]){
Threadjoiningmethod th1=new Threadjoiningmethod ();
Threadjoiningmethod th2=new Threadjoiningmethod ();
Threadjoiningmethod th3=new Threadjoiningmethod ();
th1.start();
try{
th1.join();
}
catch(Exception e){
System.out.println(e);
}
th2.start();
th3.start();
} }
class ThreadJoin extends Thread
{
public void run()
{
for (int j = 0; j < 2; j++)
{
try { Thread.sleep(300);
System.out.println("The current thread name is: " + Thread.currentThread().getName()); }
catch(Exception e)
{
System.out.println("The exception has been caught: " + e);
}
System.out.println( j );
} } }
public class ThreadJoin1
{
public static void main (String argvs[])
{
ThreadJoin th1 = new ThreadJoin();
ThreadJoin th2 = new ThreadJoin();
ThreadJoin th3 = new ThreadJoin();
th1.start();
try { System.out.println("The current thread name is: "+ Thread.currentThread().getName());
th1.join(); }
catch(Exception e)
{
System.out.println("The exception has been caught " + e);
}
th2.start();
try {
System.out.println("The current thread name is: " + Thread.currentThread().getName());
Java Thread Priority in Multithreading
Priorities in threads is a concept where each thread is having a priority which in layman’s language
one can say every object is having priority here which is represented by numbers ranging from 1 to
10.
t1.start();
t2.start();
t3.start();
}
}
public class A implements Runnable
{
public void run()
{
System.out.println(Thread.currentThread()); // This method is static.
}
public static void main(String[] args)
{
A a = new A();
Thread t = new Thread(a, "NewThread");
t.setPriority(2); // Setting the priority of thread.
● Package in java 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.
● Here, we will have the detailed learning of creating and using user-defined packages.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to access package from another package?
There are three ways to access the package from outside the package.
● import package.*;
● import package.classname;
● fully qualified name.
class StaticImportDemo
{
public static void main(String args[])
{
out.println("Christ University");
}
}
Access Modifiers in Java
Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
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.
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.
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.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is a compile-time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
//save by B.java
//save by A.java package mypack;
package pack; import pack.*;
class A{ class B{
void public static void main(String args[]){
msg(){System.out.println("Hello");} A obj = new A();//Compile Time Error
} obj.msg();//Compile Time Error
}
}
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.
● It provides more accessibility than the default modifer.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
`
In Java, streams are the sequence of data that are read from the source and written to the
destination.
An input stream is used to read data from the source. And, an output stream is used to write data
to the destination.
Types of Streams
Depending upon the data a stream holds, it can be classified into:
● Byte Stream
● Character Stream
Byte Stream
Byte stream is used to read and write a single byte (8 bits) of data.
All byte stream classes are derived from base abstract classes called InputStream and OutputStream.
Character Stream
All the character stream classes are derived from base abstract classes Reader and Writer.
import java.io.FileOutputStream;
public class FileWrite {
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);}
}
}
import java.io.FileOutputStream;
public class FileWrite {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to Christuniversity.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
import java.io.FileInputStream;
public class FileRead1 {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=fin.read();
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
import java.io.FileInputStream;
public class FileRead2 {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("s1.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}} }}
import java.io.*;
public class CopyFile {
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}}}}
public class BufferedReaderExample{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}