java24.orgfree.com

Learn Java


Email: mehedihasanbahar@gmail.com

Cell: 01957 830934

web counter
Views
HOME INTERPRETERS

See your board exam result click here


Organization

Content menu:

1.Java-Object & Class
2.Polymorphism
3.Inheritance
4.Thread
5.Encapsulation
6.Static Binding
& Dynamic Binding

7.String
8.Array

Java(Object-Oriented Programming)

Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java supports the following fundamental concepts:

Java Keywords:

The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names.


abstract assert boolean break byte
case catch char class const
continue default do double else
enum extends final finally float
for goto if implements import
instanceof int interface long native
new package private protected public
return short static strictfp super
switch synchronized this throw -----------

Java-Object & Class(1st content)

1.1 Java:

Java is a programming language expressly designed for use in the distribute environment of the Internet.It was designed to have the "look and feel" of the C++ language, but it is simpler to use than C++ and enforces an object-oriented programming model.Java can be used to create complete applications- that may run on a single computer or be distributed among servers and clients in a network.It can also be used to build a small application module or applet for use as part of a web page.Applets make it po- ssible for a web page user to interact with the page.

1.2 Class:

A class can be defined as a template/blue print that describes the behaviors/states that object of its type support.

1.3 Object:

Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors-wagging, barking, eating. An object is an instance of a class.

1.4 Methods:

A method is basically a behaviour. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed

1.5 Instance Variables:

Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.

1.6 Java Modifiers:

Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers:

1.7 Java Variables:

We would see following type of variables in Java:

1.8 Let us look at a simple code that would print the words Hello World.


public class MyFirstJavaProgram { /* This is my first java program. * This will print 'Hello World' as the output */ public static void main(String []args) { System.out.println("Hello World"); // prints Hello World } }


A sample of a class is given below:


package Int; public class Main { //This is a class in this program// public static void main(String[] args) { int a = 12; int b = 24; int result = a + b; System.out.println( result); } }


A sample of a object is given below:


package Int; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner a = new Scanner(System.in); //Here "a" is a object// int num1 =a.nextInt(); Scanner b = new Scanner(System.in); //Here "b" is a object//
int num2 = b.nextInt(); int x = num1 + num2; System.out.println(x); } }


1.9 Use of java:

According to Sun, 3 billion devices run java. There are many devices where java is currently used. Some of them are as follows:

 Back 

Polymorphism(2nd content)

2.1 Polymorphism:

Polymorphism is the ability of an object to take on many forms.Polymorphism in java is a concept by which we can perform a single action by different ways.Polymorphism is derived from 2 greek words: poly and morphs.
The word "poly" means many and "morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.

If you overload static method in java, it is the example of compile time polymorphism. Here, we will focus on runtime polymorphism in java.

2.2 Runtime Polymorphism in Java:

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as upcasting.

For example:


1.class A{} 2.class B extends A{} class A{} class B extends A{} 1.A a=new B();//upcasting A a=new B();//upcasting


Example of Java Runtime Polymorphism
In this example, we are creating two classes Bike and Splendar. Splendar class extends Bike class and over- rides its run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, subclass method is invoked at runtime.

Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.

For example:


class Bike{ void run(){System.out.println("running");} } class Splender extends Bike{ void run()1.class Bike{ {System.out.println("running safely with 60km");} public static void main(String args[]){ Bike b = new Splender();//upcasting b.run(); } }


Test it Now
Output:running safely with 60km.

2.3 Java Runtime Polymorphism with data member

Method is overridden not the datamembers, so runtime polymorphism can't be achieved by data members.

In the example given below, both the classes have a datamember speedlimit, we are accessing the datamember by the reference variable of Parent class which refers to the subclass object. Since we are accessing the datamember which is not overridden, hence it will access the datamember of Parent class always.

Note: Runtime polymorphism can't be achieved by data members.


class Bike{ int speedlimit=90; } class Honda3 extends Bike{ int speedlimit=150; public static void main(String args[]){ Bike obj=new Honda3(); System.out.println(obj.speedlimit);//90 }


