Вы находитесь на странице: 1из 102

Java Programming Language

Md. Saifur Rahman Java Programming Basic Concept


1

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

http://docs.oracle.com/javase/tutorial/java/ http://beginnersbook.com/2013/05/method-overloading/ http://www.tutorialspoint.com/java/ http://www.javatpoint.com/static-keyword-in-java


http://guru99.com/java-tutorial.html http://crunchify.com/java-tips-never-make-an-instance-fields-of-class-public/

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

198, 198, 197 214, 199, 174


204, 192, 174 234, 220, 197
237, 203, 200 221, 206, 184
192, 204, 172 205, 193, 183
172, 182, 170 197, 213, 205
226, 239, 217 235, 239, 255
245, 245, 220 210, 210, 210
233, 233, 233 233, 234, 234
211, 211, 211 255, 251, 230
225, 230, 246 210, 225, 240
220, 225, 237 237, 237, 237
227, 204, 233 208, 216, 222
233, 226, 171 242, 236, 185
175, 201, 194 253, 248, 212
234, 217, 154 196, 207, 187
250, 224, 206

Importance of topics
3

*** Most important ** Less important * important

Introduction to Computers and Java

 The smallest data item in a computer can assume the value 0 or


the value 1. Such a data item is called a bit
 characters are composed of bits. characters that are composed
of two bytes
 fields are composed of characters or bytes. A field is a group of
characters or bytes that conveys meaning.

Compiling a Java Program into Bytecodes


4

To compile To execute
javac Welcome.java java Welcome

Things We need to know


 The three types of languages discussed in the chapter are machine languages, assembly languages, high-level languages.
 The programs that translate high-level language programs into machine language are called compilers
 Android is a smartphone operating system based on the Linux kernel and Java.

Ashiq sir in class main concepts


Lecture 1
1.

Lecture 2
5

(9/29/2014)
tools NetBeans ide 8.1 link https://netbeans.org/downloads/

books java the complete reference 9th edition herbert schildt

File create File > new Project > java > java Application > project name + project location > finish

Java program works

1. Function = method 4. In java main() is not mandatory but not execute


C Java
Few little concepts 2. Add = class name (With starting capital letter) 5. In business we can give class file not source file but class file can
3. add() = Method (With starting lower case ) convert into Source code include import
Object 1. Object = set of attributes = like structure
1. Encapsulation ( লু কিয়ে রাখা )
OOP must have 3 things 2. Polymorphism ( বহুরূপতা)
3. Inheritance ( উত্তরাকিিার)
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
Environment = class
class
5. User defined data-type
 Fruit is a class then object = (mango , jackfruit, banana, etc)
6. Set of objects
Declaration
class className
{
member variable declaration;
member fuction defination;
}

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;

public class Method_overloading1 1. program begins with a call to main() method.


