Академический Документы
Профессиональный Документы
Культура Документы
Java
TABLE OF CONTENTS
Chapter Search Topic
CHAPTER 1 ............................................................................. #
STRING TOPIC Complex programs
SECTION 1.1 ...........................................................................................#
Subsection 1.1.a ...............................................................................# FILE I/O TOPIC
Subsection 1.1.b ...............................................................................#
Subsection 1.1.c................................................................................# THREAD TOPIC
SECTION 1.2 ...........................................................................................#
SECTION 1.3 ...........................................................................................# CLASS TOPIC
CHAPTER 2 ............................................................................. #
SECTION 2.1 ...........................................................................................# INHERITANCE TOPIC
SECTION 2.2 ...........................................................................................#
Subsection 2.2.a ...............................................................................#
CONSTRUCTOR TOPIC
Subsection 2.2.b ...............................................................................#
OBJECT TOPIC
Subsection 2.2.c................................................................................#
Use Ctrl+F
SECTION 2.3 ...........................................................................................# METHOD TOPIC
CHAPTER 3 ............................................................................. #
SECTION 3.1 ...........................................................................................# POLYMORPHISM TOPIC
SECTION 3.2 ...........................................................................................#
SECTION 3.3 ...........................................................................................# 6+ EXCEPTION TOPIC
Subsection 3.3.a ...............................................................................#
Subsection 3.3.b ...............................................................................# ENCAPSULATION TOPIC
Subsection 3.3.c .....................................................................................#
PACKAGES, INHERITANCE AND INTERFACES TOOPIC
CHAPTER 3 ............................................................................. #
SECTION 3.1 ...........................................................................................# STATIC KEYWORD TOPIC
SECTION 3.2 ...........................................................................................#
SECTION 3.3 ...........................................................................................# ABSTRACT KEYWORD TOPIC
Subsection 3.3.a ...............................................................................#
Subsection 3.3.b ...............................................................................#
Subsection 3.3.c .....................................................................................#
CHAPTER 3 ............................................................................. #
SECTION 3.1 ...........................................................................................#
SECTION 3.2 ...........................................................................................#
SECTION 3.3 ...........................................................................................#
Subsection 3.3.a ...............................................................................#
Subsection 3.3.b ...............................................................................#
Subsection 3.3.c .....................................................................................#
Link
http://www.programmingsimplified.com/java/source-code/java-
Web resource tutorials http://www.c4learn.com/javaprogramming/
hello-world-program
http://www.similarsites.com/site/c4learn.com
Background colors
RGB Color RGB Color
Color sample Color sample
code code
234, 224, 215 200, 213, 204
209, 187, 211 213, 241, 179
172, 185, 202 190, 225, 192
199, 208, 219 227, 215, 229
208, 208, 207 191, 222, 198
2
Importance of topics
3
To compile To execute
javac Welcome.java java Welcome
Lecture 2
5
(9/29/2014)
tools NetBeans ide 8.1 link https://netbeans.org/downloads/
File create File > new Project > java > java Application > project name + project location > finish
Class
Member
Variable
Class
Member
Member
Function
1. Name starts with a uppercase
Class naming conventions/rules 2. Main class name = file name
package class2;
import java.io.*;
package class2;
}
}
High
1. Compile 2. Convert machine code to electric signal
Program process
Low
Run Execute Interprete Starts from main()
Output
1.
/* This is a
Comments // This is a single line comment
Multiline comment */
Lecture 3
(Wednesday, October 01, 2014)
package class3;
import java.util.Scanner;
if(input %2 == 0)
{
System.out.println(input +" is even...");
}
else
System.out.println(input +" is odd ");
}
}
Function calling
Wrong Process Process one Process two
package class3;
package class3; package class3;
import java.util.Scanner;
import java.util.Scanner; class OddEvenCheck import java.util.Scanner;
{ class OddEvenCheck
public class OddEvenCheckWithFuncCall int oddeven(int input) {
{ { int oddeven(int input)
int oddeven(int input) if(input %2 == 0) {
{ { if(input %2 == 0)
if(input %2 == 0) System.out.println(input +" is even..."); return 1;
{ } else
System.out.println(input +" is even..."); else return 0;
} System.out.println(input +" is odd "); }
else return 0; }
System.out.println(input +" is odd "); } public class OddEvenCheckWithFuncCall
7
return 0; } {
} public class OddEvenCheckWithFuncCall public static void main(String args[])
{ {
public static void main(String args[]) public static void main(String args[]) System.out.print("Entert a number to check odd/even = ");
{ { Scanner sc = new Scanner(System.in);
System.out.print("Entert a number to check odd/even = "); System.out.print("Entert a number to check odd/even = "); int input = sc.nextInt();
Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(System.in);
int input = sc.nextInt(); int input = sc.nextInt(); OddEvenCheck oec = new OddEvenCheck();
int out = oec.oddeven(input);
oddeven(input); OddEvenCheck oec = new OddEvenCheck(); if(out == 1)
non-static method oddeven(int) cannot be referenced from a static context oec.oddeven(input); System.out.println(input + " is even number");
so this cannot run in java but c can compile it } else
} } System.out.println(input + " is odd number");
} }
}
T
8
Complex programs
package class2; package personal;
package class3;
import java.util.Scanner;
import java.util.Scanner;
import java.util.Scanner; package class2; public class b
public class Class2 {
public class OddEvenCheckWithFuncCall
{ public static void main(String args[])
{ class Class2
public static void main(String args[]) {
public static void main(String args[]) { int i;
{ int pos=0;
{ public static void main(String args[]) int neg=0;
System.out.print("Enter a number to make a half pyramid = ");
System.out.print("Enter a number to make a pyramid = "); { System.out.print("Enter the value of input : ");
Scanner sc = new Scanner(System.in);
Scanner sc = new Scanner(System.in); for(int r = 0; r<3; r++) Scanner sc = new Scanner(System.in);
int input = sc.nextInt(); int input = sc.nextInt();
int input = sc.nextInt(); {
int p = r;
for(int r = 1; r<=input; r++) int a[] = new int[input];
for(int r = 0; r<input; r++) for(int c = 0; c<6; c++) for(i=0; i<input; i++)
{
{ { {
for(int c = input-1; c>=r; c--) a[i] = sc.nextInt();
for(int c = 0; c< input-r-1; c++) ++p;
System.out.print("\t"); if(a[i]>0)
System.out.print("\t"); System.out.print(p + " "); {
for(int c = 0; c<=r*2; c++) } pos=pos+1;
for(int c = 1; c<=r; c++) }
System.out.print("*" +"\t"); System.out.println(); else if(a[i]<0)
System.out.print("*\t"); {
}
neg=neg+1;
System.out.println(); } }
System.out.println(); }
} } System.out.println("Pos = " + pos);
}
} System.out.println("Neg = " + neg);
} }
} }
}
Entert a number to make a piramid = 3 Enter a number to make a half pyramid = 3 Enter the value of input : 4
1 23 4 56 1
* * 2
2 34 5 67 3
* * * * * -4
3 45 6 78 Pos = 3
* * * * * * * * Neg = 1
mport java.util.*;
import java.util.Scanner;
class PrimeNumbers
public class Caller {
package personal; public static void main(String args[])
public class ConstructorCallingExplain { {
{ int n, status = 1, num = 3;
public static void main(String args[])
public static void main(String args[])
Scanner in = new Scanner(System.in);
{ { System.out.println("Enter the number of prime numbers you http://java67.blogspot.com/2014/01/how-to-check-if-given-number-is-
int f0=0; want"); prime.html
int f1 = 1, f2; System.out.print("Enter the number of elements in array = "); n = in.nextInt();
System.out.print("0 1 "); http://www.programmingsimplified.com/java/source-code/java-program-
Scanner sc = new Scanner(System.in); if (n >= 1)
for (int i=0; i<=10; i++) { print-prime-numbers
{ int n = sc.nextInt(); System.out.println("First "+n+" prime numbers are :-
f2 = f0+f1; "); http://beginnersbook.com/2014/01/java-program-to-display-prime-
System.out.println(2); numbers/
}
System.out.print(f2 + " ");
f0 = f1; int a[] = new int[n];
for ( int count = 2 ; count <=n ; )
f1 = f2; int maximum, i, location; {
} for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
{
} maximum = 0; if ( num%j == 0 )
} {
location = 0; status = 0;
break;
}
}
9
maximum = a[i];
location = i+1;
Enter 3 integers = 6
8
2
Class Topic
1. http://www.dickbaldwin.com/java/Java042.htm
2. http://www.w3resource.com/java-tutorial/java-class-
methods-instance-variables.php
3. http://journals.ecs.soton.ac.uk/java/tutorial/java/javaOO/cla
ssvars.html
class MyClass
// method declarations
}
class classname
{
type instance-variable1;
type instance-variable2;
// ... 4. Here is a class called Box that defines three instance
1. each time you create an instance of a class, you are creating
variables: width, height, and depth.
an object that contains its own copy of each instance variable
type instance-variableN;
class Box defined by the class.
{ 2. Thus, every
type methodname1(parameter-list) 1. The data, or variables, defined within a class are called instance variables.
double width; 3. Box object will contain its own copies of the instance
{ 2. A class declaration only creates a template; it does not create an actual object.
double height; variables width, height, and depth. To
// body of method 3. A class creates a new data type that can be used to create objects. That is, a class
double depth; 4. access these variables, you will use the dot (.) operator. The
} creates a logical framework that defines the relationship between its members.
} dot operator links the name of
type methodname2(parameter-list) When you declare an object of a class,
5. the object with the name of an instance variable. For
{ 4. You are creating an instance of that class. Thus, a class is a logical construct. An
5. To actually create a Box object, you will use a statement like example, to assign the width variable
// body of method object has physical reality. (That is, an object occupies space in memory.)
the following: of mybox the value 100, you would use the following statement:
} Box mybox = new Box(); // create a Box object called mybox mybox.width = 100;
// ...
type methodnameN(parameter-list) ***After this statement executes, mybox will be an instance of Box
{
// body of method
}
}
class Box
double width;
double height;
double depth;
class Class2
1. Domain Suppose messi is the best player. But he cannot play in banani park. He must need an good field or environment where he
2. Idea can play football.
3. Environment Messi = object
4. For object we need an environment that’s why we use class Environment = class
5. User defined data-type
Class 6. Set of objects
7. when we create a class, we are creating a new data type
8. a blueprint of an object Fruit is a class then object = (mango , jackfruit, banana, etc)
9. a template
10.an environment to create an object
11.
11
Declaration
class className
{
member variable declaration;
member fuction defination;
}
Explanation Of Syntax :
1. Instance Variables are Class Variables of the class.
Class name Class Instance Variable 2. When a number of objects are created for the same class, the same
type instance-variable1; copy of instance variable is provided to all.
class classname { type instance-variable2;
// ... 3. Instance variables have different value for different objects.
1. class is Keyword in Java used to create class in java.
type instance-variableN; 4. Access Specifiers can be applied to instance variable i.e public,private.
2. classname is Name of the User defined Class.
5. Instance Variable are also called as “Fields“
Inheritance Topic
http://www.studytonight.com/java/inheritance-in-java.php
Pictures
12
Single Inheritance
Heirarchical Inheritance
Example
package encapsulation.pack1;
import encapsulation.pack2.Add;
package encapsulation.pack2;
public class Caller extends Add
{
public class Add
public static void main(String args[])
{
{
public int x = 10;
// Add obj = new Add();
private int y =20;
Caller obj = new Caller();
public int show()
{
System.out.println(obj.x);
return x+y;
System.out.println(obj.y);
}
}
}
}
10
Exception in thread "main" java.lang.RuntimeException: Uncompilable
source code - y has private access in encapsulation.pack2.Add
at encapsulation.pack1.Caller.main(Caller.java:12)
Java Result: 1
Explanation
Opinion
. When a Class extends another class it inherits all non-private members including fields and
methods.
purpose
To promote code reuse.
To use Polymorphism.
http://www.studytonight.com/java/inheritance-in-java.php
http://beginnersbook.com/2013/05/java-inheritance-types/
http://examples.javacodegeeks.com/java-basics/java-inheritance-example/
-
13
Vehicle
class Vehicle class Vehicle
{ { Vehicle
void method() void method()
{ {
System.out.println("class Vehicle is showing"); System.out.println("class Vehicle is showing");
} }
} }
Constructor Topic
http://www.javatpoint.com/constructor
package personal;
}
}
class Rectangle {
int length;
int breadth;
Rectangle()
Explanation : {
length = 20;
breadth = 10;
1. new Operator will create an object.
}
2. As soon as Object gets created it will call Constructor-
void setDiamentions()
Rectangle() //This is Constructor {
{ length = 40;
length = 20; breadth = 20;
breadth = 10; }
Explanation :
}
} 1. After the Creation of Object , Instance Variables have their
own values inside.
3. In the above Constructor Instance Variables of Object r1 gets their own values. class RectangleDemo { 2. As soon as we call method , values are re-initialized.
public static void main(String args[]) {
4. Thus Constructor Initializes an Object as soon as after creation.
5. It will print Values initialized by Constructor - Rectangle r1 = new Rectangle();
}
}
Parameterized Constructors :
1. Constructor Can Take Value , Value is Called as "Argument". Rectangle(int length,int breadth)
2. Argument can be of any type i.e Integer,Character,Array or any Object. {
3. Constructor can take any number of Argument. length = length;
Explanation:
breadth = breadth;
Live Example : Constructor Taking Parameter in Java Programming }
Carefully observe above program You will found something like this
OR
class Rectangle { Rectangle r1 = new Rectangle(20,10);
int length;
int breadth; Rectangle(int length,int breadth)
This is Parameterized Constructor taking argument.These arguments are used {
Rectangle(int len,int bre) for any purpose inside Constructor Body. this.length = length;
{ this.breadth = breadth;
length = len; }
breadth = bre; New Operator is used to Create Object.
} We are passing Parameter to Constructor as 20,10. But if we use Parameter name same as Instance variable then compiler will
} These parameters are assigned to Instance Variables of the Class. recognize instance variable and Parameter but user or programmer may
We can Write above statement like - confuse. Thus we have used "this keyword" to specify that "Variable is
class RectangleDemo {
public static void main(String args[]) { Instance Variable of Object r1".
}
}
How to achieve method overloading in java
Method overloading in Java occurs when two or more methods shares same name and fulfill at least
one of the following condition.
Method overloading (example of polymorphism) “Overloading in java occurs when methods in a same class or in child classes shares a
1. http://www.beingjavaguys.com/2013/10/method-overloading-in-java.html same name with a ‘difference in number of arguments’ or ‘difference in argument type’ 1) Have different number of arguments.
or both.” 2) Have same number of arguments but their types are different.
8.
9. public void getEmpName(int empId, String empName) {
10. ......
11. }
12.
13. public void getEmpName(Date dob, String empName) {
14. ......
15. }
Default or
argumentless
Constructor Argumented
Copy
Object Topic
1. http://docs.oracle.com/javase/tutorial/java/concepts/object.html
2.
1. Object = set of attributes = like structure
2. 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.
3. Software objects also have a state and behavior. A software object's state is stored in fields and
behavior is shown via methods.
4. In software development, methods operate on the internal state of an object and the object-to-
object communication is done via methods.
5. A class provides the blueprints for objects. So basically an object is created from a class
Creating an Object:
There are three steps when creating an object from a class:
Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes the new object.
//creating a class
class Woman
1. Each object has its own copies of the instance variables. This means that
{
if you have two objects, each has its own copy of child 1, child2,
int child1;
child3.
int child2;
2. It is important to understand that changes to the instance variables of
int child3;
one object have no effect on the instance variables of another. package class3;
}
class Woman
{
int child1; public class classObj
int child2; {
int child3; public static void main(String args[])
} {
//obj creation
public class classObj
//className obj; // declare
{
public static void main(String args[])
{ //man is a reference to an object of type Box. man does not yet refer to
Woman man1 = new Woman(); an actual object. The next line allocates an object and assigns a reference to it
man1.child1 = 10; to woman. After the second line executes, you can use woman as if it were a
man1.child2 = 12; //man object. But in reality, woman simply holds, in essence, the
man1.child3 = 15; memory address of the actual man object.
Woman man2 = new Woman();
man2.child1 = 5; //obj = new className(); //initialize
man2.child2 = 6; //or, className obj = new className()
man2.child3 = 7; Woman man= new Woman();
System.out.println("Age of the child1 = " + man1.child1); //accessing the members of the woman class
System.out.println("Age of the child1 = " + man2.child1); // & initializing with a value
}
// object.instanceMemberVariable = value;
}
man.child1 = 10;
man.child2 = 12;
man.child3 = 15;
object.instanceMemberVariable = value;
17
1. We might think that b2 is being assigned a reference to a copy of the object referred to by
2. b1. That is, you might think that b1 and b2 refer to separate and distinct objects.
Assigning Object Reference Variables 3. However, this would be wrong. Instead, after this fragment executes, b1 and b2 will both refer to the
Box b1 = new Box(); same object. The assignment of b1 to b2 did not allocate any memory or copy any part of the original
Box b2 = b1; object. It simply makes b2 refer to the same object as does b1.
4. Thus, any changes made to the object through b2 will affect the object to which b1 is referring, since they
are the same object.
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;
Here, b1 has been set to null, but b2 still points to the original
object.
package personal;
class GrandSon
{
class GrandDaughter
{
class Son
{
GrandSon obj1 = new GrandSon();
GrandDaughter obj2 = new GrandDaughter();
}
class GrandFather
{
Son obj3 = new Son();
}
Vehicle
Call by Call by
Value reference
Method Topic
type methodname1(parameter-list) {
// body of method
}
1. methods are equivalent to function
2. Class methods can be declared public or private
3. These methods are meant for operating on class data i.e Class Instance
Variables.
class Rectangle {
int length;
int width;
Rectangle(int l, int b) {
length = l;
width = b;
}
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle(10, 20);
r1.area(r1);
}
}
MethodAccessChecker
package personal;
class MethodAccessChecker
{
int var1, var2;
void method1()
{
var1 = 10;
}
void method2()
{
System.out.println(var1);
}
}
Polymorphism Topic
Method Overloading
Polymorphism http://beginnersbook.com/2013/03/polymorphism-in-java/
Method Overriding
Overloading Overriding
Happening within the same class. Happening between super class and sub class.
It happen at time of compliance or we can say overloading is It happen on time of run time or we can say overriding is
the early binding or static binding. dynamic binding or let binding.
Method can have any return type. Method return type must be same as super class method
package personal;
class Parent
package personal; {
class InA void method()
{ {
void method(int l) System.out.println("Parent is showing");
{ }
System.out.println("Method overloaded in 1"); }
} class Child extends Parent
void method(float b) {
{ void method()
System.out.println("Method overloaded in 2"); {
} System.out.println("Child is showing");
} }
}
public class constructor
{ public class constructor
public static void main(String args[]) {
{ public static void main(String args[])
InA obj = new InA(); {
obj.method(4); Child obj = new Child();
} obj.method();
} }
}
package personal;
package personal;
package personal; class a
class b extends a
public class constructor {
{
{ void method()
void method()
public static void main(String args[]) {
{
{ System.out.println("Parent a is
System.out.println("Child b is
b obj = new b(); showing");
showing");
obj.method(); }
}
} }
}
}
Child b is showing
Method overriding
is the basis for polymorphism
only applicable in methods To override the functionality of an existing method.
overriding is only applicable for the classes related to each other through inheritance
only between super classes & subclasses
Definition
If a method is declared in the parent class and method with same name and parameter list is written
inside the subclass then it is called method overriding.
Rules
Rules for method overriding:
Rules for Method Overriding :
The argument list should be exactly the same as that of the overridden method.
The return type should be the same or a subtype of the return type declared in the original overridden method in the 1. Method Must have Same Name as that of Method Declared in Parent Class
superclass.
2. Method Must have Same Parameter List as that of Method Declared in Parent Class
The access level cannot be more restrictive than the overridden method's access level. For example: if the superclass 3. IS-A relation should be maintained in order to Override Method.
method is declared public then the overridding method in the sub class cannot be either private or protected.
Instance methods can be overridden only if they are inherited by the subclass.
21
A subclass within the same package as the instance's superclass can override any superclass method that is not
declared private or final.
A subclass in a different package can only override the non-final methods declared public or protected.
An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws
exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than
the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the
overridden method.
Examples
package overriding ;
package overriding ;
class Animal{ class Animal{
System.out.println("Animals can move"); In compile time, the check is made on the reference type. However, in the class Dog extends Animal{
public static void main(String args[]){
} runtime, JVM figures out the object type and would run the method that public void move(){
Animal a = new Animal(); // Animal reference and object belongs to that particular object. super.move(); // invokes the super class method
} System.out.println("Dogs can walk and run");
Animal b = new Dog(); // Animal reference but Dog object }
package overriding ; }
Therefore, in the above example, the program will compile properly since
class Dog extends Animal{ public class TestDog{
Animal class has the method move. Then, at the runtime, it runs the method
a.move();// runs the method in Animal class
specific for that object. public static void main(String args[]){
run:
Animal b = new Dog(); // Animal reference but Dog object
Animals can move o Here b is the object of dog that’s why b.method() calls the method located in Dog class Animals can move
Dogs can walk and run
Dogs can walk and run
BUILD SUCCESSFUL (total time: 0 seconds)
package encapsulation;
package com.c4learn.inheritance;
public class InheritanceRules extends baseClass{
public class TwoWheeler extends Vehicle {
package encapsulation;
public void vehicleMethod() {
package com.c4learn.inheritance; public int calculate(int num1,int num2) {
System.out.println("Method" + " in TwoWheeler.");
} return num1+num2; class baseClass {
public class Vehicle {
public static void main(String[] args) { }
public void vehicleMethod() {
TwoWheeler myBike = new TwoWheeler();
System.out.println("Method in Vehicle."); public int calculate(int num1,int num2) {
Vehicle myVehicle = new Vehicle();
}
public static void main(String[] args) { return num1*num2;
}
myVehicle.vehicleMethod();
myBike.vehicleMethod(); baseClass b1 = new baseClass(); }
Result : 100
Method in TwoWheeler.
BUILD SUCCESSFUL (total time: 0 seconds)
22
Pictures
Explanation
Animal b = new Dog(); // Animal reference but Dog object
o Here b is the object of dog that’s why b.method() calls the method located in Dog class
Access level
Opinion
Exception Topic
Definitions
Java exception handling is managed via five keywords:
1. try,
2. catch,
3. throw,
4. throws, and
5. finally.
General forms
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
24
Rules
Examples
class Caller
{
public static void main(String args[])
class Caller {
{ int d = 0;
public static void main(String args[]) try
{ {
int d = 0; int a = 42 / d;
int a = 42 / d; System.out.println(a);
System.out.println(a); }
System.out.println("Skipping not maintained"); catch(Exception err1)
} {
} System.out.println("Skipping maintained & "+ err1);
}
}
}
run:
Exception in thread "main"
run:
java.lang.ArithmeticException: / by zero
Skipping maintained & java.lang.ArithmeticException: / by zero
at interfaces_4.pack1.Caller.main(Caller.java:7)
Java Result: 1
Pictures
Explanation
Why?
Although the default exception handler provided by the Java run-time system is useful for debugging, you will usually want to handle an exception yourself.
Doing so provides two benefits.
Opinion
Classification
25
Loop Topic
Definitions
6.
General forms
Rules
Examples
package saifur;
import java.util.*;
Pictures
26
Explanation
Why?
Opinion
Classification
Class
Definitions
Rules
Examples
Pictures
27
Explanation
Opinion
Classification
Class
Definitions
Rules
Examples
28
Pictures
Explanation
Opinion
Classification
29
Encapsulation Topic
http://beginnersbook.com/2013/05/encapsulation-in-java/
http://www.tutorial4us.com/java/Encapsulation
http://www.placementyogi.com/tutorials/java/introduction-to-java/pillars-
of-oops
Encapsulation is a practice to bind related functionality (Methods) & Data (Variables) in a protective wrapper (Class) with required access modifiers
to hide the implementation details from users (public, private, default & protected) so that the code can be saved from unauthorized access by outer world and can be made easy to maintain.
Encapsulation is also known as “data Hiding” Encapsulation is a process of wrapping of data and methods in a single unit is called encapsulation
To secure the data from other methods, when we make a data private then these data only use
within the class, but these data not accessible outside the class.
Encapsulation is the mechanism of binding together the data and the code, so that they are not misused or accidentally modified.
Provides abstraction between an object and its clients. Encapsulation is technique by which we can hide the data with in a class and provide public methods to manipulate the hide da ta.To achieve encapsulation we can declare variables private and provide
Protects an object from unwanted access by clients. public methods to manipulate these private variables.
Example: A bank application forbids a client to change an Account's balance.
In the same class we can access the private variable otherwise we cannot but if we want to
access in another class’s private variable then we have to use a method to access the data
Examples
package encapsulation.pack1;
package encapsulation.pack2;
import encapsulation.pack2.Add;
{ {
public static void main(String args[]) private int x = 10, y =20;
return x+y;
System.out.println("x+y = " + obj.show()); }
} }
x + y = 30
30
pictures
explanation
ENCAPSULATION :
Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and
abstraction.
Analogy:
Let's say we had one box containing one cake. There were 4 guys who wanted to eat that cake. If we kept the box open, any
one could have eaten it,result would have been - No cake for others. How this situation was avoided ?
> we hired one person (guard), name getter. The responsibility of the person was to provide exact duplicate copy of the
cake.
> we put a lock on the class and gave the key to guard. so no one can directly eat the cake, one has to ask getter for
cake.
Bingo ! problem solved ??, Not yet; there was another issue that happened - I got the copy of cake and found that it was
not sweet enough. I added the sugar and asked the guard to replace this cake with original one. Guard said - "that's not my
duty". So we took another step:
> we hired one more person (guard), name setter. The responsibility of the setter was to replace the original cake.
I gave the new cake, with enough sweetness, to setter and he replaced it. Problem Solved ??, Not yet, one guy mixed the
poison into cake and asked the setter to replace it.
So we were in problem again, so we took anothe step, we gave addition responsbility to setter -
> Test the cake before replacing. Replace it if and only if it passes certain test.
OK !! This is the concept behined ENCAPSULATION.In Technical terms -
>Box act as Class
>Cake act as Field of the class
>guards act as public methods of the class
>responsibilities of guards act as action performed by methods
So Encapsulation is the technique of making the fields in a class private and providing access to the fields via public
methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields
within the class. For this reason, encapsulation is also referred to as data hiding.
Lets say you have to buy some medicines. You go to the medical store and ask the chemist for the meds. Only the chemist has access to the medicines in the store based on your
prescription. The chemist knows what medicines to give to you. This reduces the risk of you taking any medicine that is not intended for you.
In this example,
MEDICINES == Member Variables.
CHEMIST == Member Methods.
So, If Any external Application has to access the Member Variables It has to call the appropriate Member Methods which will do the task for it.(If You have to access the Medicines
You have to ask the Chemist). This way the member variables are secure and encapsulated by a layer of Member Methods.
The Member Methods and Member Variables are bundled together in to objects and can be accessed only by the objects.
So you need 2 steps if you have to access a public member of a class you have to:
1. Create an object of the class
2. Then access the member through object.
You need 3 steps if you want to access the private members of a class
No Term Definition
Inheritance Inheritance is a process where one object acquires the properties of another object
1
2 Subclass Class which inherits the properties of another object is called assubclass
inheritance
public class Vehicle{ 1. Vehicle is the superclass of TwoWheeler class. IS-A relationship of above example is -
} 2. Vehicle is the superclass of FourWheeler class.
TwoWheeler IS-A Vehicle
public class FourWheeler extends Vehicle{ 3. TwoWheeler and FourWheeler are sub classes of Vehicle class.
} 4. WagonR is the subclass of both FourWheeler and Vehicle classes. FourWheeler IS-A Vehicle
package interfaces_2.pack1;
package interfaces_2.pack2;
import interfaces_2.pack2.Balance;
public class Balance
public class Caller
{
{
String name;
public static void main(String args[])
float balance;
{
public Balance(String name, float balance)
Balance obj[] = new Balance[3];
{
obj[0] = new Balance("Saifur", 100);
this.name = name;
obj[1] = new Balance("hasan", 5000);
this.balance = balance;
obj[2] = new Balance("sazzad", 100000);
}
Interfaces
Syntax
Interfaces rules
an interface is a group of related methods with empty bodies
An interface is a collection of abstract methods
Writing an interface is similar to writing a class, but they are two
different concepts.
An interface can contain any number of methods but does not contain We can create object for class but not for interface
any constructors All the members/fields inside the interface are public & abstract &
You cannot instantiate an interface. static & final even if we do not declare them . It’s an automatic/default
An interface in java is a blueprint of a class. It has static constants and
All of the methods in an interface are abstract. using interface, you can specify what a class must do, but not how it mechanism
abstract methods only.
An interface can extend multiple interfaces does it Does not have any method implementation
It is used to achieve fully abstraction and multiple inheritance in Java.
An interface is not extended by a class; it is implemented by a class. If the class which implements the interface does not override the
Java Interface also represents IS-A relationship
An interface cannot contain instance fields. The only fields that can method, it should be marked abstract
It cannot be instantiated just like abstract class
appear in an interface must be declared both static and final Interface can extends any numbers of interfaces
Methods in an interface are implicitly public.
Each method in an interface is also implicitly abstract, so the abstract
keyword is not needed.
33
In When a class implements an interface, you can think of the class as signing a
contract, agreeing to perform the specific behaviors of the interface. If a class does
not perform all the behaviors of the interface, the class must declare itself as
abstract.
Definitions
The static keyword is used in java mainly for memory management. We may
apply static keyword with variables, methods, blocks and nested class. The static
keyword belongs to the class than instance of the class.
3. block
4. nested class
Rules
It is a non-access modifier
Static keyword can be applied to an instance variable or method.
o Applying to an instance variable makes that variable as a class variable.
o Both primitive and reference variable can be marked with static keyword
Static member belong to the class rather than to any particular instance, i.e.) it is used independently of any object of that class.
Static member is created using static keyword.
When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object.
Examples
The best example of a static member is main() method. main() should be called before any object exists , Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created. All student have its unique rollno and
hence it is declared as static. name so instance data member is good.Here, college refers to the common property of all objects.If we make it static,this field will get memory only once.
Suppose we have 5 secrets. Our condition is we can reveal only one secrete.
In the other hand static keyword can get memory only once for it’s field.
So, to reveal the secrete we can get the memory only once not for multiple times like object.
Pictures
Explanation
In this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory As we have mentioned above, static variable will get the memory only once, if any
at the time of object creation, each object will have the copy of the instance variable, if it is incremented, it won't refle ct to other objects. So each object changes the value of the static variable, it will retain its value.
objects will have the value 1 in the count variable. 1. class Counter2{
2. static int count=0 ;//will get memory only once and retain its value
35
1. class Counter{ 3.
2. int count=0;//will get memory when instance is created 4. Counter2(){
3. 5. count++;
4. Counter(){ 6. System.out.println(count);
5. count++; 7. }
6. System.out.println(count); 8.
7. } 9. public static void main(String args[]){
8. 10.
9. public static void main(String args[]){ 11. Counter2 c1=new Counter2();
10. 12. Counter2 c2=new Counter2();
11. Counter c1=new Counter(); 13. Counter2 c3=new Counter2();
14.
12. Counter c2=new Counter();
15. }
13. Counter c3=new Counter();
16. }
14. Test it Now
15. }
16. }
Output:1
Test it Now
2
Output:1 3
1
1
} }
} }
package Static.pack1;
package Static.pack1;
package Static.pack2; package Static.pack2;
import Static.pack2.Balance; You can see that we can happily access the “a” instance variable in
public class Balance import Static.pack2.Balance;
class Caller the “Balance” class without actually creating an object of type
{
{ public class Balance “Balance”. We can just use the “Balance” class directly. That’s
public static int a = 5; class Caller
public static void main(String args[]) { because the variable is static, and hence belongs to the class, not
} { any particular object of that class.
{ public static int a = 5;
public static void main(String args[])
Balance obj = new Balance(); }
{
System.out.println(obj.a); The fact that we declared it public allows us to access it from other
System.out.println(Balance.a);
classes (Application in this case)
}
5
}
}
}
5
package Static.pack1; package Static.pack2; package Static.pack2;
package Static.pack1;
import Static.pack2.Balance;
import Static.pack2.Balance;
class Caller public class Balance public class Balance
class Caller
{ { { Using the Static Keyword to Create Constants
{
public static void main(String public static int a = 5; public final static int a = 5;
public static void main(String args[]) One common use of static is to create a constant value that’s
args[]) } attached to a class. The only change we need to make to the above
} {
{ example is to add the keyword final in there, to make ‘a’ a
Balance.a = 10;
Balance.a = 10; constant (in other words, to prevent it ever being changed).
System.out.println(Balance.a);
}
System.out.println(Balance.a);
10 } error
}
}
package Static.pack2; package Static.pack2;
} }
36
Opinion
Classification
static variable static method
1) 2)
If you declare any variable as static, it is known If you apply static keyword with any method, it is known as static method
static variable.
A static method belongs to the class rather than object of a class.
The static variable can be used to refer the common property of all objects (that A static method can be invoked without the need for creating an instance of a class.
is not unique for each object ) e.g. company name of employees,college name of students etc. static method can access static data member and can change the value of it.
The static variable gets memory only once in class area at the time of class loading.
static method
It is a variable which belongs to the class and not to object(instance)
Static variables are initialized only once , at the start of the execution . These variables will be initialized first, before It is a method which belongs to the class and not to the object(instance)
the initialization of any instance variables A static method can access only static data. It can not access non-static data (instance variables)
A single copy to be shared by all instances of the class A static method can call only other static methods and can not call a non-static method from it.
A static variable can be accessed directly by the class name and doesn’t need any object A static method can be accessed directly by the class name and doesn’t need any object
Syntax : <class-name>.<variable-name> Syntax : <class-name>.<method-name>
A static method cannot refer to "this" or "super" keywords in anyway
1. class Student{ 1. //Program of changing the common property of all objects(static field).
2. int rollno; 2.
3. String name; 3. class Student9{
4. String college="ITS"; 4. int rollno;
5. } 5. String name;
6. static String college = "ITS";
Suppose there are 500 students in my college, now all instance data members will get memory each time when object is 7.
created.All student have its unique rollno and name so instance data member is good.Here, college refers to the common 8. static void change(){
9. college = "BBDIT";
property of all objects.If we make it static,this field will get memory only once.
10. }
class Caller{ 11.
12. Student9(int r, String n){
int rollno;
13. rollno = r;
String name; 14. name = n; Output:111 Karan BBDIT
15. } 222 Aryan BBDIT
static String college ="ITS"; 16. 333 Sonoo BBDIT
17. void display (){System.out.println(rollno+" "+name+" "+college);}
run: 18.
19. public static void main(String args[]){
Caller(int r,String n, String m){ 20. Student9.change();
111 Karan BAF
21.
rollno = r; 22. Student9 s1 = new Student9 (111,"Karan");
222 Aryan BAF 23. Student9 s2 = new Student9 (222,"Aryan");
name = n;
24. Student9 s3 = new Student9 (333,"Sonoo");
college = m; 25.
26. s1.display();
} BAF because 27. s2.display();
28. s3.display();
void display () The static variable can be used to refer 29. }
{ the common property of all objects (that30. }
is not unique for each object )
System.out.println(rollno+" "+name+" "+college);
} Suppose we have 5 secrets. Our condition is we can
reveal only one secrete. 1. //Program to get cube of a given number by static method
2.
In the other hand static keyword can get memory 3. class Calculate{
public static void main(String args[]) only once for it’s field. 4. static int cube(int x){
{ So, to reveal the secrete we can get the memory 5. return x*x*x;
only once not for multiple times like object. 6. }
Caller s1 = new Caller(111,"Karan", "SEU"); Output:125
7.
Caller s2 = new Caller(222,"Aryan", "BAF"); 8. public static void main(String args[]){
9. int result=Calculate.cube(5);
10. System.out.println(result);
s1.display(); 11. }
12. }
s2.display();
}
}
class Caller
Restrictions for static method
{
static int a =5; run:
A static variable can be accessed directly by the class name and doesn’t
public static void main(String args[]) Hello 5 need any object There are two main restrictions for the static method. They are:
{
System.out.println("Hello "+ a); The static method can not use non static data member or call non-static method directly.
} this and super cannot be used in static context.
}
37
My answer:
If we create a method as static in a class we can directly access by referencing that class not by creating any objects.
That’s how when compiler access the program it first look that program which has static method & called as a main & defined as
public access modifier
static block
class A2{
Final keyword
Definition
Rules
Way 1 : Final Variable
o If we make the variable final then the value of that variable cannot be changed once assigned.
The final keyword is a non-access modifier.
Way 2 : Final Method
o We cannot Override the final method as we cannot change the method once they are declared final. It can be applied to a class, method(both instance and static) and variable(instance, static, local and parameter).
Way 3 : Final Class
o We cannot inherit the final class
Examples
Pictures
Explanation
Access level
Opinion
final Method is inherited but cannot be overriden so always method from parent class will be executed.
Additional info
Definition
Rules
A final static variable must be definitely initialized either
o during declaration also known as compile time constant or
o in a static initialize (static block) of the class in which it is declared otherwise, it results in a compile-time error.
You cannot initialize final static variables inside a constructor
Examples
class Car
{
final static double MIN_SPEED = 0; //Compile time
constant
final static double MAX_SPEED; //Blank final static
Field
Car()
{
//MIN_SPEED = 0; //ERROR
//MAX_SPEED = 200; //ERROR
}
}
40
Pictures
Explanation
Access level
Opinion
Additional info
Naming a Constant
By convention, to name a constant we use all uppercase letters. If the name is composed of more than one word, the words are
separated by an underscore (_).
Example,
Constants
ARRAY_SIZE
Fields that are marked as final, static, and public are effectively known as constants MAX_GRADE
For example, the following variable declaration defines a constant named PI, whose value is an approximation of pi PI
1 public static final double PI = 3.141592653589793;
If a primitive type or a String is defined as a constant and the value is known at compile time, the compiler replaces the constant name
Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so.
everywhere in the code with its value. This is called a compile-time constant. If the value of the constant changes (for example,
MAX_SPEED of a Car should be 100), you will need to recompile any classes that use this constant to get the current value.
Advantage:
The compiled Java class results in faster performance if variables are declared as static final.
Super keyword
Definition
Super is used to refer the immediate parent of the class
Rules
3 ways of Using Super Keyword :
. Whenever we create an object of the child class then the reference to the parent class will be created automatically.
We can user super keyword by using three ways -
Examples
Pictures
Explanation
Access level
Opinion
42
this keyword
This = global
package personal;
class Student
{
String name;
int roll;
float mark;
package personal;
Student(String name, int roll, float mark)
{
class Test
this.name = name;
{
this.roll = roll;
int i = 20;
this.mark = mark;
}
void local()
{
}
int i = 10;
public class ConstructorCallingExplain
System.out.println("Local i = " + i);
{
System.out.println("Global this.i = " + this.i);
public static void main(String args[])
//this = gloabl
{
}
Student obj1 = new Student("saifur", 67, 70.0f);
Student obj2 = new Student("rasel", 58, 75.5f);
public static void main(String args[])
{
System.out.println(obj1.name);
Test obj = new Test();
System.out.println(obj1.roll);
obj.local();
System.out.println(obj1.mark);
}
}
System.out.println(obj2.name);
System.out.println(obj2.roll);
System.out.println(obj2.mark);
}
}
The most common reason for using the this keyword is because a field is
shadowed by a method or constructor parameter.
//constructor
public Point(int a, int b)
{
x = a;
y = b;
}
}
but it could have been written like this:
//constructor
public Point(int x, int y)
{
43
this.x = x;
this.y = y;
}
}
Java vs C#
How Java Related to C# ?
Consider Scenario of Java Programming Language
1. After the creation of Java, Microsoft developed the C# language and C# is closely related to Java.
2. Many of C# features directly parallel Java. Both Java and C# share the same general C++-style
syntax, support distributed programming, and utilize the same object model. 1. Java is created by Sun Micro System.
3. Though there are some differences between Java and C#, but the overall feel of these languages is 2. Java Compiler produces Intermediate code called Byte Code.
very similar. 3. Byte Code i.e intermediate code is executed by the Run Time Environment.
4. If you already know C#, then learning Java will be easy and vice versa 4. In Java Run Time Environment is called as JVM [ Java Virtual Machine]
5. Java and C# are optimized for two different types of computing environments. 5. If we have JVM already installed on any platform then JVM can produce machine dependent Code
6. C# and Java Both Languages are drew from C++. based on the intermediate code.
7. Both Languages are capable of creating cross platform portable program code.
Java Vs C Sharp
Point Java C#
Development Sun Microsystem Microsoft
Development Year 1995 2000
Data Types Less Primitive DT More Primitive DT
Struct Concept Not Supported Supported
Switch Case String in Switch Not Allowed String in Switch Allowed
46
Java is Considered as Platform independent because of many different reasons which are As the output of Java Compiler is Non Executable Code we can consider it as Secure (it Java is a strictly typed language, it checks your code at compile time. However, it
cannot be used for automated execution of malicious programs). also checks your code at run time
listed below –
4. JVM is an interpreter.
5. JVM accepts Bytecode as input and execute it.
1. Output of a Java compiler is Non Executable Code i.e Bytecode. 6. Translating a Java program into bytecode makes it much easier to run a program in
2. Bytecode is a highly optimized set of instructions a wide variety of environments because only the JVM needs to be implemented
3. Bytecode is executed by Java run-time system, which is called the Java Virtual for each platform.
Machine (JVM). 7. For a given System we have Run-time package , once JVM is installed for
particular system then any java program can run on it.
As the output of Java Compiler is Non Executable Code we can consider it as Secure 8. However Internal details of JVM will differ from platform to platform but still
(it cannot be used for automated execution of malicious programs). all understand the Same Java Bytecode.
The Bytecode
The output of a Java compiler is not executable code. Rather, it is bytecode
Bytecode is a highly optimized set of instructions
Bytecode designed to be executed by the Java run-time system, which is called the Java Virtual Machine (JVM)
JVM = interpreter for bytecode
Java program is executed by the JVM
HotSpot provides a Just-In-Time (JIT) compiler for bytecode
An Overview of Java
Two Paradigms
Furthermore, a program can be conceptually organized around its code or around its data. That is,
2. others are written around “who is being affected.” ( Object-oriented programming)
1. some programs are written around “what is happening” (process-oriented model.)and
All computer programs consist of two elements:
Object-oriented programming organizes a program around its data (that is, objects) and a set of well-defined
2. code and process-oriented model. This approach characterizes a program as a series of linear steps (that is, code). The
interfaces to that data. An object-oriented program can be characterized as data controlling access to code.
3. data process-oriented model can be thought of as code acting on data
As you will see, by switching the controlling entity to data
Inheritance is the process by which one object acquires the properties of another object.
1. Encapsulation ( লু কিয়ে রাখা )
2. Polymorphism ( বহুরূপতা) 1. “many forms”
3. Inheritance ( উত্তরাকিিার)
Program
By convention, the name of the main class should match the name of the file that holds the program.
package class2;
import java.io.*;
class Class2
System.out.println("Hello world");
}
}
Control statement
The if Statement
51
if(condition) statement;
Loop
package class2;
import java.io.*;
class Class2
{
public static void main(String args[])
{
1. for(initialization; condition; iteration) statement; for(int x = 0; x<10; x++)
2. ( x++ ) = ( x+=1 ) = ( x = x+1 )
3. ( x-- ) = ( x-=1 ) = ( x = x-1 ) {
System.out.println("This is x: " + x);
}
for(int x = 0; x<10; x++)
{
System.out.println("This is x+1: " + (x+1));
}
}
}
identifiers
1. Identifiers are used to name things, such as classes, variables, and methods. examples of valid identifiers are
2. An identifier may be any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore and dollar-sign
AvgTemp count a4 $test this_is_ok
characters. (The dollar-sign character is not intended for general use.)
3. They must not begin with a number, lest they be confused with a numeric literal. Invalid identifier names include these:
4. Again, Java is case-sensitive, so VALUE is a different identifier than Value. 2count high-temp & Not/ok
Separators
Symbol Name Purpose
[] Brackets / square
braces
Used to declare array types. Also used when dereferencing array values.
Chapter 1
(Variables & Data Types)
Data Types
55
Char
class ex1
{
public static void main(String args[])
{
char ch1 = 'A', ch2 = 65;
System.out.println("ch1 = "+ ch1);
System.out.println("ch1 = "+ ch2);
}
}
Int
Explanation :
Integer Data Type : Class IntDemo 1. Primitive Variable can be declared using “int” keyword.
1. Integer Data Type is used to store integer value. { 2. Though Integer contain default Initial Value as 0 , still we
public static void main(String args[])
2. Integer Data Type is Primitive Data Type in Java Programming Language. have assign 0 to show
{
3. Integer Data Type have respective Wrapper Class – “Integer“. int number=0; assignment in Java.
System.out.println("Total Number : " + number);
4. Integer Data Type is able to store both unsigned ans signed integer values so } 3. “+” operator is used to concatenate 2 strings.
}
Java opted signed, unsigned concept of C/C++. 4. Integer is converted into String internally and then two
strings are concatenated.
Float
class ex1
{
public static void main(String args[])
{
float a = 3.1415F, b = 5.3432923423f;
System.out.println("a = "+ a);
System.out.println("b = "+ b);
}
}
Double
class ex1
{
public static void main(String args[])
{
double a = 3.1415, b = 5.3432923423;
System.out.println("a = "+ a);
System.out.println("b = "+ b);
}
}
Variable Input/Output
import java.io.*;
import java.io.*; class ex1{
class ex1 import java.io.*; public static void main(String[] args){
{ class ex1{
public static void main(String args[]) public static void main(String[] args){ try{
{ InputStreamReader IN = new InputStreamReader(System.in);
DataInputStream in = new DataInputStream(System.in); try{ BufferedReader BR = new BufferedReader(IN);
char ch; InputStreamReader IN = new InputStreamReader(System.in);
try{ BufferedReader BR = new BufferedReader(IN); System.out.print("Enter Your age : ");
System.out.print("Enter a character : "); String s = BR.readLine();
ch = (char) System.in.read(); String s = BR.readLine();
System.out.println("You have entered : "+ ch); System.out.println(s); int age = Integer.parseInt(s);
} }
catch(Exception E){} System.out.println("Your age is : " + age);
catch (Exception e){} } }
} } catch(Exception E){}
} }
}
Type conversion
String s = BR.readLine();
String s = BR.readLine();
int age = Integer.parseInt(s);
float age = Float.parseFloat(s);
Chapter 2
(Variables & Data Types)
57
Chapter 3
(Control Statements)
switch()
import java.io.BufferedReader;
import java.io.InputStreamReader;
class ex1{
public static void main(String[] args){
try{
InputStreamReader IN = new InputStreamReader(System.in);
BufferedReader BR = new BufferedReader(IN);
String s = BR.readLine();
switch(year){
case 1:
System.out.println("This is first year");
break;
case 2:
System.out.println("This is Second year");
58
break;
case 3:
System.out.println("This is third year");
break;
case 4:
System.out.println("This is fourth year");
break;
default:
System.out.println("You didn't entered Right year");
}
}
catch (Exception E){}
}
}
Loop
Fibonacci series
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.InputStreamReader; class ex1{
public static void main(String[] args){
class ex1{ try{
public static void main(String[] args){ InputStreamReader IN = new InputStreamReader(System.in);
try{ BufferedReader BR = new BufferedReader(IN);
InputStreamReader IN = new InputStreamReader(System.in);
BufferedReader BR = new BufferedReader(IN); System.out.print("Enter your how many fibonacci numbers :
");
System.out.print("Enter your how many fibonacci numbers : "); int f0 = 0, f1 = 1, f2;
String s = BR.readLine();
String s = BR.readLine(); System.out.print("0 " );
for (int i = 0; i<input-1; i++){
int input = Integer.parseInt(s);
int input = Integer.parseInt(s); f2 = f0 + f1;
System.out.print(f2 + " " );
int f0 = 0, f1 = 1, f2;
int f0 = 0, f1 = 1, f2; f1 = f0;
System.out.print("0 1 " );
for (int i = 0; i<input; i++){ f0 = f2;
f2 = f0 + f1; }
for (int i = 0; i<input-2; i++){
System.out.print(f2 + " " ); f2 = f0 + f1;
f0 = f1; System.out.print(f2 + " " );
f1 = f2; f0 = f1;
} f1 = f2;
}
}
catch (Exception E){} }
} catch (Exception E){}
} }
}
Prime numbers
import java.util.*;
class Mainthread
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and
itself. A natural number greater than 1 that is not a prime number is called a composite number {
System.out.print("Enter series of prime number up to : "); System.out.print("Enter series of prime number up to : ");
String s = BR.readLine();
int input = sc.nextInt();
int input = Integer.parseInt(s);
int i = 0, j = 0; int i = 0, j = 0;
for (i = 2; i<input; i++, j++){
for(j = 2; j<i; j++){ for (i = 2; i<input; i++, j++)
if(i % j == 0){ {
break;
} for(j = 2; j<i; j++)
}
if (i == j){ {
System.out.print(i); if(i % j == 0)
}
} break;
}
catch (Exception E){} }
}
if (i == j)
}
System.out.print(i+" ");
}
}
catch (Exception E){}
}
59
Nested loop
System.out.print("Enter number up to : "); System.out.print("Enter number least to : "); System.out.print("Enter number least to : "); System.out.print("Enter number least to : ");
String s = BR.readLine(); String s = BR.readLine(); String s = BR.readLine(); String s = BR.readLine();
int input = Integer.parseInt(s); int input = Integer.parseInt(s); int input = Integer.parseInt(s); int input = Integer.parseInt(s);
if (input<1){
continue;
}
else
System.out.println("Your entered a positive
number ");
break;
}
Chapter 4
(Array Topic)
System.out.println(total);
}
60
System.out.println(total);
import java.io.BufferedReader;
import java.io.InputStreamReader;
class ex1{
public static void main(String [] args){
int Roll[] = new int[5];
float Marks[] = new float[5];
try{
for (int i=0; i<5; i++){
InputStreamReader IN = new InputStreamReader(System.in);
BufferedReader BR = new BufferedReader(IN);
}
System.out.print("Given list of Rolls are : ");
for (int i=0; i<5; i++){
System.out.print( Roll[i] + " ");
}
}
catch (Exception E){
System.out.println("Error in inpuit. Program terminated .....");
System.exit(0);
}
}
}
61
Chapter 5
(String)
String array
class ex1{
public static void main(String[] args) {
String stringArray[] = new String[5]; class ex1{
stringArray[0] = "saifur"; public static void main(String[] args) {
stringArray[1] = "jhon"; String stringArray[] = {"saifur","jhon", "miraj", "Akkhoy", "rashed" };
stringArray[2] = "miraj";
stringArray[3] = "Akkhoy"; System.out.println(stringArray[0] +" "+stringArray[1] +"
stringArray[4] = "rashed"; "+stringArray[2] +" "+stringArray[3] +" "+stringArray[4]);
System.out.println(stringArray[0] +" "+stringArray[1] +" }
"+stringArray[2] +" "+stringArray[3] +" "+stringArray[4]); }
}
}
String methods
http://www.geom.uiuc.edu/~daeron/docs/apidocs/java.lang.String.html http://www.studytonight.com/java/string-class-functions
import java.io.BufferedReader;
import java.io.BufferedReader; import java.io.IOException;
import java.io.IOException; import java.io.InputStreamReader;
import java.io.InputStreamReader;
class ex1{
class ex1{ class ex1{ public static void main(String[] args)throws IOException {
public static void main(String[] args) { public static void main(String[] args)throws IOException { BufferedReader BR = new BufferedReader(new InputStreamReader(System.in));
BufferedReader BR = new BufferedReader(new String name[] = new String[5];
StringBuffer s1 = new StringBuffer("Md. saifur"); InputStreamReader(System.in)); for (int i=0; i<5; i++) {
System.out.println(s1 + " Rahman"); System.out.print("Please enter name["+i+"] : ");
} System.out.println("Please enter your name: "); name[i] = BR.readLine();
} String name = BR.readLine(); }
System.out.println(name); for (int i=0; i<5; i++) {
} System.out.println("name["+i+"] = " + name[i] + "\tLength = "+ name[i].length());
}
} }
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class ex1{
class ex1{
public static void main(String[] args) {
class ex1{ public static void main(String[] args){
String s1 = "java is a object oriented programming";
public static void main(String[] args)throws IOException { StringBuffer s = new StringBuffer("Object oriented programming");
System.out.print("Enter a name : "); System.out.println(s);
System.out.println("s1.indexOf('p') = "+s1.indexOf('p')+
BufferedReader BR = new BufferedReader(new
"\ns1.indexOf(\"programming\") = " +s1.indexOf("programming"));
InputStreamReader(System.in)); s.setCharAt(6, '-');
}
String name = BR.readLine(); System.out.println(s);
}
for(int i=0; i<name.length(); i++) { }
System.out.println("Character at "+ i +" is : " + }
name.charAt(i));
}
}
}
class ex1{
public static void main(String[] args) {
String s1 = "java is a object oriented programming";
System.out.println("s1 = \"java is a object oriented programming\" ");
int i1 = s1.indexOf("a");
int i2 = s1.indexOf("programming");
System.out.println("s1.indexOf(\"a\") = " +i1);
System.out.println("s1.indexOf(\"programming\") = " + i2);
}
System.out.print(s2);
}
}
Conversion Data-type
class ex1{ class ex1{
public static void main(String[] args) { public static void main(String[] args) {
int i1 = 34; String s1 = "34";
float i2 = 3.456f; String s2 = "3.456f";
double i3 = 34.5646546584654354; String s3 = "34.5646546584654354";
String Topic
http://www.javatpoint.com/java-string
Definitions
In java, string is basically an object that represents sequence of char values. How to create String object?
An array of characters works same as java string. For example: There are two ways to create String object:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'}; 1. By string literal
2. String s=new String(ch);
2. By new keyword
By new keyword
1) String Literal 1. String s=new String("Welcome");//creates two objects and one reference variable
Java String literal is created by using double quotes. For Example: 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).
1. 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 poo l, 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:
Java String Example
1. String s1="Welcome";
1. public class StringExample{
2. String s2="Welcome";//will not create new instance
2. public static void main(String args[]){
3. String s1="java";//creating string by java string literal
4.
In the above example only one object will be created. Firstly JVM will not find any string object with the value "Welcome" in string constant pool, so5. it char ch[]={'s','t','r','i','n','g','s'};
will create a new object. After that it will find the string with the value "Welcome" in the pool, it will not create new object but will return the reference String s2=new String(ch);//converting char array to string
6.
7.
to the same instance. 8. String s3=new String("example");//creating java string by new keyword
9.
Note: String objects are stored in a special memory area known as string constant pool. 10. System.out.println(s1);
11. System.out.println(s2);
12. System.out.println(s3);
13. }}
Why java uses concept of string literal? 14.
Test it Now
To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).
java
strings
example
Rules
Examples
public static void main( String[] args ) public class Mainthread public class Mainthread
run: {
{ {
64
String a, b; public static void main(String args[]) throws Exception public static void main(String args[]) throws Exception
saifur
a = "hello "; { {
String ch = "saifur";
b = "world"; char[] ch = {'s', 'a', 'i', 'f','u','r'};
System.out.println(ch);
System.out.println(a+b); System.out.println(ch);
}
} }
}
}
Pictures
Explanation
Opinion
Classification
Classes
import java.util.Scanner;
import java.util.StringTokenizer;
Methods
No. Method Description
65
1 char charAt(int index) returns char value for the particular index
2 int length() returns string length
3 static String format(String format, Object... args) returns formatted string
4 static String format(Locale l, String format, Object... args) returns formatted string with given locale
5 String substring(int beginIndex) returns substring for given begin index
6 String substring(int beginIndex, int endIndex) returns substring for given begin index and end
index
7 boolean contains(CharSequence s) returns true or false after matching the sequence
of char value
8 static String join(CharSequence delimiter, returns a joined string
CharSequence... elements)
9 static String join(CharSequence delimiter, Iterable<? returns a joined string
extends CharSequence> elements)
10 boolean equals(Object another) checks the equality of string with object
11 boolean isEmpty() checks if string is empty
12 String concat(String str) concatinates specified string
13 String replace(char old, char new) replaces all occurrences of specified char value
}
66
}
public class Mainthread
String name="sonoo";
System.out.println(sf1);
System.out.println(sf2);
System.out.println(sf3);
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
}
}
public class Mainthread
{
public static void main(String args[])
isEmpty() {
String s1 = "saifur";
String s2 = "";
67
System.out.println(s1.isEmpty());
System.out.println(s2.isEmpty());
}
}
public class Mainthread
{
public class Mainthread
public static void main(String args[])
{
{
public class Mainthread public static void main(String args[]) throws Exception
String s1 = "my name is saifur rahman";
{ {
String words[] = s1.split("\\s");
public static void main(String args[]) String stringA = "Wild";
int count = 0;
{ String stringB = " Irish";
for (String w:words)
String s1 = "saifur"; String stringC = " Rose";
{
concat() String result ;
count++;
System.out.println(s1); // String result ="";
}
s1 = s1.concat(" rahman"); // String result =null;
System.out.println(count);
System.out.println(s1);
for (int i = 0;i<count ; i++)
} result= stringA.concat( stringB.concat( stringC ) );
{
} System.out.println(result);
System.out.print(words[i]+" ");
}
}
}
}
}
public class Mainthread public class Mainthread
public class Mainthread
{ {
{
public static void main(String args[]) public static void main(String args[])
public static void main(String args[])
{ {
{
String s1 = "saifur rahman"; String s1 = "my name is isfat";
replace() String s1 = "my name is isfat";
s1 = s1.replace(" is ", " was ");
s1 = s1.replace('a', 'e'); s1 = s1.replace("is", "was");
System.out.println(s1);
System.out.println(s1); System.out.println(s1);
}
} }
}
} }
public class Mainthread
public class Mainthread {
{ public static void main(String args[]) throws
public static void main(String args[]) Exception
{ {
trim() String s1 = "my name is "; String s1 = " saifur rahman ";
} System.out.println(s1.trim());
} }
}
public class Mainthread public class Mainthread public class Mainthread
{ { {
public static void main(String args[]) public static void main(String args[]) public static void main(String args[])
{ { {
String s1 = "my name is saifur rahman"; for(declaration : expression) String s1 = "my name is saifur rahman"; String s1 = "my name is saifur rahman";
String word[] = s1.split("\\s"); { for (String words:s1.split("\\s", 0) ) String words[] = s1.split("\\s");
split()
//Statements { int count = 0;
System.out.println(word[0]); } System.out.println(words); for (String w:words)
for (String w:word) } {
{ for (String words:s1.split("\\s", 1) ) count++;
System.out.println(w); { }
} System.out.println(words); System.out.println(count);
68
} } }
} for (String words:s1.split("\\s", 2) ) }
{
System.out.println(words);
}
for (String words:s1.split("\\s", 15) )
{
System.out.println(words);
}
}
}
public class Mainthread
{
public static void main(String args[])
{
String s1 = "my name is saifur rahman";
indexOf()
System.out.println(s1.indexOf("name"));
int index = s1.indexOf("name");
System.out.println(index);
}
}
public class Mainthread
{
public static void main(String args[]) throws
Exception
{
String s1 = "saifur rahman";
substring()
System.out.println(s1.substring(0));
System.out.println(s1.substring(0, 6));
System.out.println(s1.substring(7));
}
}
public class Mainthread
{
public static void main(String args[]) throws
Exception
{
String s1 = "saifur rahman";
toUpperCase() and
toLowerCase() System.out.println(s1.toUpperCase());
System.out.println(s1);
System.out.println(s1.toLowerCase());
System.out.println(s1);
}
}
public class Mainthread
{
public static void main(String args[]) throws
Exception
startsWith() {
String s1 = "saifur rahman";
endsWith()
System.out.println(s1.startsWith("s"));
System.out.println(s1.endsWith("n"));
System.out.println(s1.endsWith("m"));
69
}
}
public class Mainthread
{
public static void main(String args[]) throws Exception
{
int a = 10;
The string valueOf() method coverts given
valueOf() type such as int, long, float, double, boolean,
char and char array into string. System.out.println(a+20);
String s = String.valueOf(a);
System.out.println(s+20);
}
}
Topics
String Comparison Topic
http://www.javatpoint.com/string-comparison-in-java
1. By equals() method
2. By = = operator
3. By compareTo() method
{
compareTo() method compares values and returns an int which tells if the
values compare less than, equal, or greater than. String s1 = "saifur";
String s2 = "saifur";
Suppose s1 and s2 are two string variables.If:
By compareTo() method s1 == s2 :0
String s3 = "Saifur";
String s4 = "rahman";
s1 > s2 :positive value
System.out.println(s1.compareTo(s2));
s1 < s2 :negative value
System.out.println(s1.compareTo(s3));
System.out.println(s1.compareTo(s4));
}
Methods
Public method Description
boolean hasMoreTokens() checks if there is more tokens available.
String nextToken() returns the next token from the StringTokenizer object.
String nextToken(String delim) returns the next token based on the delimeter.
{ {
hasMoreTokens() public static void main(String args[]) throws Exception public static void main(String args[]) throws Exception
nextToken() { {
nextToken( String delim) String s = "saifur rahman is a student of cse department"; String s = "saifur,rahman,is,a,student,of,cse,department";
while(st.hasMoreTokens()) while(st.hasMoreTokens())
70
{ {
System.out.println(st.nextToken()); System.out.println(st.nextToken(","));
} }
} }
} }
Practice
import java.util.Scanner;
b. A String literal
Thread Topic
https://thenewcircle.com/static/bookshelf/java_fundamentals_tutorial/threading.ht
http://www.javabeginner.com/learn-java/java-threads-tutorial http://www.javatpoint.com/multithreading-in-java
ml
Thread
71
Computer users take it for granted that their systems can do more than one thing at a time. They assume that they can continue to work in a word processor, whil e other
applications download files, manage the print queue, and stream audio. Even a single application is often expected to do mo re than one thing at a time. For example, that
streaming audio application must simultaneously read the digital audio off the network, decompress it, manage playback, and update its display. Even the word processor
should always be ready to respond to keyboard and mouse events, no matter how busy it is reformatting text or updating the display. Software that can do such things i s
known as concurrent software.
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of start() method
According to sun there is only 4 states in thread life cycle in java new, runnable, non-runnable and
2) Runnable
terminated. There is no running state. The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the
But for better understanding the threads, we are explaining it in the 5 states. running thread.
1. New 3) Running
2. Runnable The thread is in running state if the thread scheduler has selected it.
3. Running
4. Non-Runnable (Blocked)
5. Terminated
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
Thread Rules
Threads can: join, interrupt, sleep, yield, be prioritized, stack-dumped, be enumerated, grouped, etc. When different tasks should be performed parallel, Multiple threads are needed to execute code
Syntax
class NewThread implements Runnable
Thread creating
http://www.javaworld.com/article/2077138/java-concurrency/introduction-to-java-
threads.html
import java.lang.*;
import java.lang.*;
public class Counter implements Runnable
public class Counter extends Thread
{
{
Thread T;
extending a Thread class public void run() implementing an Runnable interface
public void run()
Extending the java.lang.Thread Class { Implementing the java.lang.Runnable Interface {
....
....
}
}
}
}
Extend the java.lang.Thread Class.
Override the run( ) method in the subclass from the Thread class to A Class implements the Runnable Interface, override the run() method
define the code executed by the thread. to define the code executed by thread. An object of this class is
Create an instance of this subclass. This subclass may call a Thread Runnable Object.
Extend Thread, override run(), instantiate, and start() Implement Runnable's run() and start() in a new Thread (preferred)
class constructor by subclass constructor. Create an object of Thread Class by passing a Runnable object as
Invoke the start( ) method on the instance of the class to make the argument.
thread eligible for running. Invoke the start( ) method on the instance of the Thread class.
72
http://www.roseindia.net/java/thread/thread-creation.shtml
System.out.println("Thread called");
th.start();
run:
Thread called
public class Test public class A extends Thread public class B extends Thread public class Test
{ { { {
public class A extends Thread public class B extends Thread
public static void main(String[] args) public void run() public void run() public static void main(String[] args)
{ {
{ { { {
public void run() public void run()
A th1 = new A(); for (int i=0; i<=5; i+=2) for (int i=0; i<=5; i+=2) System.out.println("Thread Started ..");
{ {
B th2 = new B(); { {
for (int i=0; i<=5; i+=2) for (int i=0; i<=5; i+=2)
th1.start(); System.out.println("Inside A Thread.."); System.out.println("Inside B Thread.."); A th1 = new A();
{ {
th2.start(); } } B th2 = new B();
System.out.println("Inside A Thread.. : i = "+ i); System.out.println("Inside B Thread.. : i = " + i);
} } } th1.start();
} }
} } } th2.start();
} }
System.out.println("Exit from main Thread..");
} }
}
}
run: rerun:
run: rerun:
Inside A Thread.. Inside B Thread..
Thread Started .. Thread Started ..
Inside A Thread.. Inside B Thread..
Exit from main Thread.. Exit from main Thread..
Inside A Thread.. Inside B Thread..
Inside A Thread.. : i = 0 Inside B Thread.. : i = 0
Inside B Thread.. Inside A Thread..
Inside A Thread.. : i = 2 Inside A Thread.. : i = 0
Inside B Thread.. Inside A Thread..
Inside A Thread.. : i = 4 Inside B Thread.. : i = 2
Inside B Thread.. Inside A Thread..
Inside B Thread.. : i = 0 Inside A Thread.. : i = 2
{ public class A extends Thread // Thread B public class B extends Thread // Thread B
for (int i=0; i<=5; i+=2) for (int i=0; i<=5; i+=2)
B th2 = new B(); // creating obj of Thread B System.out.println("Inside A Thread.. : i = "+ i); System.out.println("Inside B Thread.. : j = " + i);
}
73
public static void main(String[] args) public class A extends Thread // Thread B public class B extends Thread // Thread B public class C extends Thread // Thread C Inside A Thread.. : i = 0 Inside A Thread.. : i = 0 Inside A Thread.. : i = 0 Inside A Thread.. : i = 0
System.out.println("Thread Started .."); public void run() public void run() public void run() Inside B Thread.. : j = 0 Inside B Thread.. : j = 2 Exit from main Thread.. Inside A Thread.. : i = 4
{ { { Exit from main Thread.. Inside B Thread.. : j = 4 Inside C Thread.. : k = 0 Exit From Thread A ...
A th1 = new A(); // creating obj of Thread A for (int i=0; i<=5; i+=2) for (int i=0; i<=5; i+=2) for (int i=0; i<=5; i+=2) Inside A Thread.. : i = 4 Exit From Thread B ... Inside C Thread.. : k = 2 Exit from main Thread..
B th2 = new B(); // creating obj of Thread B { { { Exit From Thread A ... Exit from main Thread.. Inside C Thread.. : k = 4 Inside B Thread.. : j = 0
C th3 = new C(); // creating obj of Thread C System.out.println("Inside A Thread.. : i = "+ i); System.out.println("Inside B Thread.. : j = " + i); System.out.println("Inside B Thread.. : k = " + i); Inside C Thread.. : k = 0 Inside C Thread.. : k = 0 Exit From Thread C ... Inside B Thread.. : j = 2
th1.start(); // Calls run() method of Thread A } } } Inside B Thread.. : j = 2 Inside A Thread.. : i = 2 Inside B Thread.. : j = 0 Inside B Thread.. : j = 4
th2.start(); // Calls run() method of Thread B System.out.println("Exit From Thread A ..."); System.out.println("Exit From Thread B ..."); System.out.println("Exit From Thread C ..."); Inside B Thread.. : j = 4 Inside C Thread.. : k = 2 Inside B Thread.. : j = 2 Exit From Thread B ...
th3.start(); // Calls run() method of Thread C } } } Exit From Thread B ... Inside A Thread.. : i = 4 Inside A Thread.. : i = 4 Inside C Thread.. : k = 0
System.out.println("Exit from main Thread.."); } } } Inside C Thread.. : k = 2 Inside C Thread.. : k = 4 Exit From Thread A ... Inside C Thread.. : k = 2
} Inside C Thread.. : k = 4 Exit From Thread A ... Inside B Thread.. : j = 4 Inside C Thread.. : k = 4
} Exit From Thread C ... Exit From Thread C ... Exit From Thread B ... Exit From Thread C ...
{ void display()
} Inside A Thread.. : i = 2
th1.start(); // Calls run() method of Thread A public void run() Inside A Thread.. : i = 4
} }
new NewThread(); // create a new thread { Child Thread: 5 NewThread th = new NewThread(); { Child Thread: 5
try // Create a new, second thread Child Thread: 4 // new NewThread(); // create & call a new thread // Create a new, second thread Child Thread: 4
{ t = new Thread(this, "Demo Thread"); Child Thread: 3 try super("Demo Thread"); Main Thread: 4
for(int i = 5; i > 0; i--) System.out.println("Child thread: " + t); Main Thread: 4 { System.out.println("Child thread: " + this); Child Thread: 3
{ t.start(); // Start the thread Child Thread: 2 for(int i = 5; i > 0; i--) start(); // Start the thread Child Thread: 2
Thread.sleep(1000); // This is the entry point for the second thread. Child Thread: 1 System.out.println("Main Thread: " + i); // This is the entry point for the second thread. Child Thread: 1
} public void run() Exiting child thread. Thread.sleep(1000); public void run() Exiting child thread.
System.out.println("Main thread exiting."); System.out.println("Child Thread: " + i); } System.out.println("Child Thread: " + i);
} } } }
} } }
{ {
} }
} }
} }
{
class ExtendThread
NewThread2()
{
{
public static void main(String args[])
start();
{
}
new NewThread2(); run:
public void run()
try Main : 0
{
{ Child : 0
try
for (int i=0;i<5 ; i++) Main : 1
{
{ Child : 1
for (int i=0;i<5 ; i++)
System.out.println("Main : "+i); Main : 2
{
Thread.sleep(1000); Child : 2
System.out.println("Child : "+i);
} Main : 3
Thread.sleep(1000);
} Child : 3
}
catch(Exception err) Child : 4
}
{ Main : 4
catch(Exception err)
{
}
}
}
}
}
Lynda
public class Mainthread public class A extends Thread run: public class Mainthread public class A implements Runnable run:
public static void main(String[] args) public void run() Inside A Thread.. : j = 0 public static void main(String[] args) public void run() Inside A Thread.. : j = 0
try for (int i=0; i<=3; i++) Inside A Thread.. : j = 2 try for (int i=0; i<=3; i++) Inside Main Thread.. : i = 2
{ { Inside A Thread.. : j = 3 { { Inside Main Thread.. : i = 3
for (int i=0; i<=3; i++) System.out.println("Inside A Thread.. : j = "+ i); Inside Main Thread.. : i = 3 for (int i=0; i<=3; i++) System.out.println("Inside A Thread.. : j = "+ i); Inside A Thread.. : j = 3
{ sleep(1000*2); { Thread.sleep(1000*2);
System.out.println("Inside Main Thread.. : i = "+ i); } System.out.println("Inside Main Thread.. : i = "+ i); }
Thread.sleep(1000*2); } Thread.sleep(1000*2); }
} { } {
catch(Exception err) catch(Exception err)
{ } { }
} }
} } } }
} }
} }
Thread t; {
System.out.println(err); }
{
public class A implements Runnable
//do not use this
{
//Thread t;
Thread t;
static int i=0;
static int i=0;
A(String name, int p)
A(String name, int p)
{
{
super(name);
public class Mainthread class A implements Runnable public class Mainthread class A implements Runnable
{ { { {
public static void main(String args[]) Thread t; public static void main(String args[]) Thread t;
A t2=new A("t2", 5); t = new Thread(this, threadName); A t2=new A("t2", 5); t = new Thread(this, threadName);
} } } t.sleep(500);
77
} } } }
} catch(Exception e) } }
{ catch(Exception e)
System.out.println(e); {
} System.out.println(e);
} }
} }
int count;
}
try
System.out.print("Prime Number"+"\n");
{
new Thread(x).start();
new Thread(y).start();
}
System.out.print(count+"\n");
}
78
Thread t;
t.setPriority(p);
try
for (; i<=100; )
if (t.getName().compareTo("One") == 0)
isOddEvens(i);
i++;
if (t.getName().compareTo("Two") == 0);
isPrimeNumber(i);
i+=2;
if (t.getName().compareTo("Three") == 0);
fact(i);
i+=3;
Thread.sleep(1000);
catch(Exception err)
System.out.println(err);
}
}
Rules
Examples
Pictures
79
80
Explanation
81
New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the
thread. It is also referred to as a born thread.
Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is
considered to be executing its task.
Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for another thread to
perform a task.A thread transitions back to the runnable state only when another thread signals the waiting
thread to continue executing.
Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in
this state transitions back to the runnable state when that time interval expires or when the event it is waiting
for occurs.
Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.
Opinion
Classification
}
}
System.out.println("Exit From Thread A ...");
}
}
public class Mainthread public class Mainthread
{ {
public static void main(String[] args) public static void main(String[] args)
{ {
Thread t = Thread.currentThread(); Thread t = Thread.currentThread();
t.setName("MyThread"); System.out.println("Current Thread is : "+t);
System.out.println(t); t.setName("My Thread");
for (int i=0;i<5 ; i++) System.out.println("changed Thread name is : "+t); run:
run:
{ for (int i=0;i<5 ;i++ ) Current Thread is : Thread[main,5,main]
Thread[MyThread,5,main]
System.out.println(t +" : "+ i); { changed Thread name is : Thread[My Thread,5,main]
Thread[MyThread,5,main] : 0
try System.out.println(t+" : "+ i); Thread[My Thread,5,main] : 0
Thread[MyThread,5,main] : 1
{ try Thread[My Thread,5,main] : 1
Thread[MyThread,5,main] : 2
Thread.sleep(1000); { Thread[My Thread,5,main] : 2
Thread[MyThread,5,main] : 3
// t.sleep(1000); Thread.sleep(1000); Thread[My Thread,5,main] : 3
Thread[MyThread,5,main] : 4
} } Thread[My Thread,5,main] : 4
catch(Exception err) catch(Exception err)
{ {
} }
} }
} }
} }
public class A extends Thread
{
public class Mainthread
public void run()
{
{ public class B extends Thread public class C extends Thread // Thread C
public static void main(String[] args)
for (int i=0; i<=5; i++) { {
{
{ public void run() public void run()
System.out.println("Starting main thread..");
System.out.println("Inside A Thread.. : i = "+ i); { {
A th1 = new A();
try for (int i=0; i<=5; i++) for (int i=0; i<=5; i++)
B th2 = new B();
{ { {
C th3 = new C();
sleep(2000); System.out.println("Inside B Thread.. : j = " + i); System.out.println("Inside C Thread.. : k = " + i);
th1.start();
} if(i==2) if (i%2==0)
th2.start();
catch(Exception E) stop(); yield();
th3.start();
{ } }
System.out.println("Exit From Thread B ..."); System.out.println("Exit From Thread C ...");
System.out.println("Exiting main thread..");
} } }
}
} } }
}
System.out.println("Exit From Thread A ...");
}
}
sleep(), yield(),
run:
stop() Starting main thread..
Inside A Thread.. : i = 0
Exiting main thread..
Inside B Thread.. : j = 0
Inside B Thread.. : j = 1
Inside B Thread.. : j = 2
Inside C Thread.. : k = 0
Inside C Thread.. : k = 1
Inside C Thread.. : k = 2
Inside C Thread.. : k = 3
Inside C Thread.. : k = 4
Inside C Thread.. : k = 5
Exit From Thread C ...
Inside A Thread.. : i = 1
Inside A Thread.. : i = 2
Inside A Thread.. : i = 3
Inside A Thread.. : i = 4
Inside A Thread.. : i = 5
Exit From Thread A ...
public class Mainthread
{ public class A extends Thread public class B extends Thread public class C extends Thread // Thread C
public static void main(String[] args) { { {
{ public void run() public void run() public void run()
System.out.println("Starting main thread.."); { { {
A th1 = new A(); for (int i=0; i<=3; i++) for (int j=0; j<=3; j++) for (int k=0; k<=3; k++)
setpriority() B th2 = new B(); { { {
C th3 = new C(); System.out.println("Inside A Thread.. : i = "+ i); System.out.println("Inside B Thread.. : j = " + j); System.out.println("Inside C Thread.. : k = " + k);
th1.setPriority(Thread.MIN_PRIORITY); } } }
th2.setPriority(Thread.MAX_PRIORITY); System.out.println("Exit From Thread A ..."); System.out.println("Exit From Thread B ..."); System.out.println("Exit From Thread C ...");
th3.setPriority(th1.getPriority()+2); } } }
th1.start(); } } }
th2.start();
84
th3.start();
Synchronization Topic
There are two types of synchronization
Synchronization in java is the capability of control the access of multiple threads to any shared resource.
Process Synchronization
Java Synchronization is better option where we want to allow only one thread to access the shared resource.
Thread Synchronization
85
Extra knowledge
Stream class :
File stream
i/o stream
Java defines two types of streams:
Character streams provide a convenient means for handlinginput and output of characters. They use
Unicode
Definitions
Rules
i/o stream
OutputStream
InputStream
Java application uses an output stream to write data to a destination, it may be a file,an array,peripheral device or socket.
Java application uses an input stream to read data from a source, it may be a file,an array,peripheral device or socket.
Method Description
1) public void write(int)throws IOException: is used to write a byte to the current output stream.
2) public void write(byte[])throws IOException: is used to write an array of byte to the current output
stream.
4) public void close()throws IOException: is used to close the current output stream.
Notice the use of the for-slash (the normal slash character) as directory separator. That is how you write file
paths on unix. Actually, in my experience Java will also understand if you use a / as directory separator on
FileInputStream Constructors Windows (e.g.c:/user/data/thefile.txt), but don't take my word for it. Test it on your own system!
The FileInputStream class has a three different constructors you can use to create The second FileInputStream constructor takes a File object as parameter. The File object has to
a FileInputStream instance. I will cover the first two here. point to the file you want to read. Here is an example:
The FileInputStream class makes it possible to read the
contents of a file as a stream of bytes. String path = "C:\\user\\data\\thefile.txt"; String path = "C:\\user\\data\\thefile.txt";
TheFileInputStream class is a subclass of InputStream. This
means that you use the FileInputStream as File file = new File(path);
anInputStream (FileInputStream behaves like
FileInputStream fileInputStream = new FileInputStream(path);
an InputStream)
FileInputStream fileInputStream = new FileInputStream(file);
Notice the path String. It needs double backslashes (\\) to create a single backslash in the String,
because backslash is an escape character in Java Strings. To get a single backslash you need to use the
escape sequence \\. Which of the constructors you should use depends on what form you have the path in before opening
theFileInputStream. If you already have a String or File, just use that as it is. There is no particular
On unix the file path could have looked like this: gain in converting a String to a File, or a File to a String first.
86
import java.io.*;
int i;
while((i=fis.read())!=-1)
System.out.print((char)i);
}
fis.close();
import java.io.*;
import java.util.*;
// FileWriter fw = new
FileWriter("C:\\Users\\user\\Desktop\\Saifur\\s.ini");
}
}
FileOutputStream
http://www.javatpoint.com/FileInputStream-and-FileOutputStream
import java.io.*;
import java.util.*;
import java.io.*;
import java.io.*;
public class Mainthread
public class Mainthread public class Mainthread
{
{ {
public static void main(String args[]) throws Exception
public static void main(String args[]) throws Exception public static void main(String args[]) throws Exception
{
{ {
FileOutputStream fos = new FileOutputStream("FileOutputStream.txt");
FileOutputStream fos = new FileOutputStream("filecreation.ini"); FileOutputStream fos = new FileOutputStream("Write.txt");
String s ="Saifur rahman";
String s = "saifur rahman"; Scanner sc = new Scanner(System.in);
byte[] b = s.getBytes();
byte[] b = s.getBytes(); String s = sc.nextLine();
fos.write(b);
fos.write(b); byte[] b = s.getBytes();
fos.close();
} fos.write(b);
}
} fos.close();
}
}
Pictures
Explanation
87
Opinion
Classification
import java.util.*;
import java.io.*;
Chapter 6
(Vector Topic)
Empty Vector
package saifur.vector;
import java.util.*;
Vector Operation
import java.util.Vector;
88
class ex1{
public static void main(String[] args) {
Vector v = new Vector();
System.out.println(v);
System.out.println(v.size());
}
}
methods
import java.util.Vector;
class ex1{
public static void main(String[] args) {
capacity() Vector v = new Vector();
ensureCapacity() System.out.println(v.capacity());
v.ensureCapacity(50);
System.out.println(v.capacity());
}
}
import java.util.Vector;
class ex1{
public static void main(String[] args) {
Vector name = new Vector();
addElement() name.addElement("saifur");
name.addElement("masud");
elementAt() name.addElement("ricki");
import java.util.Vector;
class ex1{
public static void main(String[] args) {
Vector name = new Vector();
name.addElement("saifur");
name.addElement("masud");
name.addElement("ricki");
}
}
}
import java.util.Vector;
class ex1{
public static void main(String[] args) {
Vector name = new Vector();
name.addElement("saifur");
name.addElement("masud");
name.addElement("ricki");
System.out.println("name.size() = "+name.size());
name.removeElementAt(2);
name.insertElementAt("ridoy", 2);
}
}
}
v1.addElement("sa"); v1.addElement("sa");
System.err.println(v1.size()); v1.addElement("ads");
System.err.println(v1.elements()); v1.addElement("sasdfa");
System.err.println(v1.elements().nextElement());
} Enumeration e = v1.elements();
} while (e.hasMoreElements())
{
1 run: System.err.println(e.nextElement());
java.util.Vector$1@1db9742 sa }
sa ads }
sasdfa }
arrays/
http://mindprod.com/jgloss/jche
at.html
Java is not a
javascript Operating system Not for just internet Tiny language
JDK Java development kit JSE Java standard edition J2RE Java 2 runtime edition J2ME Java two micro edition J2EE Java two enterprise edition
extensions
.java
object method
public class hello{ System.out == object println("hello world"); == method
public static void main(String[] args) {
System.out.println("hello world");
}
}
Java begin
1. We begin defining a class to hold our code public class Howdy { All java program begin execution with the method public class Howdy {
} public static void main(String arg[]) {
name main. So that must be declared first like this }
}
93
Class in java
My resource class declaration Classes contains
In general, class declarations can include these components, in order: 1. the first letter of a class name should be capitalized
1. PDF class MyClass { 1. Modifiers such as public, private, and a number of others that you will encounter
2. WEB 1. Fields later.
// field, constructor, and 2. Constructors
3. ***oracle (click here) 2. The class name, with the initial letter capitalized by convention.
// method declarations 3. Methods 3. The name of the class's parent (superclass), if any, preceded by the keyword
4. extends. A class can only extend (subclass) one parent.
class body 4. A comma-separated list of interfaces implemented by the class, if any, preceded by
the keyword implements. A class can implement more than one interface.
} 5. The class body, surrounded by braces, {}.
public class Mother{
}
Methods in java
1. the first (or only) word in a method name should be a verb.
94
Object in java
My resource
1. pdf
2. web
95
1. http://docs.oracle.com/javase/6/docs/api/overview-frame.html 1. http://docs.oracle.com/javase/6/docs/api/allclasses-frame.html
2. http://docs.oracle.com/javase/6/docs/api/
2. http://docs.oracle.com/javase/6/docs/api/
3.
3.
96
First program
public class hello{
Variables declaration
1. 2. 3.
public class variables { public class variables{ Here are the next two lines in the program:
public static void main(String args[]) { public static void main(String args[]){
int a=5, b=10, sum=a+b; System.out.print("var2 contains var1 / 2: ");
int var1; // this declares a variable^ Declare variables.
System.out.println(var2);
int var2; // this declares another variable
System.out.println(a);
var1 = 1024; // this assigns 1024 to varH Assign a variable a System.out.println(b); Two new things are occurring here. First, the built-in method print( ) is used to display the
value. string "var2 contains var1 / 2: ". This string is not followed by a new line. This means that
System.out.println(sum); when the next output is generated, it will start on the same line. The print( ) method is just
System.out.println("var1 contains " + var1); like println(), except that it does not output a new line after each call. Second, in the call to
System.out.println("The sum of the two println(),
var2 = var1 / 2;
System.out.print("var2 contains var1 / 2: "); numbers is = " + sum);
System.out.println(var2);
} }
} }
4.
public class variables{
public static void main(String args[]){
int a=5, b=10, sum=a+b;
System.out.println(a);
System.out.println(b);
System.out.print(sum);
}
}
Output:
5
10
15The sum of the two numbers is = 15
15
char c = 'A';
char 16 0 216-1
char c = 65;
Integer
short 16 -215 215-1 short s = 65;
Floating-point
double 64 2-1074 (2-2-52)·21023 double d = 65.55;
1.int 1.float 1.
2.double(most commonly used) public class dataType {
10.0 gallons is 37.854 liters. System.out.println(); // print a blank line ^ Output a blank line.
// now, divide both by 4
var = var / 4; x = x / 4;
System.out.println("var after division(int): " + var);
System.out.println("x after division(double): " + x);
}
2.
/*
Project 1-1
This program converts gallons to liters.
Call this program GalToLit.java.
*/
class GalToLit {
public static void main(String args[]) {
double gallons; // holds the number of gallons
double liters; // holds conversion to liters
The if statement
if (condition) { if (condition) { if (condition) { if (condition) {
//condition is a Boolean expression
} else { } }
}
else if (condition) { else if (condition) {
}
} }
else { else if {
} }
public class variables{
public static void main(String args[]){
int a=5, b=10, sum=a+b;
if (a==b) {
System.out.println("This is not a true
boolean expression / condition ");
}
else if (a<b) {
System.out.println("(a<b) This is a
true boolean expression / condition ");
}
if (sum ==(a+b)) {
System.out.println("(sum ==(a+b)) This
is a true boolean expression / condition ");
}
}
}
100
operators
Operator Meaning
< Less than
<= Less than or equal
> Greater than
>= Greater than or equal
== Equal to
!= Not equal
* asterisk
for loop
for (int i = 0; i < args.length; i++) { for (int i = 0; i < args.length; i++) { for (java.util.Iterator iterator = collection.iterator(); iterator
.hasNext();) {
} type type = (type) iterator.next();
}
}
public class variables { public class variables {
public static void main(String args[]) { public static void main(String args[]) {
int count; int count;
for(count = 0; count < 5; count++){ for(count = 0; count < 50; count++){
System.out.println("This is count: " + count); System.out.println(count + " gallons is "+count * 3.7854 + "
} litres");
if (count % 10== 0){
System.out.println("Done!"); System.out.println();
}
} }
}
}
}
101
keywords
abstract assert boolean break byte case
catch char class const continue default
volatile while