 Back 

Inheritance(3rd content)

3.1 Inheritance :

Inheritance can be defined as the process where one class acquires the properties (methods and fiels) of another.With the use of inheritance the information is made manageable in a hierarchical order.

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

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 parent class, and you can add new methods and fields also.

The class which inherits the properties of other is known as subclass(derived class child class) and the class whose properties are inherited is known as superclass (base class,parent class).

For example:


class A{ ------------ ------------ } // This is base class// class B extends A{ --------------- --------------- } //This is parent class//


Inheritance represents the IS-A relationship, also known as parent-child relationship.

3.2 Why use inheritance in java:

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

3.3 IS-A Relationship:

IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance.

Example:


public class Car{ } public class Transport extends Car{ } public class Bus extends Car{ } public class Motor-bike extends Car{ }


Now, based on the above example, In Object Oriented terms, the following are true −

Now, if we consider the IS-A relationship, we can say −

With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass.

We can assure that Transport is actually an Car with the use of the instance operator.

3.4 HAS-A relationship:

These relationships are mainly based on the usage. This determines whether a certain class HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs.

Lets us look into an example −


public class Vehicle{} public class Speed{} public class Van extends Vehicle{ private Speed sp; }


This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to put the entire code that belongs to speed inside the Van class., which makes it possible to reuse the Speed class in multiple applications.

In Object-Oriented feature, the users do not need to bother about which object is doing the real work. To achieve this, the Van class hides the implementation details from the users of the Van class. So basically what happens is the users would ask the Van class to do a certain action and the Van class will either do the work by itself or ask another class to perform the action.

3.5 Types of inheritance:

There are various types of inheritance as demonstrated below.



3.6 Extends:

Extends mean that the class is an extention of another class and inherits all of it's attributes, properties, and method

Extends Keyword

Extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends keyword.

Example:


class Super{ ------- ------- } class Sub extends Super{ ------- ------- }


Example of single inheritance:


package TEST; class A { public int a = 12; public int b = 14; int result = a + b; } class B extends A { public int c = 16; public int d = 18; int result1 = c + d; } public class MAIN { public static void main(String[] args) { B m1 = new B(); System.out.println(m1.result+" "+m1.result1); } }


3.7 Multiple inheritance in Java by interface

Firstly we will know what is interface:

3.8 Interface :

An interface is a collection of method signatures that are defined.Objects can indicate that they implement an interface this means they agree to provide the methods that apper in the interface.

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

For example:


package RAF; interface A{ public String a = "I am Mehedi hasan."; public void setA(); } interface B{ public String b = "I am a boy."; public void setB(); } class C implements A,B { String c = "I read in class five."; public void setA() { System.out.println("a="); } public void setB() { System.out.println("b="); } public void display() { System.out.println(a+b+c); } } public class Main { public static void main(String[] args){ C a = new C(); a.display(); } }


 Back 

Thread(4th content)

4.1 Thread:

Thread is the part of a program that run different ways.

All programmers are familiar with writing sequential programs. You've probably written a program that displays "Hello World!", or sorts a list of names, or computes a list of prime numbers. These are sequential programs: each has a beginning, an execution sequence, and an end. At any given time during the runtime of the program there is a single point of execution.

A thread is similar to the sequential programs described above: a single thread also has a beginning, an end, a sequence, and at any given time during the runtime of the thread there is a single point of execution. However, a thread itself is not a program. It cannot run on its own, but runs within a program.

4.2 Definition:

A thread is a single sequential flow of control within a program.
or
A thread--sometimes known as an execution context or a lightweight process--is a single sequential flow of control within a process.

Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It shares a common memory area.

As shown in the above figure, thread is executed inside the process. There is context-switching between the threads. There can be multiple processes inside the OS and one process can have multiple threads.

4.3 There are two ways to create a thread:

4.4 Thread class:

Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

Example of extends thread:


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


4.5 Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run().

public void run(): is used to perform action for a thread.

Starting a thread:

start() method of Thread class is used to start a newly created thread. It performs following tasks:

Example of runnable interface:


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


4.6 Types of thread:

Thread are two types-

4.7 Single thread:

Thread is the part of a program.A thread have a one control flow.Every thread's program have minimum one thread.And this program is called single thread.Single thread construct with one base class and one main class.

Is it...only one thread/one instance at a time
or
is it...one thread/instance at a time.

Now we see a example of single thread:


package Mehedi; class Ringchips extends Thread{ public void run() { int a[] = {1,2,3,4,5}; for (int i=0;i<5;i++) { System.out.println(a[i]); } } } public class Water { public static void main(String[]args){ System.out.println("Main start."); for (int i=0;i<5;i++) { System.out.println("Mehedi Hasan"); } Ringchips a = new Ringchips(); a.start(); } }


4.8 Multi Thread:

Java is a multi threaded programming language which means we can develop multi threaded program using java. A multi threaded program contains two or more parts that can run concurrently and each part can handle diff- erent task at the same time making optional use of the available resources specially when your computer has multiple CPUs.

Multithreading in java is a process of executing multiple threads simultaneously.

Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.

But we use multithreading than multiprocessing because threads share a common memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.

4.9 Advantage of Java Multithreading:

4.10 Multitasking:

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU.
Multitasking can be achieved by two ways:

Example of multi thread:


package Thread; class Dhaka extends Thread{ public void run() { for(int i=1;i<=4;i++) { System.out.println("inside thread Dhaka"); } } } class Comilla extends Thread{ public void run() { int a = 10; int b = 20; int result1 = a+b; for(int i=1;i<=4;i++) { System.out.println("inside thread Comilla ="+result1); } } } public class MAIN05 { public static void main(String[] args) { System.out.println("Start thread program"); Dhaka d1 = new Dhaka(); Comilla c1 = new Comilla(); d1.start(); c1.start(); } }


4.11 Life cycle of thread:

The life cycle of the thread in java is controlled by JVM.

The java thread states are as follows:

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

1.New

The thread is in new state if you create an instance of Thread class but before the invocation of start() method.

2.Runnable

The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.

3.Running

The thread is in running state if the thread scheduler has selected it.

4.Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated(Dead)

A thread is in terminated or dead state when its run() method exits.