import java.io.*;
{ 2. In main( ), there is only one parameter, albeit a complicated one. String args[ ] declares a parameter
public static void main(String args[]) named args, which is an array of instances of the class String. (Arrays are collections of similar objects.)
class Class2
{ 3. Output is actually accomplished by the built-in println( ) method & displays the string which is passed to it.
{
First program public static void main(String args[])
int num = 7; & println( ) can be used to display other types of information, too. The line begins with System.out,
if(num % 2 == 0) System is a predefined class that provides access to the system, and out is the output stream that is
{
{ connected to the console.
System.out.println("Hello world");
System.out.println("Even"); 4. All statements in Java end with a semicolon.
}
} 5.
else
}
{
System.out.println("Odd");
}
6

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

public class Input


{
public static void main(String args[])
{
System.out.print("Entert a number to check odd/even = ");
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();

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

Introduction to Java Applications


{ = an opening left brace
} = the closing right brace
C

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

System.out.print("Enter " + n +" integers = "); if ( status != 0 )


{
for (i = 0; i < n; i++) System.out.println(num);
count++;
a[i] = sc.nextInt(); }
status = 1;
num++;
for (i = 0; i < n; i++) }
}
{ }

if (a[i] > maximum)

maximum = a[i];
location = i+1;

System.out.println("Maximum element number located at "+ location + " and it's


value is = " + maximum);

Enter the number of elements in array = 3

Enter 3 integers = 6

8
2

Maximum element number located at 2 and it's value is = 8


10

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

// field, constructor, and

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

public static void main(String args[])

Box myBox = new Box();

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

Member instance Variable

Class's Member instance methods/Function


Members

Object of another class which is declared


in current class
class classname {
type instance-variable1;
type instance-variable2;
Thus in short Class have - // ...
1. Class name type instance-variableN;
2. Properties or Attributes type methodname1(parameter-list) {
3. Common Functions // body of method
}
type methodname2(parameter-list) {
// body of method
Syntax of Class : }
 A Class is a blueprint or a template to create objects of identical type. // ...
 A Class is core concept of Object Oriented Programming Language. type methodnameN(parameter-list) {
// body of method
}
}

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

1. Inherit property of another class


2. a class to inherit property of another class
3.
class Vehicle  Vehicle is super class of Car.
{  Car is sub class of Vehicle.
......  Car IS-A Vehicle.
}

class Car extends Vehicle


{
....... //extends the property of vehicle
class.
}

Pictures
12

Single Inheritance

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

 Multiple inheritance is not supported in java


 Multilevel inheritance is supported not multiple inheritance

 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

package personal; package personal;

Vehicle
class Vehicle class Vehicle
{ { Vehicle
void method() void method()
{ {
System.out.println("class Vehicle is showing"); System.out.println("class Vehicle is showing");
} }
} }

class Car extends Vehicle class Car extends Vehicle


Car Gear
{ {
void method()
{
Car void method()
{
System.out.println("class Car is showing"); System.out.println("class Car is showing");
}
} }
}
class Gear extends Vehicle
Showing
class Gear extends Car {
{ void method()
void method()
Gear {
{ System.out.println("class Gear is showing");
System.out.println("class Gear is showing"); }
} }
}
public class constructor
public class constructor Showing {
{ public static void main(String args[])
public static void main(String args[]) {
{ Gear obj = new Gear();
Gear obj = new Gear(); obj.method();
obj.method(); }
} }
}

Constructor Topic
http://www.javatpoint.com/constructor

Rules for creating constructor

There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type

package personal;

class ClassName // a class definition


{
int a;
int b;
package personal;
ClassName() //constructor
class Classname // a class definition
{ package personal;
{
a = 10; class Const
int a;
b = 20; {
int b;
} int length, width;
int classmethod() Const(int len, int wid)
Classname() //constructor
{ {
{
a = 30; length = len;
a = 10;
b = 40; width = wid;
b = 20;
return 0; // or void }
}
} }
}
}
public class constructor public class constructor public class constructor {
{
{ public static void main(String args[])
public static void main(String args[])
public static void main(String args[]) {
{
{ Const obj = new Const(10, 20);
Classname obj = new Classname(); // an obj
ClassName obj = new ClassName(); // an obj System.out.println("length "+ obj.length);
creation
creation }
}
System.out.println(obj.a + obj.b);
System.out.println(obj.a + obj.b);
}
}
obj.classmethod();
System.out.println(obj.a + obj.b);
}
}

Live Example : How Constructor Works ?


class Rectangle {
int length;
int breadth;
Constructors : Initializing an Class Object in Java Programming Some Rules of Using Constructor :
Rectangle()
1. Objects contain there own copy of Instance Variables. 1. Constructor Initializes an Object. {
2. It is very difficult to initialize each and every instance variable of each and every object of Class. 2. Constructor cannot be called like methods. length = 20;
3. Java allows objects to initialize themselves when they are created. Automatic initialization is 3. Constructors are called automatically as soon as object gets created. breadth = 10;
performed through the use of a constructor. 4. Constructor don't have any return Type. (even Void) }
4. A Constructor initializes an object as soon as object gets created. 5. Constructor name is same as that of "Class Name". }
5. Constructor gets called automatically after creation of object and before completion of new 6. Constructor can accept parameter.
class RectangleDemo {
Operator.
public static void main(String args[]) {

Rectangle r1 = new Rectangle();

System.out.println("Length of Rectangle : " + r1.length);


System.out.println("Breadth of Rectangle : " + r1.breadth);
14

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

System.out.println("Length of Rectangle : " + r1.length);


System.out.println("Length of Rectangle : " + r1.length); System.out.println("Breadth of Rectangle : " + r1.breadth);
System.out.println("Breadth of Rectangle : " + r1.breadth);
r1.setDiamentions();

System.out.println("Length of Rectangle : " + r1.length);


System.out.println("Breadth of Rectangle : " + r1.breadth);

}
}

Parameterized Constructors : Constructor Taking Parameters


In this article we are talking about constructor that will take parameter. Constructor taking
parameter is called as "Parameterized Constructor".

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

Rectangle r1 = new Rectangle(20,10);

System.out.println("Length of Rectangle : " + r1.length);


System.out.println("Breadth of Rectangle : " +
r1.breadth);

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

3) Have both different numbers of arguments with a difference in their types.

4) number of arguments & types of arguments cannot be same

1. public void getEmpName(int empId) {


2. ...... 2. Method Overloading occurs when methods are having same
3. } name, but
4.
5. public void getEmpName(String empName) {
3. A difference in the number of their parameters or type of their
6. ...... parameters or both.
7. }
15

8.
9. public void getEmpName(int empId, String empName) {
10. ......
11. }
12.
13. public void getEmpName(Date dob, String empName) {
14. ......
15. }

1. Constructor method name = container class name


2. Constructor method always declared as a public
3. It has no return type even void too
4. It’s being called automatically we do not need to call this
5. It can have arguments
6.
package personal;
class Student
{
String name;
package personal; int roll;
class Student float mark;
{ Student(String name, int roll, float mark)
String name; {
int roll; this.name = name;
package personal; float mark; this.roll = roll;
Student() this.mark = mark;
public class constructor { { }
public constructor() name = "Md. Saifur Rahman";
{ roll = 67; }
System.out.println("Constructor auto called at the mark = 70;
time of initializing object"); } public class ConstructorCallingExplain
} {
} public static void main(String args[])
public static void main(String args[]) {
{ public class ConstructorCallingExplain { Student obj1 = new Student("saifur", 67, 70.0f);
constructor obj = new constructor(); //auto called public static void main(String args[]) Student obj2 = new Student("rasel", 58, 75.5f);
} {
} Student obj = new Student(); System.out.println(obj1.name);
System.out.println(obj.name); System.out.println(obj1.roll);
System.out.println(obj.roll); System.out.println(obj1.mark);
System.out.println(obj.mark);
} System.out.println(obj2.name);
} System.out.println(obj2.roll);
System.out.println(obj2.mark);
}
}

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:

Declaration: A variable declaration with a variable name with an object type.

Instantiation: The 'new' key word is used to create the object.

Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes the new object.

students s1 = new students();


Point originOne = new Point(23, 94);
16

Rectangle rectOne = new Rectangle(originOne, 100, 200);


Rectangle rectTwo = new Rectangle(50, 100);
1. Suppose a gentleman wants to marry a woman who has 3 childs. He
wants to take care of them too.
1. We create an object to create a reference 2. He can control the childs when he becomes the stepfather
3. Until then he has no right to take care or control the childs
2. To access class’s members
4. So, to make the childs as his own he has to marry that woman
3. The man = object or reference or instance of the woman class
The women = class of the man object
The childs = instance member variables of the woman class
package class3;

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

System.out.println("Age of the child1 = " + man.child1);


}
}

To access instance variables & initializing it

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.

Nesting member object

package personal;

class GrandSon
{

class GrandDaughter
{

class Son
{
GrandSon obj1 = new GrandSon();
GrandDaughter obj2 = new GrandDaughter();
}

class GrandFather
{
Son obj3 = new Son();
}

Passing Object as Parameter


package personal; package personal;

class Rectangle // a class definition class Rectangle // a class definition


{ {
int length; int length;
int width; int width;

Rectangle(int l, int b) //constructor Rectangle(int l, int b) //constructor


{ {
length = l; length = l;
width = b; width = b;
} }

void area(Rectangle obj) void rect (int length, int width)


{ {
System.out.println("Area = " + (obj.length * obj.width)); System.out.println("area = " + (length*width));
} }
} }
public class constructor public class constructor
{ {
public static void main(String args[]) public static void main(String args[])
{ {
Rectangle obj = new Rectangle(20, 8); // an obj creation Rectangle obj = new Rectangle(10, 5);
obj.rect(obj.length, obj.width);
obj.area(obj);
} }
} }

Object as method’s argument


18

Vehicle

Call by Call by
Value reference

Object as method’s return type

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.

Passing Object as Parameter


package com.pritesh.programs;

class Rectangle {
int length;
int width;

Rectangle(int l, int b) {
length = l;
width = b;
}

void area(Rectangle r1) {


int areaOfRectangle = r1.length * r1.width;
System.out.println("Area of Rectangle : "
+ areaOfRectangle);
}
}

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

public class NestingMemberObject


{
public static void main(String args[])
{
MethodAccessChecker obj = new
MethodAccessChecker();
obj.method2();
obj.method1();
obj.method2();
}
}

A Closer Look at new


1. the new operator dynamically allocates memory for an object
19

Polymorphism Topic

Method Overloading
Polymorphism http://beginnersbook.com/2013/03/polymorphism-in-java/

Method Overriding

Difference between Overloading & overriding


Method Overloading Method Overriding
1. http://www.programmerinterview.com/index.php/java-questions/method-overriding-vs-overloading/ 1.
2.
1. If a derived class requires a different definition for an inherited method, then that method can be redefined in the derived
class. This would be considered overriding. An overridden method would have the exact same method name, return type,
number of parameters, and types of parameters as the method in the parent class, and the only difference would be the
1. Method overloading in Java occurs when two or more methods in the same class have the exact same name but different definition of the method.( overriding a method everything remains exactly the same except the method definition)
parameters (remember that method parameters accept values passed into the method). 2. overriding is a run time phenomenon – not a compile time phenomenon like method overloading
2. The conditions for method overloading 3. overloading is static polymorphism whereas overriding is dynamic polymorphism
o The number of parameters is different for the methods. 4. Argument list should be different while doing method overloading. Argument list should be same in method Overriding.
o The parameter types are different (like changing a parameter that was a float to an int). 5. you can overload method in same class but you can only override method in sub class.
6. private and final method can not be overridden but can be overloaded in Java.
7. Overloaded method are fast as compare to Overridden method in Java.
8.
 Overriding means having two methods with the same method name and arguments (i.e., method signature). One of them is in the P arent class and the other is in
 Overloading is the situation that two or more methods in the same class have the same name but different arguments. the Child class.

Overloading Overriding

Happening within the same class. Happening between super class and sub class.

Method signature should not be same. Method signature should be same.

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

Method must have same or wide access level than super


Method can have any access level. class method access level.
20

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 method declared final cannot be overridden.

 A method declared static cannot be overridden but can be re-declared.

 If a method cannot be inherited, then it cannot be overridden.

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

 Constructors cannot be overridden.

Examples
package overriding ;
package overriding ;
class Animal{ class Animal{

public void move(){


System.out.println("Animals can move");
public class Caller{ }
public void move(){ }

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[]){

Animal b = new Dog(); // Animal reference but Dog object


public void move(){ b.move(); //Runs the method in Dog class
b.move();//Runs the method in Dog class
System.out.println("Dogs can walk and run"); }
} }
}
}
}

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

int result = b1.calculate(10, 10); }


}
} System.out.println("Result : " + result);

Method in Vehicle. run:

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

Access Level in Parent Access Level in Child Allowed ?


Public Public Allowed

Public Private Not Allowed

Public Protected Not Allowed

Public No Modifier Allowed

Protected Public Allowed

Protected Protected Allowed, I think not allowed


23

Protected Private Not Allowed

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.

First, it allows you to fix the error.

 Second, it prevents the program from automatically terminating.


 Most users would be confused (to say the least) if your program

Opinion

Classification
25

Loop Topic
 

Definitions
6.

General forms

Rules

Examples
package saifur;
import java.util.*;

public class Saifur {

public static void main(String[] args)


{
Scanner sc = new Scanner(System.in);
while(true)
{
String s = sc.nextLine();
if(s.compareTo("exit")==0)break;
System.err.print("Sunny Says ");
if(s.compareTo("jiku")==0)System.err.println(s+" u are better than .....");
if(s.compareTo("shafin")==0)System.err.println(s+" very good.....");
if(s.compareTo("hira")==0)System.err.println(s+" Valo chay.....");
if(s.compareTo("saifur")==0)System.err.println(s+" don't care .....");
}
}
}

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 class Caller public class Add