 Back 

Encapsulation(5th content)

5.1 Encapsulation:

Encapsulation is the machanism that binds together code and the data it manipulates,and keeps both safe from out- side interference and misuse.One way to think about encapsulation is as a protective wrapper that prevents the code and data from being arbitrarily accessed by other code defined outside the wrapper.

When we design the class we essentially write encapsulation rules. We achieve data encapsulation in java by using access modifiers - Public, Protected, default, Private.

We define functions or variables with some access modifier to control the scope that can be used or accessed by the user. For Example: Class is a example of Encapsulation.

5.2 To achieve encapsulation in Java:

1.Declare the variables of a class as private.
2.Provide public setter and getter methods to modify and view the variables values.

5.3 Advantage of Encapsulation:

Example:


package Raf01; import java.util.Scanner; public class Tom { public static void main(String[] args) { int add,substraction,multiplication; float divide; for(;;) { System.out.println("Enter anumber :"); Scanner x = new Scanner(System.in); int a = x.nextInt(); int b = x.nextInt(); add = a + b; substraction = a - b; multiplication = a * b; divide = a /(float)b; System.out.println(add); System.out.println(substraction); System.out.println(multiplication); System.out.println(divide); } } }


 Back 

Static Binding & Dynamic binding(6th content)

6.1 Binding:

Association of method definition to the method call is known as binding.

or

Connecting a method call to the method body is known as binding.

6.2 Static binding:

When type of the object is determined at the compiled time (by the compiler), it is known as static binding.

Static binding is a binding which happens during com-pilation.It is also called early binding because binding happ- ens before a program actually runs.

If there is any private, final or static method in a class,there is static binding.

Example:


package ctg; public static void main(String[]args){ class Human{ .... } class Boy extends Human{ public void walk(){ System.out.println("Boy walks"); } public static void main( String args[]) { Boy obj1 = new Boy(); obj1.walk(); } } }


6.3 Dynamic binding:

When type of the object is determined at run-time, it is known as dynamic binding.

Dynamic binding is a binding which happens during run time. It is also called late binding because binding happens when program actually is running.

Example:


public class Dynamic { public static void main(String args[]) { Vehicle vehicle = new Car(); //here Type is vehicle but object will be Car vehicle.start(); //Car's start called because start() is overridden method } } class Vehicle { public void start() { System.out.println("Inside start method of Vehicle"); } } class Car extends Vehicle { @Override public void start() { System.out.println("Inside start method of Car"); } }


6.4 Here are few important difference between static and dynamic binding:

1.variables have a type:

Each variable has a type, it may be primitive and non-primitive.

Example:

int data=30;

Here data variable is a type of int.

2.References have a type:

Example:


class Dog{ public static void main(String args[]){ Dog d1;//Here d1 is a type of Dog } }


3.Objects have a type:

An object is an instance of particular java class,but it is also an instance of its superclass.

Example:


class Animal{} class Dog extends Animal{ public static void main(String args[]){ Dog d1=new Dog(); } }


Here d1 is an instance of Dog class, but it is also an instance of Animal.