{ {
public static void main(String args[]) private int x = 10, y =20;

{ public int show()

Add obj = new Add(); {

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.

Medicine store example to explain Encapsulation:

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.

You == External Application or piece of Code.

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

1. You have to create an object of the class


2. Then access the public method of the class through the object
3. Then access the private member of the class through the public method which has access to it.
Also, encapsulation ensures that you do not accidentally modify something else. i.e. if you call the method setMy1stMemberVariable() it modifies only my1stMemberVariable and
does not changes my2ndMemberVariable i.e. there are no side effects!
Now refer to the above program and read the comments. You should understand it properly.
31

Packages, Inheritance And Interfaces Toopic

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

3 Superclass Class whose properties are inherited by subclass is called assuperclass

4 Keywords Used extends and implements

Finding Packages and CLASSPATH


-classpath option with java
and javac to specify the path to your classes

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

public class TwoWheeler extends Vehicle{ WagonR IS-A FourWheeler


32

public class WagonR extends FourWheeler{


}

public class Caller public class Vehicle


{ {
public static void main( String[] args )
}
{
public class FourWheeler extends Vehicle
FourWheeler v1 = new FourWheeler();
TwoWheeler v2 = new TwoWheeler();
{ true
WagonR v3 = new WagonR(); }
true
public class TwoWheeler extends Vehicle
System.out.println(v1 instanceof Vehicle); {
true
System.out.println(v2 instanceof Vehicle);
} true
System.out.println(v3 instanceof Vehicle);
System.out.println(v3 instanceof FourWheeler); public class WagonR extends FourWheeler
{
}
}
}

Packages and Interfaces

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

public void show()


// obj[0].show();
{
// obj[1].show();
if(balance<0)
// obj[2].show();
System.out.print("--> ");
for (int i = 0;i<3 ; i++)
System.out.println(name + ": $" + balance);
{
}
obj[i].show();
}
}

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

Why use them


 No Multiple inheritance, cannot extends more than on class at a time, so that’s why we use multiple implements
 An object may need IS-A relationship with many types

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.

Static Keyword Topic


 

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.

The static can be:

1. variable (also known as class variable)


2. method (also known as class method)
34

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

Program of counter without static variable Program of counter by static variable

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

class Caller class Caller


{ {

int a =5; static int a =5;


Exception in thread "main" java.lang.RuntimeException: Uncompilable
public static void main(String args[]) source code - non-static variable a cannot be referenced from a static public static void main(String args[])
context 5
{ {
at Static.pack1.Caller.main(Caller.java:11)
System.out.println(a); System.out.println(a);

} }

} }

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;

public class Balance { public class Balance


package Static.pack1;
package Static.pack1; {
import Static.pack2.Balance;
import Static.pack2.Balance; // Set count to zero initially. static int count = 0;
class Caller
class Caller static int count = 0; int id;
{
{ run: public Balance()
public static void main(String args[])
public static void main(String args[]) public Balance() { {
Created object number: 1 { run:
{ count++;
Created object number: 2 Balance Balance1 = new Balance();
Balance Balance1 = new Balance(); // Every time the constructor runs, increment count. id= count; 2
Balance Balance2 = new Balance();
Balance Balance2 = new Balance(); count++; Created object number: 3 }
Balance Balance3 = new Balance();
Balance Balance3 = new Balance(); public int getID()
System.out.println(Balance2.getID());
} // Display count. {
}
} System.out.println("Created object number: " + count); return id;
}
} }

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

public class Application {

public class Stuff { 1. class A{


public static void main(String[] args) {
2. int a=40;//non static
3.
public static String name = "I'm a static variable";
4. public static void main(String args[]){ Output:Compile Time Error
System.out.println(Stuff.name); 5. System.out.println(a);
} 6. }
} 7. }

I'm a static variable 8.

why main method is static?


Ans) because object is not required to call static method if it were non-static method, jvm create object first then call
main() method that will lead the problem of extra memory allocation.

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{

static{System.out.println( "static block is invoked");}


 Is used to initialize the static data member.
Output:static block is invoked
public static void main(String args[]){ Hello main
 It is executed before main method at the time of classloading.
System.out.println("Hello main");
}
}

// Demonstrate static variables, methods, and


blocks.
class UseStatic {
static int a = 3;
static int b;
static void meth(int x) { Outside of the class in which they are defined, static methods and variables can be used
System.out.println("x = " + x);
independently of any object. To do so, you need only specify the name of their class followed by the
System.out.println("a = " + a); Static block initialized.
System.out.println("b = " + b); x = 42 dot operator. For example, if you wish to call a static method from outside its class, you can do so
} a = 3 using the following general form:
static { b = 12
System.out.println("Static block initialized.");
b = a * 4;
classname.method( )
}
public static void main(String args[]) {
meth(42);
}
}

Abstract Keyword Topic


 A class defined as abstract cannot be instantiated/create any object of that class
 A method defined as an abstract cannot have any BODY like {} it finished with a
semicolon
 Abstract methods are meant to be overridden in subclasses
 Abstract class need not have abstract methods  Abstract class exist to extended they cannot be instantiated 
 But if a single method defined as an abstract in a class then the container class must be 
defined as abstract
 Base class must be abstract if super class is an abstract class
 Methods marked as private cannot be abstract
 Methods marked as static cannot be abstract
 Methods marked as final cannot be abstract
38

 Abstract class can have constructors


 When no constructor defined a default constructor defines by compiler

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.

Final Entity Description


package com.c4learn.inheritance;
39

Final Value Final Value cannot be modified


public class ShapeClass {

final void setShape() {


Final Method Final Method cannot be overriden System.out.println("I am Inherited");;
}

public static void main(String[] args) {


Final Class Final Class cannot be inherited Circle c1 = new Circle();
c1.setShape();
}
}

class Circle extends ShapeClass {

Additional info

final static keyword


 

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

//static initialization block


static
{
MAX_SPEED = 200; //mph
}

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 -

 Accessing Instance Variable of Parent Class


 Accessing Parent Class Method
 Accessing Parent Class Class Constructor
41

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

Using this with a Field

The most common reason for using the this keyword is because a field is
shadowed by a method or constructor parameter.

For example, the Point class was written like this

public class Point


{
public int x = 0;
public int y = 0;

//constructor
public Point(int a, int b)
{
x = a;
y = b;
}
}
but it could have been written like this:

public class Point


{
public int x = 0;
public int y = 0;

//constructor
public Point(int x, int y)
{
43

this.x = x;
this.y = y;
}
}

Inheritance & interfaces

Parent Class/Base class/Super Class

class should be public


if we want to access
• Everything in base
• Like import
Parent Class/Base class/Super Class

Child Class/Derived Class/Inherited class

Child Class/Derived Class/Inherited class


44
45

The History and


Evolution of Java
Goals of java
Object-oriented programming is a programming methodology that helps organize World Wide Web demanded portable programs.
complex programs through the use of Perhaps the most important example of Java’s influence is C#. Created by Microsoft to 1. It should be object oriented
support the .NET Framework, C# is closely related to Java. For example, both share the 2. A single representation of a program could be executed on multiple
1. inheritance, same general syntax, support distributed programming, and utilize the same object model. operating systems
2. encapsulation, and There are, of course, differences between Java and C#, but the overall “look and feel” of 3. It should fully support network programming
4. It should execute code from remote sources securely
3. polymorphism. these languages is very similar.
5. It should be easy to use
These 3 must have been in object oriented programming language

Primary goals of java:


1. It should be "simple, object-oriented and familiar".
2. It should be "robust and secure".
3. It should be "architecture-neutral and portable".
4. It should execute with "high performance".
5. It should be "interpreted, threaded, and dynamic".

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

Delegates Absent Supported


Interpreter vs compiler

Java compilation process


47

Java is considered as Portable because – Important Note :

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

Servlets: Java on the Server Side


 A servlet is a small program that executes on the server servlets (like all Java programs) are compiled into bytecode and executed
by the JVM, they are highly portable

The Java Buzzwords


• Simple
• Secure
The Java Buzzwords • Portable
• Object-oriented
No discussion of Java’s history is complete without a look at the Java buzzwords. Although
• Robust
the fundamental forces that necessitated the invention of Java are portability and security, • Multithreaded
• Architecture-neutral
other factors also played an important role in molding the final form of the language. The
• Interpreted
key considerations were summed up by the Java team in the following list of buzzwords: • High performance
• Distributed
• Dynamic
48
49
50

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

The Three OOP Principles

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

public static void main(String args[])


{

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

Using Blocks of Code


Java allows two or more statements to be grouped into blocks of code, also called code
blocks.
Consider this if statement:
if(x < y) { // begin a block
x = y;
y = 0;
} // end of block

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

Used to contain lists of parameters in method definition and invocation.


() Parentheses Also used for defining precedence in expressions, containing expressions in
control statements, and surrounding cast types.

Used to contain the values of automatically initialized arrays. Also used to


{} Curly Braces
define a block of code, for classes, methods, and local scopes.

[] Brackets / square
braces
Used to declare array types. Also used when dereferencing array values.

Semicolon Terminates statements.


; Separates consecutive identifiers in a variable declaration. Also used to chain
, Comma
statements together ins000ide a for statement.
Used to separate package names from subpackages and classes. Also used to
. Period
separate a variable or method from a reference variable.
Used to create a method or constructor reference. (Added by JDK
:: Colons
8.)
52

The Java Keywords


abstract continue for new switch
assert default goto package synchronized
boolean do if private this
There are 50 keywords currently defined in the break double implements protected throw
Java language. These keywords, combined with
byte else import public throws
the syntax of the operators and separators, form
the foundation case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while
53
54

Chapter 1
(Variables & Data Types)

Data Types
55

Type Contains Default Size


boolean true or false false 1 bit
char Unicode Character u0000 16 bits
byte Signed Integer 0 8 bits
short Signed Integer 0 16 bits
int Signed Integer 0 32 bits
long Signed Integer 0 64 bits
float Floating Number 0.0 32 bit
double Floating Number 0.0 64 bit
Boolean
class ex1
class ex1 {
{ public static void main(String args[])
public static void main(String args[]) {
{ int a = 10, b = 15;
boolean a = true, b = false; System.out.println("(a > b) = "+ (a > b));
System.out.println("a = "+ a); boolean c = (a < b);
System.out.println("b = "+ b); System.out.println("c = (a < b) = "+ c);
} }
} }

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

Double & Float


class ex1
{
public static void main(String args[])
{
float a = 9E5f;
double b = 9E5;
System.out.println("a = "+ a);
System.out.println("b = "+ b);
}
}

Type conversion & cast operation


class ex1
{
public static void main(String args[])
{
int a = 14;
float b = 3.1413424f;
int c = a % (int)b ;
System.out.println("c = "+ c);
}
56

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

System.out.print("Enter your academic year : ");

String s = BR.readLine();

int year = Integer.parseInt(s);

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 {

public static void main(String[] args)


import java.io.BufferedReader; {
import java.io.InputStreamReader;
try
class ex1{
public static void main(String[] args){ {
try{
Scanner sc = new Scanner(System.in);
InputStreamReader IN = new InputStreamReader(System.in);
BufferedReader BR = new BufferedReader(IN);

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

int i, j; int i, j; int i, j; int i, j;


for (i = 1 ; i<=input; i++){ for (i = 1 ; i<=input; i++){ for (i = 1 ; i<=input; i++){ for (i = input ; i>=1; i--){
for (j = 1; j<=i; j++){ for (j = 1; j<=input; j++){ for (j = input; j>=i; j--){ for (j = 1; j<=i; j++){
System.out.print(j); System.out.print(j); System.out.print(j + " "); System.out.print(j + " ");
} } } }
System.out.print("\n"); System.out.print("\n"); System.out.print("\n"); System.out.print("\n");
} } } }

Continue & break


for( ; ; ){
System.out.print("Enter a positive integer : ");
String s = BR.readLine();

int input = Integer.parseInt(s);

if (input<1){
continue;
}
else
System.out.println("Your entered a positive
number ");
break;
}

Chapter 4
(Array Topic)

Value assigning after the array declared


class ex1{
public static void main(String[] args){

int array[] = new int[5];


array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;
int total = array[0] + array[1] + array[2] + array[3] + array[4];

System.out.println(total);
}
60

Value assigning when the array declared


int array[] = {1,2,3,4,5};
int total = 0; int marks[] = {40, 55, 69, 89, 78};

for (int i = 0; i<=4; i++){ for (int i = 0; i<5; i++){


System.out.print("marks[" + i + "] = " + marks[i]);
total = total + array[i]; System.out.print("\n");
} }

System.out.println(total);

Value assigning while program processing


import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.InputStreamReader;
class ex1{ class ex1{
public static void main(String [] args){
class ex1{ public static void main(String [] args){ int Roll[] = new int[5];
public static void main(String[] args){ int Roll[] = new int[5]; float Marks[] = new float[5];
float Marks[] = new float[5];
try{ try{
InputStreamReader IN= new InputStreamReader(System.in); try{ for (int i=0; i<5; i++){
BufferedReader BR = new BufferedReader(IN); for (int i=0; i<5; i++){ InputStreamReader IN = new InputStreamReader(System.in);
InputStreamReader IN = new InputStreamReader(System.in); BufferedReader BR = new BufferedReader(IN);
int array[] = new int[5]; BufferedReader BR = new BufferedReader(IN);
int total = 0; System.out.print("Enter Roll ["+ i +"] = " );
System.out.println("Enter 5 of your Numbers to Sum : "); System.out.print("Enter Roll ["+ i +"] = " ); String s1 = BR.readLine();
for(int i =0; i<=4; i++){ String s1 = BR.readLine(); Roll[i] = Integer.parseInt(s1);
String s = BR.readLine(); Roll[i] = Integer.parseInt(s1);
System.out.print("Enter Marks ["+ i +"] = ");
int input = Integer.parseInt(s); String s2 = BR.readLine();
array[i] = input; System.out.print("Enter Marks ["+ i +"] = "); Marks[i] = Float.parseFloat(s2);
} String s2 = BR.readLine(); }
Marks[i] = Float.parseFloat(s2);
for (int i = 0; i<=4; i++){ } for (int i=0; i<5; i++){
System.out.println("Roll ["+ i +"] = " + Roll[i]);
total = total + array[i]; for (int i=0; i<5; i++){
} System.out.println("Roll ["+ i +"] = " + Roll[i]); System.out.println("Marks["+ i +"] = " + Marks[i]);
}
System.out.println("Total = "+total); System.out.println("Marks["+ i +"] = " + Marks[i]); }
catch (Exception E){
} }
System.out.println("Error in inpuit. Program terminated .....");
catch (Exception E){} } System.exit(0);
} catch (Exception E){} }
} } }
} }

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("Enter Roll ["+ i +"] = " );


String s1 = BR.readLine();
Roll[i] = Integer.parseInt(s1);

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

class ex1{ class ex1{


public static void main(String [] args){ public static void main(String [] args){
String first_name = new String("Md. Saifur"); String first_name = new String("Md. Saifur ");
StringBuffer last_name = new StringBuffer(" Rahman"); String full_name = first_name + "Rahman";
System.out.println(first_name + last_name); System.out.println(full_name);
} }
} }
62

import java.io.IOException; import java.io.DataInputStream;


import java.io.IOException;

class ex1{ class ex1{


public static void main(String[] args)throws IOException { public static void main(String[] args)throws IOException {
char ch; System.out.print("Enter Your name : ");
System.out.println("Enter some characters : ");
DataInputStream IN = new DataInputStream(System.in);
do {
ch = (char)System.in.read(); String name = IN.readLine();
System.out.print(ch); System.out.print("Your name is : ");
}while(ch != 'q'); System.out.print(name);
System.out.println("Program terminated"); }
}
}
}
import java.io.BufferedReader;
import java.io.DataInputStream; import java.io.IOException;
import java.io.IOException; import java.io.InputStreamReader;

class ex1{ class ex1{


public static void main(String[] args)throws IOException {
public static void main(String[] args)throws IOException { System.out.print("Enter Your name : ");
System.out.print("Please enter your name : ");
DataInputStream IN = new DataInputStream(System.in); InputStreamReader IN = new
InputStreamReader(System.in);
String name = IN.readLine(); BufferedReader BR = new BufferedReader(IN);
System.out.print("Your name is : ");
String name = BR.readLine();
System.out.println(name); System.out.print("Your name is : ");
System.out.print(name);
} }
} }

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

char ca1 = s1.charAt(6);


System.out.println("s1.charAt(6) = " + ca1);

StringBuffer s2 = new StringBuffer("java is a object oriented programming");


for(int i= 0; i<s2.length(); i++) {
if (i%2 == 0) {
s2.setCharAt(i, '_');
}
63

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

Number to string long i4 = 34; String to number String s4 = "34";


String s1 = Integer.toString(i1);
String s2 = Float.toString(i2); int i = Integer.valueOf(s1);
String s1 = Integer.toString(i1); String s3 = Double.toString(i3); int i = Integer.valueOf(s1); float f = Float.valueOf(s2);
String s4 = Long.toString(i4); double d = Double.valueOf(s3);
String s2 = Float.toString(i2); float f = Float.valueOf(s2); long l = Long.valueOf(s4);
String s3 = Double.toString(i3); System.out.println(s1); double d = Double.valueOf(s3);
String s4 = Long.toString(i4); System.out.println(s2); long l = Long.valueOf(s4); System.out.println(i);
System.out.println(s3); System.out.println(f);
System.out.println(s4); System.out.println(d);
System.out.println(l);
}
}
} }

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;

public class Mainthread


{
public static void main(String args[])
{
int count =0;
String a;
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
StringTokenizer st = new StringTokenizer(s);
StringTokenizer
while(st.hasMoreTokens())
{
st.nextToken();
count++;
}
System.out.println(count);
}
}
run:
asd asdasd asd asdas
4

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

14 String replace(CharSequence old, CharSequence new) replaces all occurrences of specified


CharSequence
15 String trim() returns trimmed string omitting leading and
trailing spaces
16 String split(String regex) returns splitted string matching regex
17 String split(String regex, int limit) returns splitted string matching regex and limit

18 String intern() returns interned string


19 int indexOf(int ch) returns specified char value index
20 int indexOf(int ch, int fromIndex) returns specified char value index starting with
given index
21 int indexOf(String substring) returns specified substring index
22 int indexOf(String substring, int fromIndex) returns specified substring index starting with
given index
public class Test
{
public static void main( String[] args )
{
String a, b;

length() a = "hello "; 11


b = "world";
int len = a.length()+b.length();
System.out.println(len);
}
}
public class Test
{
public class Test
public static void main( String[] args )
{
{
public static void main( String[] args )
String a;
{
a = "hello world";
String a, b;
reverse() dlrow olleh int len = a.length();
a = "hello world";
for (int i =len-1; i>=0; i--)
String rev = new StringBuffer(a).reverse().toString();
{
System.out.println(rev);
System.out.print(a.charAt(i));
}
}
}
}
}
public class Mainthread
{
public static void main(String args[]) throws Exception
charAt() {
run:
length() String ch = "saifur";
f
System.out.println(ch.charAt(3));
System.out.println(ch.length());

}
66

}
public class Mainthread

public static void main(String args[])


{

String name="sonoo";

String sf1=String.format("name is %s",name);

String sf2=String.format("value is %f",32.33434);


format() String sf3=String.format("value is %32.12f",32.33434);//returns
12 char fractional part filling with 0

System.out.println(sf1);

System.out.println(sf2);
System.out.println(sf3);

public class Mainthread


public class Mainthread
{
{
public static void main(String args[])
public static void main(String args[])
{
{
String name = "saifur rahman";
format() String name = "saifur rahman";
int age = 21;
String s = String.format("My name is %s & %d years old..", name, 21);
String s = String.format("My name is %s & %d years old..", name, age);
System.out.print(s);
System.out.print(s);
}
}
}
}
public class Mainthread
{
public static void main(String args[])
{
String name = "saifur";
contains(name)
String s = "saifur rahman is checking";
System.out.println(s.contains(name));
System.out.println(s.contains("rahma"));
}
}
public class Mainthread
{
public static void main(String args[])
{
String s1 = "saifur";
String s2 = "rahman";

equals() String s3 = "saifur";

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()+" saifur rahman"); System.out.println(s1);

} 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

We can compare two given strings on the basis of content and


reference.

It is used in authentication (by equals()


method), sorting (by compareTo() method), reference
matching (by == operator) etc.

There are three ways to compare String objects:

1. By equals() method
2. By = = operator
3. By compareTo() method

public class Mainthread

public static void main(String args[]) throws Exception

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

StringTokenizer class Topic

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.

boolean hasMoreElements() same as hasMoreTokens() method.

Object nextElement() same as nextToken() but its return type is Object.

int countTokens() returns the total number of tokens.

import java.util.*; import java.util.*;


public class Mainthread public class Mainthread

{ {
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";

StringTokenizer st = new StringTokenizer(s); StringTokenizer st = new StringTokenizer(s);

while(st.hasMoreTokens()) while(st.hasMoreTokens())
70

{ {

System.out.println(st.nextToken()); System.out.println(st.nextToken(","));
} }

} }

} }

Practice
import java.util.Scanner;

public class Test


import java.util.Scanner;
{
public class Test
public static void main( String[] args )
{
{
public static void main( String[] args )
Scanner sc = new Scanner(System.in);
{
String a = sc.nextLine();
Scanner sc = new Scanner(System.in);
String b = a.toLowerCase();
String a = sc.nextLine();
int len = b.length(), count=0;
String b = a.toLowerCase();
char c;
Vowel numbers int len = b.length(), count=0; Consonants numbers for (int i =0; i<len; i++)
for (int i =0; i<len; i++)
{
{
c = b.charAt(i);
if(b.charAt(i) == 'a'|| b.charAt(i) == 'e'||b.charAt(i) == 'i'||b.charAt(i) == 'o'||b.charAt(i) == 'u')
if(c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u' && c != ' ')
count++;
// if(b.charAt(i) != 'a' && b.charAt(i) != 'e' && b.charAt(i) != 'i' && b.charAt(i) != 'o' && b.charAt(i) != 'u' && b.charAt( i) != ' ')
}
count++;
System.out.println(count);
}
}
System.out.println("Consonants : " +count);
}
}

Things We should know


String myString = ""; String myString; What value is assigned to a reference value to show that there is no
What value is contained in myString? 1. What sort of thing is "Nothing New" as in the following: String str = "Nothing New"; What is the data type of myString? object?

b. A String literal

b. a String reference b. reference to String c. null

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.

Life cycle of a Thread (Thread States)

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 calling new NewThread(); {

class NewThread implements Runnable


new Thread(th1).start();
Thread method calling {

Difference between thread & process

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

Examples(Using Thread Class)


public class Test extends Thread

public void run()

System.out.println("Thread called");

public static void main( String[] args )

Test th = new Test();

th.start();

run:

Thread called

class Minitest extends Thread

String s=null; class MyThread extends Thread


public class Test
{
public class Test {
Minitest(String s1) public void run()
{ public static void main(String[] args) run:
{ {
public static void main(String args[]) { Test started :
s=s1; run: for (int i=0; i<=5; i+=2)
{ System.out.println("Test started : "); Inside MyThread Thread..
start(); Thread started.... {
Minitest m1=new Minitest("Thread started...."); MyThread obj = new MyThread(); Inside MyThread Thread..
} System.out.println("Inside MyThread Thread..");
} obj.start(); Inside MyThread Thread..
public void run() }
} }
{ }
}
System.out.println(s); }

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

Inside B Thread.. : i = 2 Inside B Thread.. : i = 4

Inside B Thread.. : i = 4 Inside A Thread.. : i = 4

public class Test // main Thread

{ public class A extends Thread // Thread B public class B extends Thread // Thread B

public static void main(String[] args) { {

{ public void run() public void run()

System.out.println("Thread Started .."); { {

for (int i=0; i<=5; i+=2) for (int i=0; i<=5; i+=2)

A th1 = new A(); // creating obj of Thread A { {

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

th1.start(); // Calls run() method of Thread A } }

th2.start(); // Calls run() method of Thread B } }

System.out.println("Exit from main Thread.."); } }

}
73

public class Test // main Thread run: run: run: run:

{ Thread Started .. Thread Started .. Thread Started .. Thread Started ..

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

{ { { { Inside A Thread.. : i = 2 Inside B Thread.. : j = 0 Inside A Thread.. : i = 2 Inside A Thread.. : i = 2

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

public class A extends Thread // Thread B

public class Test // main Thread {

{ void display()

public static void main(String[] args) {

{ for (int i=0; i<=5; i+=2) run:

System.out.println("Thread Started .."); { Thread Started ..

System.out.println("Inside A Thread.. : i = "+ i); Exit from main Thread..

A th1 = new A(); // creating obj of Thread A } Inside A Thread.. : i = 0

} Inside A Thread.. : i = 2

th1.start(); // Calls run() method of Thread A public void run() Inside A Thread.. : i = 4

{ Exit From Thread A ...

System.out.println("Exit from main Thread.."); display();

} System.out.println("Exit From Thread A ...");

} }

Examples(Using Runnable interface)


public class A implements Runnable run:

{ Thread Started .. public class Mainthread


// main Thread == main method container
void display() Exit from main Thread.. { public class A implements Runnable
public class Mainthread
{ Inside A Thread.. : i = 0 public static void main(String[] args) {
{ run:
for (int i=0; i<=5; i+=2) Inside A Thread.. : i = 2 { public void run()
public static void main(String[] args) Starting main thread..
{ Inside A Thread.. : i = 4 System.out.println("Starting main thread.."); {
{ Exiting main thread..
System.out.println("Inside A Thread.. : i = "+ i); Exit From Thread A ... A th1 = new A(); for (int i=0; i<=3; i++)
System.out.println("Thread Started .."); Inside A Thread.. : i = 0
} //Thread t = new Thread(th1); {
A objA = new A(); Inside A Thread.. : i = 1
} // t.start(); System.out.println("Inside A Thread.. : i = "+ i);
Thread th1 = new Thread(objA); Inside A Thread.. : i = 2
public void run() }
th1.start(); Inside A Thread.. : i = 3
{ new Thread(th1).start(); System.out.println("Exit From Thread A ...");
System.out.println("Exit from main Thread.."); Exit From Thread A ...
display(); System.out.println("Exiting main thread.."); }
}
System.out.println("Exit From Thread A ..."); } }
}
} }

The complete reference examples


class ThreadDemo class NewThread implements Runnable run: class ExtendThread // Create a second thread by extending Thread run:
{ { Child thread: Thread[Demo { class NewThread2 extends Thread Child thread: Thread[Demo
public static void main(String args[ ] ) Thread t; Thread,5,main] public static void main(String args[]) { Thread,5,main]

{ NewThread() Main Thread: 5 { NewThread2() Main Thread: 5

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

System.out.println("Main Thread: " + i); } Main Thread: 3 { } Main Thread: 3

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.

} { Main Thread: 2 } { Main Thread: 2

catch (InterruptedException e) try Main Thread: 1 } try Main Thread: 1

{ { Main thread exiting. catch (InterruptedException e) { Main thread exiting.


74

System.out.println("Main thread interrupted."); for(int i = 5; i > 0; i--) { for(int i = 5; i > 0; i--)

} { System.out.println("Main thread interrupted."); {

System.out.println("Main thread exiting."); System.out.println("Child Thread: " + i); } System.out.println("Child Thread: " + i);

} Thread.sleep(500); System.out.println("Main thread exiting."); Thread.sleep(500);

} } } }

} } }

catch (InterruptedException e) catch (InterruptedException e)

{ {

System.out.println("Child interrupted."); System.out.println("Child interrupted.");

} }

System.out.println("Exiting child thread."); System.out.println("Exiting child thread.");

} }

} }

class NewThread2 extends Thread

class ExtendThread NewThread2() class ExtendThread


class NewThread2 extends Thread
{ { {
{
public static void main(String args[]) System.out.println("Child thread: " + this); public static void main(String args[])
run: NewThread2()
{ start(); {
Child thread: Thread[Demo {
NewThread th = new NewThread(); } new NewThread2(); run:
Thread,5,main] for (int i=0;i<5 ; i++)
try public void run() for (int i=0;i<5 ; i++) Child : 0
Main Thread: 5 {
{ { { Child : 1
Child Thread: 5 try
for(int i = 5; i > 0; i--) try try Child : 2
Child Thread: 4 {
{ { { Child : 3
Child Thread: 3 System.out.println("Child : "+i);
System.out.println("Main Thread: " + i); for(int i = 5; i > 0; i--) System.out.println("Main : "+i); Child : 4
Main Thread: 4 Thread.sleep(1000);
Thread.sleep(1000); { Thread.sleep(1000); Main : 0
Child Thread: 2 }
} System.out.println("Child Thread: " + i); } Main : 1
Main Thread: 3 catch(Exception err)
} Thread.sleep(500); catch(Exception err) Main : 2
Child Thread: 1 {
catch (InterruptedException e) } { Main : 3
Exiting child thread.
{ } Main : 4
Main Thread: 2 }
catch (InterruptedException e) }
Main Thread: 1 }
} { }
}
} }
}
} } }

class NewThread2 extends Thread

{
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:

{ { Inside Main Thread.. : i = 0 { { Inside Main Thread.. : i = 0

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

{ { Inside A Thread.. : j = 1 { { Inside Main Thread.. : i = 1


A th1 = new A(); try Inside Main Thread.. : i = 1 A th1 = new A(); try Inside A Thread.. : j = 1
75

th1.start(); { Inside Main Thread.. : i = 2 new Thread(th1).start(); { Inside A Thread.. : j = 2

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)

} { } {
catch(Exception err) catch(Exception err)

{ } { }

} }

} } } }
} }

} }

Left Ashiq sir’s & Right mine


public class mythread implements Runnable

{ public class A implements Runnable

Thread t; {

mythread(String x, int p) Thread t;


{ A(String name, int p)

t = new Thread(this, x); {


public class Lec10
// Thread(Runnable target, String name) t = new Thread(this, name); //this = A
{
// Allocates a new Thread object. t.setPriority(p);
public static void main(String[] args)
t.setPriority(p); }
{
t.start(); public void run()
mythread abc = new mythread("One", 5); public class Mainthread
} run: {
mythread xyz = new mythread("Two", 9); {
Thread[One,5,main] : 0 try
public static void main(String[] args)
public void run() Thread[Two,9,main] : 0 {
try {
{ Thread[One,5,main] : 1 for (int i=0; i<=3; i++)
{ A x = new A("One", 5);
int i; Thread[Two,9,main] : 1 {
abc.t.join(); A y = new A("Two", 9);
for(i = 0; i < 10; i++) Thread[One,5,main] : 2 System.out.println(t +" : "+ i);
xyz.t.join(); new Thread(x).start();
{ Thread[Two,9,main] : 2 Thread.sleep(1000);
} new Thread(y).start();
System.out.println(t+":"+i); Thread[One,5,main] : 3 }
catch(Exception err) }
try Thread[Two,9,main] : 3 }
{ }
{ catch(Exception err)
System.out.println(err);
//t.sleep(1000); {
}
}
}
catch(Exception err) }
}
{ }

System.out.println(err); }

public class A extends Thread run: public class A extends Thread


public class Mainthread
{ Thread[One,3,main] : 0 {
{ public class Mainthread
Thread t; Thread[Three,5,main] : 0 Thread t;
public static void main(String[] args) {
A(String name, int p) Thread[Two,4,main] : 0 A(String name, int p)
{ public static void main(String[] args)
{ Thread[Two,4,main] : 1 {
A x = new A("One", 3); {
t = new Thread(this, name); Thread[Three,5,main] : 1 t = new Thread(this, name); //this = A
A y = new A("Two", 4); A x = new A("One", 5);
t.setPriority(p); Thread[One,3,main] : 1 t.setPriority(p);
A z = new A("Three", 5); A y = new A("Two", 9);
} Thread[Three,5,main] : 2 }
x.start(); x.start();
Thread[One,3,main] : 2 public void run()
y.start(); y.start();
public void run() Thread[Two,4,main] : 2 {
z.start(); }
{ Thread[One,3,main] : 3 try
} }
try Thread[Three,5,main] : 3 {
}
{ Thread[Two,4,main] : 3 for (int i=0; i<=3; i++)
76

for (int i=0; i<=3; i++) {

{ System.out.println(t +" : "+ i);


run:
System.out.println(t +" : "+ i); sleep(1000);
Thread[One,5,main] : 0
sleep(1000); }
Thread[Two,9,main] : 0
} }
Thread[One,5,main] : 1
} catch(Exception err)
Thread[Two,9,main] : 1
catch(Exception err) {
Thread[One,5,main] : 2
{
Thread[Two,9,main] : 2
}
Thread[One,5,main] : 3
} }
Thread[Two,9,main] : 3
} }

public class A extends Thread

{
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 setPriority(p); Thread[One,3,main] : 0 public class Mainthread


t = new Thread(this, name);
{ //do not use this Thread[Three,5,main] : 0 {
t.setPriority(p);
public static void main(String[] args) //t = new Thread(this, name); Thread[Two,4,main] : 4 public static void main(String[] args)
}
{ //t.setPriority(p); Thread[Three,5,main] : 6 {

A x = new A("One", 3); } Thread[Two,4,main] : 6 A x = new A("One", 3);


public void run()
A y = new A("Two", 4); Thread[One,3,main] : 9 A y = new A("Two", 4);
{
A z = new A("Three", 5); public void run() Thread[Three,5,main] : 12 A z = new A("Three", 5);
try
try { Thread[One,3,main] : 15 try
{
{ try Thread[Two,4,main] : 15 {
for (; i<=100; )
x.start(); { Thread[Three,5,main] : 18 new Thread(x).start();
{
y.start(); for (; i<=100; ) Thread[Two,4,main] : 21 new Thread(y).start();
System.out.println(t +" : "+ i);
z.start(); { Thread[One,3,main] : 21 new Thread(z).start();

} System.out.println(this +" : "+ i); Thread[Three,5,main] : 24 }


if (t.getName().compareTo("One") == 0)i++;
catch(Exception err) Thread[Two,4,main] : 27 catch(Exception err)
if (t.getName().compareTo("Two") == 0)i+=2;
{ if (this.getName().compareTo("One") == 0)i++; Thread[One,3,main] : 27 {
if (t.getName().compareTo("Three") == 0)i+=3;
System.out.println(err); if (this.getName().compareTo("Two") == 0)i+=2; Thread[Three,5,main] : 30 System.out.println(err);

} if (this.getName().compareTo("Three") == 0)i+=3; Thread[Two,4,main] : 33 }


Thread.sleep(1000);
} Thread[One,3,main] : 33 }
}
} sleep(1000); Thread[Three,5,main] : 3 }
}
}
catch(Exception err)
}
{
catch(Exception err)
System.out.println(err);
{
}
System.out.println(err);
}
}
}
}

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(String threadName, int p) { A(String threadName, int p)


A t1=new A("t1", 3); { A t1=new A("t1", 3); {

A t2=new A("t2", 5); t = new Thread(this, threadName); A t2=new A("t2", 5); t = new Thread(this, threadName);

A t3=new A("t3", 7); t.setPriority(p); A t3=new A("t3", 7); t.setPriority(p);

try } try t.start();

{ public void run() { }

new Thread(t1).start(); { t1.t.join(); public void run()

new Thread(t2).start(); try t2.t.join(); {

new Thread(t3).start(); { t3.t.join(); try

} for (int i=0; i<5; i++) } {

catch(Exception e) { catch(Exception e) for (int i=0; i<5; i++)

{ System.out.println(t+" : "+ i); { {

System.out.println(e); t.sleep(500); System.out.println(e); System.out.println(t+" : "+ i);

} } } t.sleep(500);
77

} } } }

} catch(Exception e) } }

{ catch(Exception e)

System.out.println(e); {

} System.out.println(e);

} }

} }

class A implements Runnable


class A extends Thread
public class Mainthread {
{
{ Thread t;
A(String threadName, int p) public class Mainthread
public class Mainthread public static void main(String args[]) A(String threadName, int p)
{ {
{ { {
super(threadName); public static void main(String args[])
public static void main(String args[]) Thread[t3,7,main] : 0 A t1=new A("t1", 3); t= new Thread(this, threadName);
setPriority(p); {
{ Thread[t1,3,main] : 0 A t2=new A("t2", 5); t.setPriority(p);
start(); A t1=new A("t1", 3);
A t1=new A("t1", 3); Thread[t2,5,main] : 0 A t3=new A("t3", 7); t.start();
} A t2=new A("t2", 5);
A t2=new A("t2", 5); Thread[t3,7,main] : 1 Thread t = new Thread(t2); }
public void run() A t3=new A("t3", 7);
A t3=new A("t3", 7); Thread[t2,5,main] : 1 try public void run()
{ try
try Thread[t1,3,main] : 1 { {
try {
{ Thread[t3,7,main] : 2 try
{ t1.t.join();
t1.join(); Thread[t2,5,main] : 2 t1.t.join(); {
for (int i=0; i<5; i++) // new Thread(t1).join();
t2.join(); Thread[t1,3,main] : 2 // new Thread(t1).join(); for (int i=0; i<5; i++)
{ t2.t.join();
t3.join(); Thread[t3,7,main] : 3 // t2.t.join(); {
System.out.println(this+" : "+ i); t3.t.join();
} Thread[t2,5,main] : 3 t.join(); System.out.println(t+" : "+ i);
sleep(500); }
catch(Exception e) Thread[t1,3,main] : 3 t3.t.join(); t.sleep(500);
} catch(Exception e)
{ Thread[t3,7,main] : 4 } }
} {
System.out.println(e); Thread[t2,5,main] : 4 catch(Exception e) }
catch(Exception e) System.out.println(e);
} Thread[t1,3,main] : 4 { catch(Exception e)
{ }
} System.out.println(e); {
System.out.println(e); }
} } System.out.println(e);
} }
} }
}
} }
}
}

public class A implements Runnable

int count;

void isPrimeNumber(int number)


public class Mainthread
{
{
for(int i=2; i<=number/2; i++)
public static void main(String a[])
{
{
if(number % i == 0)
A x= new A("One", 3);
{
A y= new A("Two", 5);
System.out.print("Not Prime Number"+"\n");
A z= new A("Three", 7);
}

}
try
System.out.print("Prime Number"+"\n");
{

new Thread(x).start();

new Thread(y).start();
}

public void isOddEvens(int number)


Need to edit
{
new Thread(z).start();
if(number%2==0)
}
System.out.print("Even"+"\n");
catch(Exception err)
else
{
System.out.print("Odd"+"\n");
System.err.println(err);
}
}
public void fact(int number)
}
{
}
count = 1;

for(int i=1; i<=number; i++)count*=i;

System.out.print(count+"\n");

}
78

Thread t;

static int i=0;

A(String name, int p)

t = new Thread(this, name);

t.setPriority(p);

public void run()

try

for (; i<=100; )

if (t.getName().compareTo("One") == 0)

System.out.print(t +" : "+ i +" : " );

isOddEvens(i);

i++;

if (t.getName().compareTo("Two") == 0);

System.out.print(t +" : "+ i +" : ");

isPrimeNumber(i);
i+=2;

if (t.getName().compareTo("Three") == 0);

System.out.print(t +" : "+ i +" : ");

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

Thread class’s Methods


Commonly used methods of Thread class:

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


2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause and allow other threads
to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.

public class Mainthread


{ public class Mainthread
public static void main(String[] args) {
{ public static void main(String[] args)
System.out.println("Starting main thread.."); {
Thread th = Thread.currentThread(); // System.out.println(Thread.currentThread());
Returns a reference to the currently executing thread object.
System.out.println("currentThread is : "+ th); Thread t = Thread.currentThread();
currentThread() public static Thread currentThread() System.out.println("Exiting main thread.."); System.out.println(t);
} }
} }
run:
Starting main thread..
run:
currentThread is : Thread[main,5,main]
Thread[main,5,main]
Exiting main thread..
public class Mainthread
{
public class Mainthread
public static void main(String[] args)
{
{
public static void main(String[] args)
Thread t= Thread.currentThread();
{
t.setName("ThreadName");
setName() Thread.currentThread().setName("MyThread");
System.out.println(t);
System.out.println(Thread.currentThread());
}
}
}
}
run:
Thread[ThreadName,5,main]
82

public class Mainthread


{
public static void main(String[] args)
{
System.out.println("Starting main thread..");
getName()
Thread th = Thread.currentThread();
th.getName();
System.out.println("currentThread is : "+ th);
th.setName("MyThread");
System.out.println("Now Thread name is : "+ th);
System.out.println("Exiting main thread..");
}
}
run:
setName()
Starting main thread..
currentThread is : Thread[main,5,main]
Now Thread name is : Thread[MyThread,5,main]
Exiting main thread..
public class Mainthread
public class A extends Thread public class B extends Thread
{
{ {
public static void main(String[] args)
public void run() public void run()
{
{ {
System.out.println("Starting main thread..");
for (int i=0; i<=5; i+=2) for (int i=0; i<=5; i+=2)
A th1 = new A();
{ {
B th2 = new B();
System.out.println("Inside A Thread.. : i = "+ i); System.out.println("Inside B Thread.. : j = " + i);
th1.start();
yield(); yield();
th2.start();
} }
System.out.println("Exit From Thread A ..."); System.out.println("Exit From Thread B ...");
System.out.println("Exiting main thread..");
} }
}
yield() } }
}
run: run: run:
Starting main thread.. Starting main thread.. Starting main thread..
Exiting main thread.. Exiting main thread.. Exiting main thread..
Inside A Thread.. : i = 0 Inside B Thread.. : j = 0 Inside B Thread.. : j = 0
Inside B Thread.. : j = 0 Inside B Thread.. : j = 2 Inside A Thread.. : i = 0
Inside A Thread.. : i = 2 Inside A Thread.. : i = 0 Inside B Thread.. : j = 2
Inside B Thread.. : j = 2 Inside B Thread.. : j = 4 Inside A Thread.. : i = 2
Inside B Thread.. : j = 4 Inside A Thread.. : i = 2 Inside B Thread.. : j = 4
Inside A Thread.. : i = 4 Inside A Thread.. : i = 4 Inside A Thread.. : i = 4
Exit From Thread B ... Exit From Thread A ... Exit From Thread B ...
Exit From Thread A ... Exit From Thread B ... Exit From Thread A ...
public class Mainthread public class B extends Thread
public class A extends Thread
{ {
{
public static void main(String[] args) public void run()
public void run()
{ {
{
System.out.println("Starting main thread.."); for (int i=0; i<=5; i+=2)
for (int i=0; i<=5; i+=2)
A th1 = new A(); {
{
B th2 = new B(); System.out.println("Inside B Thread.. : j = " + i);
System.out.println("Inside A Thread.. : i = "+ i);
th1.start(); if(i==2)
yield();
th2.start(); stop();
}
}
System.out.println("Exit From Thread A ...");
System.out.println("Exiting main thread.."); System.out.println("Exit From Thread B ...");
stop() }
} }
}
} }
run:
Starting main thread..
Exiting main thread..
Inside A Thread.. : i = 0
Inside B Thread.. : j = 0
Inside B Thread.. : j = 2
Inside A Thread.. : i = 2
Inside A Thread.. : i = 4
Exit From Thread A ...
public class A extends Thread
{
public class Mainthread
public void run()
{
{
public static void main(String[] args) run:
for (int i=0; i<=5; i+=2)
{ Starting main thread..
{
System.out.println("Starting main thread.."); Exiting main thread..
System.out.println("Inside A Thread.. : i = "+ i);
sleep() A th1 = new A(); Inside A Thread.. : i = 0
try
th1.start(); Inside A Thread.. : i = 2
{
Inside A Thread.. : i = 4
sleep(2000);
System.out.println("Exiting main thread.."); Exit From Thread A ...
}
}
catch(Exception E)
}
{
83

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

System.out.println("Exiting main thread..");


}
}
run: run:
Starting main thread.. Starting main thread..
Inside A Thread.. : i = 0 Exiting main thread..
Inside B Thread.. : j = 0 Inside B Thread.. : j = 0
Inside B Thread.. : j = 1 Inside B Thread.. : j = 1
Inside B Thread.. : j = 2 Inside B Thread.. : j = 2
Inside B Thread.. : j = 3 Inside B Thread.. : j = 3
Exit From Thread B ... Exit From Thread B ...
Exiting main thread.. Inside C Thread.. : k = 0
Inside C Thread.. : k = 0 Inside C Thread.. : k = 1
Inside C Thread.. : k = 1 Inside C Thread.. : k = 2
Inside C Thread.. : k = 2 Inside C Thread.. : k = 3
Inside C Thread.. : k = 3 Exit From Thread C ...
Exit From Thread C ... Inside A Thread.. : i = 0
Inside A Thread.. : i = 1 Inside A Thread.. : i = 1
Inside A Thread.. : i = 2 Inside A Thread.. : i = 2
Inside A Thread.. : i = 3 Inside A Thread.. : i = 3
Exit From Thread A ... Exit From Thread A ...
public class Mainthread
{
public static void main(String[] args)
public class A implements Runnable
{
{
Thread t = new Thread();
public void run()
A th1 = new A();
{
new Thread(th1).start();
try run:
try
{ Inside A Thread.. : j = 0
{
for (int i=0; i<=3; i++) Inside Main Thread.. : i = 0
for (int i=0; i<=3; i++)
{ Inside A Thread.. : j = 1
{
System.out.println("Inside A Thread.. : j = "+ i); Inside A Thread.. : j = 2
interrupt() System.out.println("Inside Main Thread.. : i = "+ i);
Thread.sleep(500); Inside A Thread.. : j = 3
Thread.sleep(1000*2);
} Inside Main Thread.. : i = 1
}
} Inside Main Thread.. : i = 2
}
catch(Exception err) Inside Main Thread.. : i = 3
catch(Exception err)
{ Interrupt called..
{
}
}
}
t.interrupt();
}
System.out.println("Interrupt called..");
}
}
Practice

Commonly used Constructors of Thread class


 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)

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

File I/O Topic


http://tutorials.jenkov.com/java-io/fileinputstream.html

 
85

Extra knowledge
Stream class :
 File stream
 i/o stream
Java defines two types of streams:

 byte and (old & appropriate way) ASCII TABLE


 character (new & easy way). The Byte Stream Classes
http://www.techonthenet.com/ascii/chart.php
Byte streams are used, for example, when reading or writing binary data.

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.

Commonly used methods of OutputStream class

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.

3) public void flush()throws IOException: flushes the current output stream.

4) public void close()throws IOException: is used to close the current output stream.

File Stream Examples


FileInputStream
http://tutorials.jenkov.com/java-io/fileinputstream.html

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

String path = "/home/jakobjenkov/data/thefile.txt";

import java.io.*;

public class Mainthread

public static void main(String args[]) throws Exception

FileInputStream fis = new FileInputStream("FileInputStream.txt");

int i;

while((i=fis.read())!=-1)

System.out.print((char)i);

}
fis.close();

import java.io.*;

import java.util.*;

public class Mainthread

public static void main(String[] args) throws Exception

// FileWriter fw = new
FileWriter("C:\\Users\\user\\Desktop\\Saifur\\s.ini");

FileWriter fw = new FileWriter("s.ini"); // new file creating & opening

fw.close(); //file closing

}
}

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

public class Mainthread


{
public static void main(String args[]) throws Exception
{
FileInputStream fin = new FileInputStream("text.txt");
byte[] b = new byte[fin.available()];
String a ="";
int count =0;
int i= b.length;
fin.read(b, 0, i);

for(int j = 0; j < i; j++)


{
System.out.print((char)b[j]);
a += ""+(char)b[j];
}
fin.close();
}
}

Chapter 6
(Vector Topic)

Empty Vector
package saifur.vector;
import java.util.*;

public class EmptyVector


{
public static void main(String[] args)
{
Vector v1 = new Vector();
System.err.println(v1.size());
System.err.println(v1.capacity());
System.err.println(v1.contains(v1));
}
}

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

for(int i = 0; i<3; i++) {


System.out.println("name.elementAt (" + i +") is : " + name.elementAt(i));
}
}
}

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

for(int i = 0; i<3; i++) {


set() System.out.println("name.elementAt (" + i +") is : " + name.elementAt(i));
}
get()
System.out.println("name.size() = "+name.size());
name.set(1, "rima");

for(int i=0; i<name.size(); i++) {


// System.out.println("name.elementAt (" + i +") is : " + name.elementAt(i));
System.out.println("name.get (" + i +") is : " + name.get(i));

}
}
}

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

for(int i = 0; i<3; i++) {


System.out.println("name.elementAt (" + i +") is : " + name.elementAt(i));
}

System.out.println("name.size() = "+name.size());
name.removeElementAt(2);
name.insertElementAt("ridoy", 2);

for(int i=0; i<name.size(); i++) {


System.out.println("name.get (" + i +") is : " + name.get(i));

}
}
}

package saifur.vector; package saifur.vector;


import java.util.*; import java.util.*;

public class EmptyVector public class EmptyVector


elements() { {
public static void main(String[] args) public static void main(String[] args)
{ {
Vector v1 = new Vector(); Vector v1 = new Vector();
89

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 }

Primitive Wrapper Class Constructor Argument

boolean Boolean boolean or String

byte Byte byte or String

char Character char

int Integer int or String

float Float float, double or String

double Double double or String

long Long long or String

short Short short or String

- See more at: http://www.w3resource.com/java-tutorial/java-wrapper-


classes.php#sthash.Z9MbzSBH.dpuf
90
91

Files(like hello.java) application


Must contain a class public class hello{ http://introcs.cs.princeton.edu/j http://www.hongkiat.com/blog/ Must contain a method named public static public return_type
ava/11cheatsheet/ cheatsheet-infographic- by main return_type name() { name() {
} software-developers/
} }
http://www.sitepoint.com/beginn http://www.tutorialspoint.com/java/java_basic_data http://java9s.com/core-java/data-types-in-java http://www.javacamp.org/javaI/primitiveTy http://en.wikibooks.org/wiki/Java_Programming/Primi
ing-java-data-types-variables-and- types.htm pes.html tive_Types
92

arrays/

http://mindprod.com/jgloss/jche
at.html

Java is not a
 javascript  Operating system  Not for just internet  Tiny language

Few Important Words


SDK Software development kit SE Standard edition RE Runtime edition ME Micro edition EE Enterprise edition

JDK Java development kit JSE Java standard edition J2RE Java 2 runtime edition J2ME Java two micro edition J2EE Java two enterprise edition

J2SE Java two standard 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

Java supports the following fundamental concepts


 Classes Resources Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as Class - A class can be defined as a template/blue print that describes the behaviors/states that
well as behaviors -wagging, barking, eating. An object is an instance of a class. object of its type support.
 Polymorphism  Objects
 Inheritance Software objects also have a state and behavior. A software object's state is stored in fields and every Class has a constructor
1. behavior is shown via methods.
 Encapsulation If we do not explicitly write a constructor for a class the Java compiler builds a default
a. tutorialspoint So in software development, methods operate on the internal state of an object and the object- constructor for that class
 Abstraction b. My resourece to-object communication is done via methods.
The main rule of constructors is that they should have the same name as the class. A class can
 Classes have more than one constructor.
 Objects
 Instance
 Method
 Message Parsing

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

public class Son extends Saifur{


}
“Son” is a subclass of “Mother” class

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

***Import statements(package members)


To make types easier to find and use, to avoid naming conflicts, and to control access, programmers bundle groups of related types Definition: A package is a grouping of related types providing access protection and name space management. Note that types refers
into packages. to classes, interfaces, enumerations, and annotation types. Enumerations and annotation types are special kinds of classes and
interfaces, respectively, so types are often referred to in this lesson simply as classes and interfaces.

Oracle resource 1. http://www.cis.upenn.edu/~matuszek/General/JavaSyntax/import.html


1. http://docs.oracle.com/javase/tutorial/java/package/usepkgs.html 2. http://wiki.answers.com/Q/What_is_the_import_statement_in_java?#slide=1
2. http://docs.oracle.com/javase/tutorial/java/package/index.html 3. http://en.wikibooks.org/wiki/Java_Programming/Keywords/import My resource
3. http://docs.oracle.com/javase/tutorial/java/package/packages.html 4. http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter05/packagesImport.html
4. 5. http://www.leepoint.net/notes-java/language/10basics/import.html
6.

Package>classes/package members classes


203 packages 3793 classes
Oracle Resources Oracle Resources

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{

public static void main(String[] args) {


System.out.println("hello world");
}
}

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

System.out.println("The sum of the two numbers is = " +


sum);
System.out.print(sum);
97

}
}

Output:

5
10
15The sum of the two numbers is = 15
15

Java's Built-in Primitive Data Types

Category Types Size (bits) Minimum Value Maximum Value Example

byte 8 -128 127 byte b = 65;

char c = 'A';
char 16 0 216-1
char c = 65;
Integer
short 16 -215 215-1 short s = 65;

int 32 -231 231-1 int i = 65;

long 64 -263 263-1 long l = 65L;

float 32 2-149 (2-2-23)·2127 float f = 65f;

Floating-point
double 64 2-1074 (2-2-52)·21023 double d = 65.55;

boolean 1 -- -- boolean b = true;


Other
void -- -- -- --

1.int 1.float 1.
2.double(most commonly used) public class dataType {

public static void main(String[] args) {


1.
Output /*
This program illustrates the differences between int and double.
Original value of var(int): 10 Call this file Example3.java.
Original value of x(double): 10.0 */
int var; // this declares an int variable
var after division(int): 2 double x; // this declares a floating-point variable
x after division(double): 2.5 var = 10; // assign var the value 10
x = 10.0; // assign x the value 10.0
System.out.println("Original value of var(int): " + var);
98

2. System.out.println("Original value of x(double): " + x);


Output

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

gallons = 10; // start with 10 gallons


liters = gallons * 3.7854; // convert to liters

System.out.println(gallons + " gallons is " + liters + " liters.");


}
}
99

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

do double else enum extends final

finally float for goto if implements

import instanceof int interface long native

new package private protected public return

short static strictfp super switch synchronized

this throw throws transient try void

volatile while

Вам также может понравиться