 Back 

String(7th content)

7.1 String:

String, which are widely used in java programming, are a sequence of characters.In java programming language, string are object.

The java platform provides the String class to create and manipulate string.

In java, string is basically an object that represents sequence of char values.

7.2 Creating a String object:

There are two ways to create a String in Java

1.By string literal

Java String literal is created by using double quotes.

For Example:

String s="welcome";

Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string instance is created and placed in the pool.

For Example:


String s1="Welcome"; String s2="Welcome"; //will not create new instance


In the above example only one object will be created.

Note:

String objects are stored in a special memory area known as string constant pool.

Concept of string literal:

To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).

2.Using new keyword:

Example:


Scanner b = new Scanner (System.in); int num2 = b.nextInt(); or String s=new String("Welcome"); //creates two objects and one reference variable


In such case, JVM will create a new string object in normal(non pool) heap memory and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap(non pool).

Example:


package string; public class Dhaka { public static void main(String[] args) { String a = "I am Nabil."; String b = " I read in TMU. "; String result = a + b; System.out.println(result); } }



package String02; public class Java { public static void main(String[] args) { String S1 = new String("This is"); String S2 = "Java class"; String S3; int l,c,i=3,index; char ch; System.out.println(S1); l = S1.length(); System.out.println(l); //Returns the length of this string. S3 = S1.concat(S2); System.out.println(S3); //Concatenates the specified string to the end of this string. c = S1.compareTo(S2); System.out.println(c); //Compares two strings lexicographically. ch = S1.charAt(i); System.out.println(ch); //Returns the character at the specified index. S3 = S1.replace('T','D'); //Returns a new string resulting from replacing all occurrences of oldChar in this System.out.println(S3); string with newChar. index = S1.indexOf('h'); //Returns the index within this string of the rightmost occurrence of the specified System.out.println(indeex); substring S3 = S1.toUpperCase(); //Converts all of the characters in this String to upper case using the rules of the given System.out.println(S3); Locale. S3 = S1.toLowerCase(); //Converts all of the characters in this String to lower case using the rules of the given Locale. System.out.println(S3); S3 = S1.substring(5); System.out.println(S3); //Returns a new string that is a substring of this string. String P = new StringBuffer(S1).reverse().toString(); System.out.println(P); } }


 Back 

Array(8th content)

8.1 Array:

Normally, array is a collection of similar type of elements that have contiguous memory location.

Java array is an object the contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed set of elements in a java array.

8.2 Creating Arrays:

We can create an array by using the new operator with the following syntax:

arrayRefVar = new dataType[arraySize];

The above statement does two things:

Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement.

Example:

dataType[] arrayRefVar = new dataType[arraySize]

8.3 Advantage of Java Array:

Code Optimization: It makes the code optimized, we can retrieve or sort the data easily. Random access: We can get any data located at any index position.

8.4 Disadvantage of Java Array:

Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.

8.5 Types of Array in java:

There are two types of array.

Single Dimensional Array in java:

Syntax to Declare an Array in java


dataType[] arr; (or) dataType []arr; (or) dataType arr[];


Instantiation of an Array in java:

arrayRefVar=new datatype[size];

Example of single dimensional java array:

Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an array.

package String; public class Array { 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; for(int i=0;i<=3;i++) System.out.println(a[i]); //printing array } }


8.6 Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:


int a[]={33,3,4,5};//declaration, instantiation and initialization


Let's see the simple example to print this array.


package String; public class Array2 { public static void main(String[] args) { // TODO Auto-generated method stub int a[]={33,3,4,5};//declaration, instantiation and initialization //printing array for(int i=0;i<=3;i++) //length is the property of array System.out.println(a[i]); } }


Multidimensional array in java:

In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in java:


dataType[][] arrayRefVar; (or) dataType [][]arrayRefVar; (or) dataType arrayRefVar[][]; (or) dataType []arrayRefVar[];


Example to instantiate Multidimensional Array in java

int[][] arr=new int[3][3]; //3 row and 3 column

Example to initialize Multidimensional Array in java


arr[0][0]=1; arr[0][1]=2; arr[0][2]=3; arr[1][0]=4; arr[1][1]=5; arr[1][2]=6; arr[2][0]=7; arr[2][1]=8; arr[2][2]=9;


Example of Multidimensional java array

Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.


class Testarray3{ public static void main(String args[]){ //declaring and initializing 2D array int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; //printing 2D array for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ System.out.print(arr[i][j]+" "); } System.out.println(); } } }


Example of arraycopy method:


class TestArrayCopyDemo { public static void main(String[] args) { char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' }; char[] copyTo = new char[7]; System.arraycopy(copyFrom, 2, copyTo, 0, 7); System.out.println(new String(copyTo)); } }


 Back 

See board exam result

Top[^] 

 

THE END

Created by: Syed Mehedi Hasan...

Free Web Hosting