SlideShare a Scribd company logo
1 of 102
Java Programming Language
Md. Saifur Rahman Java Programming Basic Concept
1
Java
TABLE OF CONTENTS
Chapter Search Topic
CHAPTER 1 ............................................................................. #
SECTION 1.1 ...........................................................................................#
Subsection 1.1.a ...............................................................................#
Subsection 1.1.b ...............................................................................#
Subsection 1.1.c................................................................................#
SECTION 1.2 ...........................................................................................#
SECTION 1.3 ...........................................................................................#
CHAPTER 2 ............................................................................. #
SECTION 2.1 ...........................................................................................#
SECTION 2.2 ...........................................................................................#
Subsection 2.2.a ...............................................................................#
Subsection 2.2.b ...............................................................................#
Subsection 2.2.c................................................................................#
SECTION 2.3 ...........................................................................................#
CHAPTER 3 ............................................................................. #
SECTION 3.1 ...........................................................................................#
SECTION 3.2 ...........................................................................................#
SECTION 3.3 ...........................................................................................#
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.....................................................................................#
CHAPTER 3 ............................................................................. #
SECTION 3.1 ...........................................................................................#
SECTION 3.2 ...........................................................................................#
SECTION 3.3 ...........................................................................................#
Subsection 3.3.a ...............................................................................#
Subsection 3.3.b ...............................................................................#
Subsection 3.3.c.....................................................................................#
UseCtrl+F
STRING TOPIC Complex programs
FILE I/O TOPIC
THREAD TOPIC
CLASS TOPIC
INHERITANCE TOPIC
CONSTRUCTOR TOPIC
OBJECTTOPIC
METHODTOPIC
POLYMORPHISM TOPIC
EXCEPTION TOPIC
ENCAPSULATION TOPIC
PACKAGES, INHERITANCEANDINTERFACES TOOPIC
STATIC KEYWORDTOPIC
ABSTRACT KEYWORD TOPIC
Link
Web resource tutorials http://www.c4learn.com/javaprogramming/
http://www.programmingsimplified.com/java/source-code/java-
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
code
Color sample
RGB Color
code
Color sample
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
6+
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
javac Welcome.java
To execute
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
Filecreate File > new Project> java > java Application > projectname + projectlocation > finish
Javaprogramworks
Few littleconcepts
1. Function = method
2. Add = class name (With starting capital letter)
3. add() = Method (With starting lower case)
4. In java main() is not mandatory but not execute
5. In business wecan give class file not sourcefile but class file can
convertinto Sourcecode
C Java
include import
Object 1. Object = set of attributes = like structure
OOP must have3 things
1. Encapsulation ( লুকিয়ে রাখা )
2. Polymorphism( বহুরূপতা)
3. Inheritance( উত্তরাকিিার)
Class
1. Domain
2. Idea
3. Environment
4. For object we need an environment that’s why we use
class
 Suppose messi is the best player. But he cannot play in banani park. He must need an good field or environment where he
can play football.
Messi = object
Environment = class
5. User defined data-type
6. Set of objects
 Fruit is a class then object = (mango , jackfruit, banana, etc)
Declaration
class className
{
member variable declaration;
member fuction defination;
}
Classnaming conventions/rules
1. Name starts with a uppercase
2. Main class name = file name
First program
package class2;
import java.io.*;
class Class2
{
public static void main(String args[])
{
System.out.println("Hello world");
}
}
package class2;
import java.io.*;
public class Method_overloading1
{
public static void main(String args[])
{
int num = 7;
if(num % 2 == 0)
{
System.out.println("Even");
}
else
{
System.out.println("Odd");
}
1. program begins with a call to main() method.
2. In main( ), there is only one parameter, albeit a complicated one. String args[ ] declares a parameter
named args, which is an array of instances of the class String. (Arrays are collections of similar objects.)
3. Output is actually accomplished by the built-in println( ) method & displays the string which is passed to it.
& println( ) can be used to display other types of information, too. The line begins with System.out,
System is a predefined class that provides access to the system, and out is the output stream that is
connected to the console.
4. All statements in Java end with a semicolon.
5.
Class
Member
Member
Variable
Member
Function
6
}
}
Programprocess
1.
Comments // This is a single line comment
/* This is a
Multiline comment */
Lecture 3
(Wednesday, October 01, 2014)
packageclass3;
import java.util.Scanner;
public class Input
{
public static void main(String args[])
{
System.out.print("Enterta 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
packageclass3;
import java.util.Scanner;
public class OddEvenCheckWithFuncCall
{
int oddeven(int input)
{
if(input %2 == 0)
{
System.out.println(input+" is even...");
}
else
System.out.println(input+" is odd ");
Process one
packageclass3;
import java.util.Scanner;
class OddEvenCheck
{
int oddeven(int input)
{
if(input %2 == 0)
{
System.out.println(input+" is even...");
}
else
System.out.println(input+" is odd ");
return 0;
}
Process two
packageclass3;
import java.util.Scanner;
class OddEvenCheck
{
int oddeven(int input)
{
if(input %2 == 0)
return 1;
else
return 0;
}
}
public class OddEvenCheckWithFuncCall
Output
Low
Run Execute Interprete Starts from main()
High
1. Compile 2. Convert machine code to electric signal
7
return 0;
}
public static void main(String args[])
{
System.out.print("Enterta number to check odd/even = ");
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
oddeven(input);
non-static method oddeven(int) cannot be referenced from a static context
so this cannot run in java but c can compile it
}
}
}
public class OddEvenCheckWithFuncCall
{
public static void main(String args[])
{
System.out.print("Enterta number to check odd/even = ");
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
OddEvenCheck oec = new OddEvenCheck();
oec.oddeven(input);
}
}
{
public static void main(String args[])
{
System.out.print("Enterta number to check odd/even = ");
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
OddEvenCheck oec = new OddEvenCheck();
int out = oec.oddeven(input);
if(out == 1)
System.out.println(input+" is even number");
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
packageclass3;
import java.util.Scanner;
public class OddEvenCheckWithFuncCall
{
public static void main(String args[])
{
System.out.print("Enter a number to make a pyramid = ");
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
for(intr = 0; r<input; r++)
{
for(intc = 0; c< input-r-1; c++)
System.out.print("t");
for(intc = 0; c<=r*2; c++)
System.out.print("*" +"t");
System.out.println();
}
}
}
packageclass2;
class Class2
{
public static void main(String args[])
{
for(intr = 0; r<3; r++)
{
int p = r;
for(intc = 0; c<6; c++)
{
++p;
System.out.print(p +" ");
}
System.out.println();
}
}
}
packageclass2;
import java.util.Scanner;
public class Class2
{
public static void main(String args[])
{
System.out.print("Enter a number to make a half pyramid = ");
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
for(intr = 1; r<=input; r++)
{
for(intc = input-1; c>=r; c--)
System.out.print("t");
for(intc = 1; c<=r; c++)
System.out.print("*t");
System.out.println();
}
}
}
package personal;
import java.util.Scanner;
public class b
{
public static void main(String args[])
{
int i;
int pos=0;
int neg=0;
System.out.print("Enter the value of input : ");
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
int a[] = new int[input];
for(i=0; i<input; i++)
{
a[i] = sc.nextInt();
if(a[i]>0)
{
pos=pos+1;
}
else if(a[i]<0)
{
neg=neg+1;
}
}
System.out.println("Pos = " + pos);
System.out.println("Neg = " + neg);
}
}
Entert a number to make a piramid = 3
*
* * *
* * * * *
1 2 3 4 5 6
2 3 4 5 6 7
3 4 5 6 7 8
Enter a number to make a half pyramid = 3
*
* *
* * *
Enter the value of input : 4
1
2
3
-4
Pos = 3
Neg = 1
package personal;
public class ConstructorCallingExplain
{
public static void main(String args[])
{
int f0=0;
int f1 = 1, f2;
System.out.print("0 1 ");
for (int i=0; i<=10; i++)
{
f2 = f0+f1;
System.out.print(f2 + " ");
f0 = f1;
f1 = f2;
}
}
}
import java.util.Scanner;
public class Caller
{
public static void main(String args[])
{
System.out.print("Enter the number of elements in array = ");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n];
int maximum, i, location;
maximum = 0;
location = 0;
mport java.util.*;
class PrimeNumbers
{
public static void main(String args[])
{
int n, status = 1, num = 3;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of prime numbers you
want");
n = in.nextInt();
if (n >= 1)
{
System.out.println("First "+n+" prime numbers are :-
");
System.out.println(2);
}
for ( int count = 2 ; count <=n ; )
{
for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
{
if ( num%j == 0 )
{
status = 0;
break;
}
}
http://java67.blogspot.com/2014/01/how-to-check-if-given-number-is-
prime.html
http://www.programmingsimplified.com/java/source-code/java-program-
print-prime-numbers
http://beginnersbook.com/2014/01/java-program-to-display-prime-
numbers/
9
System.out.print("Enter " + n +" integers = ");
for (i = 0; i < n; i++)
a[i] = sc.nextInt();
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);
}
}
if ( status != 0 )
{
System.out.println(num);
count++;
}
status = 1;
num++;
}
}
}
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
classMyClass
{
// field,constructor,and
// methoddeclarations
}
class classname
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list)
{
// bodyof method
}
type methodname2(parameter-list)
{
// bodyof method
}
// ...
type methodnameN(parameter-list)
{
// bodyof method
}
}
1. The data, or variables, defined within a class are called instance variables.
2. A class declaration only creates a template; it does not create an actual object.
3. A class creates a new data type that can be used to create objects. That is, a class
creates a logical frameworkthat defines the relationship between its members.
When you declare an object of a class,
4. You are creating an instance of that class. Thus, a class is a logical construct. An
object has physical reality. (That is, an object occupies space in memory.)
4. Here is a class called Box that defines three instance
variables: width, height, and depth.
classBox
{
doublewidth;
doubleheight;
doubledepth;
}
5. To actually create a Box object, you will use a statement like
the following:
Box mybox = newBox(); // createa Box object called mybox
***After this statement executes, mybox will be an instance of Box
1. each time you create an instance of a class, you arecreating
an object that contains its own copy of each instance variable
defined by the class.
2. Thus, every
3. Box object will contain its own copies of the instance
variables width, height, and depth. To
4. access these variables, you will use the dot (.) operator. The
dot operator links the name of
5. the object with the name of an instance variable. For
example, to assign the width variable
of mybox the value 100, you would use the following statement:
mybox.width = 100;
classBox
{
double width;
double height;
double depth;
}
classClass2
{
publicstaticvoidmain(Stringargs[])
{
Box myBox = newBox();
}
}
Class
1. Domain
2. Idea
3. Environment
4. For object we need an environment that’s why we use class
 Suppose messi is the best player. But he cannot play in banani park. He must need an good field or environment where he
can play football.
Messi = object
Environment = class
5. User defined data-type
6. Set of objects
7. when we create a class, weare creating a new data type
8. a blueprint of an object
9. a template
10.an environmentto create an object
11.
 Fruit is a class then object = (mango , jackfruit, banana, etc)
11
Declaration
class className
{
member variable declaration;
member fuction defination;
}
Thus in short Class have -
1. Class name
2. Properties or Attributes
3. Common Functions
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.
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
Explanation Of Syntax :
Class name
class classname {
1. class is Keyword in Java used to create class in java.
2. classname is Name of the User defined Class.
Class Instance Variable
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
1. Instance Variables are Class Variables of the class.
2. When a number of objects are created for the same class, the same
copy of instance variable is provided to all.
3. Instance variables have different value for different objects.
4. Access Specifiers can be applied to instance variable i.e public,private.
5. Instance Variable are also called as “Fields“
Inheritance Topic
 http://www.studytonight.com/java/inheritance-in-java.php
1. Inheritproperty of another class
2. a class to inherit property of another class
3.
class Vehicle
{
......
}
class Car extends Vehicle
{
....... //extends the property of vehicle
class.
}
 Vehicle is super class of Car.
 Car is sub class of Vehicle.
 Car IS-A Vehicle.
Pictures
Class's
Members
Member instance Variable
Member instance methods/Function
Object of another class which is declared
in current class
12
Example
package encapsulation.pack1;
import encapsulation.pack2.Add;
public class Caller extends Add
{
public static void main(String args[])
{
// Add obj = new Add();
Caller obj = new Caller();
System.out.println(obj.x);
System.out.println(obj.y);
}
}
package encapsulation.pack2;
public class Add
{
public int x = 10;
private int y =20;
public int show()
{
return x+y;
}
}
10
Exception in thread "main" java.lang.RuntimeException: Uncompilable
sourcecode - 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/

-
Inheritance
Single Inheritance
Multilevel Inheritance
Heirarchical Inheritance
13
package personal;
class Vehicle
{
void method()
{
System.out.println("class Vehicle is showing");
}
}
class Car extends Vehicle
{
void method()
{
System.out.println("class Car is showing");
}
}
class Gear extends Car
{
void method()
{
System.out.println("class Gear is showing");
}
}
public class constructor
{
public static void main(String args[])
{
Gear obj = new Gear();
obj.method();
}
}
package personal;
class Vehicle
{
void method()
{
System.out.println("class Vehicle is showing");
}
}
class Car extends Vehicle
{
void method()
{
System.out.println("class Car is showing");
}
}
class Gear extends Vehicle
{
void method()
{
System.out.println("class Gear is showing");
}
}
public class constructor
{
public static void main(String args[])
{
Gear obj = new Gear();
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;
Classname() //constructor
{
a = 10;
b = 20;
}
}
public class constructor
{
public static void main(String args[])
{
Classname obj = new Classname(); // an obj
creation
System.out.println(obj.a + obj.b);
}
}
package personal;
class ClassName // a class definition
{
int a;
int b;
ClassName() //constructor
{
a = 10;
b = 20;
}
int classmethod()
{
a = 30;
b = 40;
return 0; // or void
}
}
public class constructor
{
public static void main(String args[])
{
ClassName obj = new ClassName(); // an obj
creation
System.out.println(obj.a + obj.b);
obj.classmethod();
System.out.println(obj.a + obj.b);
}
}
package personal;
class Const
{
int length, width;
Const(int len, int wid)
{
length = len;
width = wid;
}
}
public class constructor {
public static void main(String args[])
{
Const obj = new Const(10, 20);
System.out.println("length "+ obj.length);
}
}
Constructors : Initializing an Class Object in Java Programming
1. Objects contain there own copy of Instance Variables.
2. It is very difficult to initialize eachand every instance variable of each and every object of Class.
3. Java allows objects to initialize themselves when they are created. Automatic initialization is
performed through the use of a constructor.
4. A Constructor initializes an object as soonas object gets created.
5. Constructorgets calledautomatically after creationof objectand before completion of new
Operator.
Some Rules of Using Constructor :
1. ConstructorInitializes an Object.
2. Constructorcannotbe calledlike methods.
3. Constructors are calledautomatically as soonas object gets created.
4. Constructordon't have any return Type. (even Void)
5. Constructorname is same as that of "Class Name".
6. Constructorcan acceptparameter.
Live Example : How Constructor Works ?
class Rectangle {
int length;
int breadth;
Rectangle()
{
length = 20;
breadth = 10;
}
}
class RectangleDemo {
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);
Vehicle
Car
Gear
Showing
Vehicle
Car Gear
Showing
14
}
}
Explanation :
1. new Operator will create an object.
2. As soon as Object gets created it will call Constructor-
Rectangle() //This is Constructor
{
length = 20;
breadth = 10;
}
3. In the above Constructor Instance Variables of Object r1 gets their own values.
4. Thus Constructor Initializes an Object as soon as after creation.
5. It will print Values initialized by Constructor -
System.out.println("Length of Rectangle : " + r1.length);
System.out.println("Breadth of Rectangle : " + r1.breadth);
class Rectangle {
int length;
int breadth;
Rectangle()
{
length = 20;
breadth = 10;
}
void setDiamentions()
{
length = 40;
breadth = 20;
}
}
class RectangleDemo {
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);
r1.setDiamentions();
System.out.println("Length of Rectangle : " + r1.length);
System.out.println("Breadth of Rectangle : " + r1.breadth);
}
}
Explanation :
1. After the Creation of Object , Instance Variables have their
own values inside.
2. As soon as we call method , values are re-initialized.
ParameterizedConstructors: ConstructorTakingParameters
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".
2. Argument can be of any type i.e Integer,Character,Array or any Object.
3. Constructor can take any numberof Argument.
Live Example : Constructor Taking Parameter in Java Programming
class Rectangle {
int length;
int breadth;
Rectangle(int len,int bre)
{
length = len;
breadth = bre;
}
}
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle(20,10);
System.out.println("Length of Rectangle : " + r1.length);
System.out.println("Breadth of Rectangle : " +
r1.breadth);
}
}
Explanation:
Carefully observe above program You will found something like this
Rectangle r1 = new Rectangle(20,10);
This is Parameterized Constructor taking argument.These arguments are used
for any purpose inside Constructor Body.
 New Operator is used to Create Object.
 We are passing Parameter to Constructor as 20,10.
 These parameters are assigned to Instance Variables of the Class.
 We can Write above statement like -
Rectangle(int length,int breadth)
{
length = length;
breadth = breadth;
}
OR
Rectangle(int length,int breadth)
{
this.length = length;
this.breadth = breadth;
}
But if we use Parameter name same as Instance variable then compiler will
recognize instance variable and Parameter but user or programmer may
confuse. Thus we have used "this keyword" to specify that "Variable is
Instance Variable of Object r1".
Methodoverloading (exampleofpolymorphism)
1. http://www.beingjavaguys.com/2013/10/method-overloading-in-java.html
“Overloading injava occurs when methods in a same class or in childclasses shares a
same name witha ‘difference innumber of arguments’ or ‘difference inargument type’
or both.”
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.
1) Have different number of arguments.
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(intempId){
2. ......
3. }
4.
5. public void getEmpName(String empName){
6. ......
7. }
2. Method Overloadingoccurs when methods are having same
name, but
3. A difference in the number of their parameters or type of their
parameters or both.
15
8.
9. public void getEmpName(intempId,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;
public class constructor {
public constructor()
{
System.out.println("Constructor auto called at the
time of initializing object");
}
public static void main(String args[])
{
constructor obj = new constructor(); //auto called
}
}
package personal;
class Student
{
String name;
int roll;
float mark;
Student()
{
name = "Md. Saifur Rahman";
roll = 67;
mark = 70;
}
}
public class ConstructorCallingExplain {
public static void main(String args[])
{
Student obj = new Student();
System.out.println(obj.name);
System.out.println(obj.roll);
System.out.println(obj.mark);
}
}
package personal;
class Student
{
String name;
int roll;
float mark;
Student(String name, int roll, float mark)
{
this.name = name;
this.roll = roll;
this.mark = mark;
}
}
public class ConstructorCallingExplain
{
public static void main(String args[])
{
Student obj1 = new Student("saifur", 67, 70.0f);
Student obj2 = new Student("rasel", 58, 75.5f);
System.out.println(obj1.name);
System.out.println(obj1.roll);
System.out.println(obj1.mark);
System.out.println(obj2.name);
System.out.println(obj2.roll);
System.out.println(obj2.mark);
}
}
Object Topic
1. http://docs.oracle.com/javase/tutorial/java/concepts/object.html
2.
1. Object = set of attributes = like structure
2. Objects havestates and behaviors. Example: A dog has states - color, name, breed as well as
behaviors -wagging, barking, eating. An objectis an instance of a class.
3. Softwareobjects also have a state and behavior. A softwareobject's state is stored in fields and
behavior is shown via methods.
4. In softwaredevelopment, methods operate on the internal state of an objectand the object-to-
object communication is done via methods.
5. A class provides the blueprints for objects. So basically an objectis created froma class
Creating an Object:
There are three steps when creating an object froma class:
Declaration: A variable declaration with a variablename with an objecttype.
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);
Constructor
Defaultor
argumentless
Argumented
Copy
16
Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);
1. We create an object to create a reference
2. To access class’s members
3.
1. Suppose a gentleman wants to marry a woman who has 3 childs. He
wants to take care of them too.
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
4. So, to make the childs as his own he has to marry that woman
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
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,
child3.
2. It is important to understand that changes to the instance variables of
one object have no effect on the instance variables of another. package class3;
class Woman
{
int child1;
int child2;
int child3;
}
public class classObj
{
public static void main(String args[])
{
Woman man1 = new Woman();
man1.child1 = 10;
man1.child2 = 12;
man1.child3 = 15;
Woman man2 = new Woman();
man2.child1 = 5;
man2.child2 = 6;
man2.child3 = 7;
System.out.println("Age of the child1 = " + man1.child1);
System.out.println("Age of the child1 = " + man2.child1);
}
}
package class3;
//creating a class
class Woman
{
int child1;
int child2;
int child3;
}
public class classObj
{
public static void main(String args[])
{
//obj creation
//className obj; // declare
//man is a reference to an object of type Box. man does not yet refer to
an actual object. The next line allocates an object and assigns a reference to it
to woman. After the second line executes, you can use woman as if it were a
//man object. But in reality, woman simply holds, in essence, the
memory address of the actual man object.
//obj = new className(); //initialize
//or, className obj = new className()
Woman man= new Woman();
//accessing the members of the woman class
// & 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
Assigning Object Reference Variables
Box b1 = new Box();
Box b2 = b1;
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.
3. However, this would be wrong. Instead, after this fragment executes, b1 and b2 will both refer to the
same object. The assignment of b1 to b2 did not allocate any memory or copy any part of the original
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;
class Rectangle // a class definition
{
int length;
int width;
Rectangle(int l, int b) //constructor
{
length = l;
width = b;
}
void area(Rectangle obj)
{
System.out.println("Area = " + (obj.length * obj.width));
}
}
public class constructor
{
public static void main(String args[])
{
Rectangle obj = new Rectangle(20, 8); // an obj creation
obj.area(obj);
}
}
package personal;
class Rectangle // a class definition
{
int length;
int width;
Rectangle(int l, int b) //constructor
{
length = l;
width = b;
}
void rect (int length, int width)
{
System.out.println("area = " + (length*width));
}
}
public class constructor
{
public static void main(String args[])
{
Rectangle obj = new Rectangle(10, 5);
obj.rect(obj.length, obj.width);
}
}
Object as method’s argument
18
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
Vehicle
Call by
Value
Call by
reference
19
Polymorphism Topic
http://beginnersbook.com/2013/03/polymorphism-in-java/
Difference between Overloading & overriding
Method Overloading Method Overriding
1. http://www.programmerinterview.com/index.php/java-questions/method-overriding-vs-overloading/
2.
1.
1. Method overloading in Java occurs when two or more methods in the sameclass have the exact samename but different
parameters (remember that method parameters accept values passed into the method).
2. The conditions for method overloading
o The number of parameters is different for the methods.
o The parameter types are different (like changing a parameter that was a float to an int).
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 samemethod name, return type,
number of parameters, and types of parameters as the method in the parent class, and the only difference would be the
definition of the method.( overriding amethodeverything remains exactly the same except the methoddefinition)
2. overriding is a run time phenomenon – not a compile time phenomenon like method overloading
3. overloading is static polymorphismwhereas overriding is dynamic polymorphism
4. Argumentlist should be different while doing method overloading. Argumentlist should be same in method Overriding.
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 fastas compareto Overridden method in Java.
8.
 Overloadingisthe situationthattwoor more methodsinthe same classhave the same name butdifferentarguments.
 Overridingmeanshavingtwomethodswiththe same methodname andarguments(i.e.,methodsignature).One of themisinthe Parentclassand the otherisin
the Childclass.
Overloading
Happening within the same class.
Method signature should not be same.
It happen at time of compliance or we can say overloading is
the early binding or static binding.
Method can have any return type.
Method can have any access level.
Overriding
Happening between super class and sub class.
Method signature should be same.
It happen on time of run time or we can say overriding is
dynamic binding or let binding.
Method return type must be same as super class method
Method must have same or wide access level than super
class method access level.
Polymorphism
Method Overloading
Method Overriding
20
package personal;
class InA
{
void method(int l)
{
System.out.println("Method overloaded in 1");
}
void method(float b)
{
System.out.println("Method overloaded in 2");
}
}
public class constructor
{
public static void main(String args[])
{
InA obj = new InA();
obj.method(4);
}
}
package personal;
class Parent
{
void method()
{
System.out.println("Parent is showing");
}
}
class Child extends Parent
{
void method()
{
System.out.println("Child is showing");
}
}
public class constructor
{
public static void main(String args[])
{
Child obj = new Child();
obj.method();
}
}
package personal;
public class constructor
{
public static void main(String args[])
{
b obj = new b();
obj.method();
}
}
package personal;
class a
{
void method()
{
System.out.println("Parent a is
showing");
}
}
package personal;
class b extends a
{
void method()
{
System.out.println("Child b is
showing");
}
}
Child b is showing
Method overriding
 is the basis for polymorphism
 only applicable in methods
 overriding is only applicable for the classes related to each other through inheritance
 only between super classes & subclasses

 To override the functionality of an existing method.

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:
 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
superclass.
 The access level cannot be more restrictive than the overridden method's access level. For example: if the superclass
method is declared public then the overridding method in the sub class cannot be either private or protected.
Instance methods can be overriddenonly if they are inherited by the subclass.
RulesforMethodOverriding :
1. Method Must have Same Name as that of Method Declared in Parent Class
2. Method Must have Same Parameter List as that of Method Declared in Parent Class
3. IS-A relation should be maintained in order to Override Method.
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 ;
public class Caller{
public static void main(String args[]){
Animal a = new Animal(); // Animal referenceand object
Animal b = new Dog(); // Animal reference but Dog object
a.move();//runs the method in Animal class
b.move();//Runs the method in Dog class
}
}
package overriding ;
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
In compile time, the check is made on the referencetype. However, in the
runtime, JVM figures out the object type and would run the method that
belongs to that particular object.
Therefore, in the above example, the programwill compile properly since
Animal class has the method move. Then, at the runtime, it runs the method
specific for that object.
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
Animal b = new Dog(); // Animal reference but Dog object
b.move(); //Runs the method in Dog class
}
}
package overriding ;
class Dog extends Animal{
public void move(){
System.out.println("Dogscan walk and run");
}
}
run:
Animals can move
Dogs can walk and run
BUILD SUCCESSFUL (total time: 0 seconds)
 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 Animals can move
Dogs can walk and run
package com.c4learn.inheritance;
public class Vehicle {
public void vehicleMethod() {
System.out.println("Method in Vehicle.");
}
}
package com.c4learn.inheritance;
public class TwoWheeler extends Vehicle {
public void vehicleMethod() {
System.out.println("Method" + " in TwoWheeler.");
}
public static void main(String[] args) {
TwoWheeler myBike = new TwoWheeler();
Vehicle myVehicle = new Vehicle();
myVehicle.vehicleMethod();
myBike.vehicleMethod();
}
}
package encapsulation;
publicclassInheritanceRulesextendsbaseClass{
publicintcalculate(intnum1,intnum2) {
returnnum1+num2;
}
publicstaticvoidmain(String[] args) {
baseClassb1= newbaseClass();
int result= b1.calculate(10,10);
System.out.println("Result:" + result);
}
}
package encapsulation;
classbaseClass {
publicintcalculate(intnum1,intnum2) {
returnnum1*num2;
}
}
Method in Vehicle.
Method in TwoWheeler.
run:
Result: 100
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 monitorfor errors
}
catch(ExceptionType1exOb){
// exceptionhandler for ExceptionType1
}
catch(ExceptionType2exOb){
// exceptionhandler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
24
}
Rules
Examples
class Caller
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
System.out.println(a);
System.out.println("Skipping notmaintained");
}
}
class Caller
{
public static void main(String args[])
{
int d = 0;
try
{
int a = 42 / d;
System.out.println(a);
}
catch(Exception err1)
{
System.out.println("Skipping maintained & "+ err1);
}
}
}
run:
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at interfaces_4.pack1.Caller.main(Caller.java:7)
Java Result: 1
run:
Skipping maintained & java.lang.ArithmeticException: / by zero
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 programfrom automatically terminating.
 Most users wouldbe confused(to say the least) if your program
Opinion
Classification
25
Loop Topic
 
Definitions
6.
General forms
Rules
Examples
packagesaifur;
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 arebetter 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'tcare.....");
}
}
}
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


 to hide the implementation details from users
 Encapsulation is also known as “data Hiding”
 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.
 Provides abstraction between an object and its clients.
 Protects an object from unwanted access by clients.
 Example: A bank application forbids a client to change an Account's balance.
 Encapsulation is a practice to bind related functionality (Methods) & Data (Variables) in a protective wrapper (Class) with required access modifiers
(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 a process of wrapping of data and methods in a single unit is called encapsulation
 Encapsulation is the mechanism of binding together the data and the code, so that they are not misused or accidentally modified.
 Encapsulation is technique by which we can hide the data with in a class and provide public methods to manipulate the hide data.To achieve encapsulation we can declare variables private and provide
public methods to manipulate these private variables.

 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;
import encapsulation.pack2.Add;
public class Caller
{
public static void main(String args[])
{
Add obj = new Add();
System.out.println("x+y = " + obj.show());
}
}
package encapsulation.pack2;
public class Add
{
private int x = 10, y =20;
public int show()
{
return x+y;
}
}
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
1
Inheritance Inheritance is a process where one object acquires the properties of another object
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{
}
public class FourWheeler extends Vehicle{
}
public class TwoWheeler extends Vehicle{
1. Vehicle is the superclass of TwoWheeler class.
2. Vehicle is the superclass of FourWheeler class.
3. TwoWheeler and FourWheeler are sub classes of Vehicle class.
4. WagonR is the subclass of both FourWheeler and Vehicle classes.
IS-A relationship of above example is -
TwoWheeler IS-A Vehicle
FourWheeler IS-A Vehicle
WagonR IS-A FourWheeler
32
}
public class WagonR extends FourWheeler{
}
publicclass Caller
{
publicstaticvoid main( String[] args )
{
FourWheeler v1 = new FourWheeler();
TwoWheeler v2 = new TwoWheeler();
WagonR v3 = new WagonR();
System.out.println(v1instanceofVehicle);
System.out.println(v2instanceofVehicle);
System.out.println(v3instanceofVehicle);
System.out.println(v3instanceofFourWheeler);
}
}
publicclass Vehicle
{
}
true
true
true
true
publicclass FourWheeler extends Vehicle
{
}
publicclass TwoWheeler extends Vehicle
{
}
publicclass WagonR extends FourWheeler
{
}
Packages and Interfaces
package interfaces_2.pack1;
importinterfaces_2.pack2.Balance;
publicclassCaller
{
publicstaticvoidmain(Stringargs[])
{
Balance obj[] =newBalance[3];
obj[0] = newBalance("Saifur",100);
obj[1] = newBalance("hasan",5000);
obj[2] = newBalance("sazzad",100000);
//obj[0].show();
//obj[1].show();
//obj[2].show();
for(inti = 0;i<3 ; i++)
{
obj[i].show();
}
}
}
package interfaces_2.pack2;
publicclassBalance
{
Stringname;
floatbalance;
publicBalance(Stringname,floatbalance)
{
this.name =name;
this.balance =balance;
}
publicvoidshow()
{
if(balance<0)
System.out.print("-->");
System.out.println(name +": $" + balance);
}
}
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
any constructors
 You cannot instantiate an interface.
 All of the methods in an interface are abstract.
 An interface can extend multiple interfaces
 An interface is not extended by a class; it is implemented by a class.
 An interface cannot contain instance fields. The only fields that can
appear in an interface must be declared both static and final
 Methods in an interface are implicitly public.
 Each method in an interface is also implicitly abstract, so the abstract
keyword is not needed.

 using interface, you can specify what a class must do, but not how it
does it
 An interface in java is a blueprint of a class. It has static constants and
abstract methods only.
 It is used to achieve fully abstraction and multiple inheritance in Java.
 Java Interface also represents IS-A relationship
 It cannot be instantiated just like abstract class
 We can create object for class but not for interface
 All the members/fields inside the interface are public & abstract &
static & final even if we do not declare them . It’s an automatic/default
mechanism
 Does not have any method implementation
 If the class which implements the interface does not override the
method, it should be marked abstract
 Interface can extends any numbers of interfaces

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 Whena class implementsaninterface,youcanthinkof the class as signinga
contract, agreeingtoperformthe specificbehaviorsof the interface.If aclassdoes
not performall the behaviorsof the interface,the classmustdeclare 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 ,
hence it is declared as static.
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
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
In this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory
at the time of object creation, each object will have the copy of the instance variable, if it is incremented, it won't reflect to other objects. So each
objects will have the value 1 in the count variable.
Program of counter by static variable
As we have mentioned above, static variable will get the memory only once, if any
object changes the value of the static variable, it will retain its value.
1. class Counter2{
2. static int count=0;//will get memory only once and retain its value
35
1. class Counter{
2. int count=0;//will get memory when instance is created
3.
4. Counter(){
5. count++;
6. System.out.println(count);
7. }
8.
9. public static void main(String args[]){
10.
11. Counter c1=new Counter();
12. Counter c2=new Counter();
13. Counter c3=new Counter();
14.
15. }
16. }
Test it Now
Output:1
1
1
3.
4. Counter2(){
5. count++;
6. System.out.println(count);
7. }
8.
9. public static void main(String args[]){
10.
11. Counter2 c1=new Counter2();
12. Counter2 c2=new Counter2();
13. Counter2 c3=new Counter2();
14.
15. }
16. }
Test it Now
Output:1
2
3
class Caller
{
int a =5;
public static void main(String args[])
{
System.out.println(a);
}
}
Exception in thread "main" java.lang.RuntimeException: Uncompilable
source code - non-static variable a cannot be referenced from a static
context
at Static.pack1.Caller.main(Caller.java:11)
class Caller
{
static int a =5;
public static void main(String args[])
{
System.out.println(a);
}
}
5
package Static.pack1;
import Static.pack2.Balance;
class Caller
{
public static void main(String args[])
{
Balance obj = new Balance();
System.out.println(obj.a);
}
}
package Static.pack2;
public class Balance
{
public static int a = 5;
}
package Static.pack1;
import Static.pack2.Balance;
class Caller
{
public static void main(String args[])
{
System.out.println(Balance.a);
}
}
package Static.pack2;
public class Balance
{
public static int a = 5;
}
You can see that we can happily access the “a” instance variable in
the “Balance” class without actually creating an object of type
“Balance”. We can just use the “Balance” class directly. That’s
because the variable is static, and hence belongs to the class, not
any particular object of that class.
The fact that we declared it public allows us to access it from other
classes (Application in this case)
5
5
packageStatic.pack1;
import Static.pack2.Balance;
class Caller
{
public static void main(String
args[])
{
Balance.a = 10;
System.out.println(Balance.a);
}
}
packageStatic.pack2;
public class Balance
{
public static int a = 5;
}
package Static.pack1;
import Static.pack2.Balance;
class Caller
{
public static void main(String args[])
{
Balance.a = 10;
System.out.println(Balance.a);
}
}
package Static.pack2;
public class Balance
{
public final static int a = 5;
}
Using the Static Keyword to Create Constants
One common use of static is to create a constant value that’s
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
constant (in other words, to prevent it ever being changed).
10 error
package Static.pack1;
import Static.pack2.Balance;
class Caller
{
public static void main(String args[])
{
Balance Balance1 = new Balance();
Balance Balance2 = new Balance();
Balance Balance3 = new Balance();
}
}
package Static.pack2;
public class Balance {
// Set count to zero initially.
static int count = 0;
public Balance() {
// Every time the constructor runs, increment count.
count++;
// Display count.
System.out.println("Created object number: " + count);
}
}
run:
Created object number: 1
Created object number: 2
Created object number: 3
package Static.pack1;
import Static.pack2.Balance;
class Caller
{
public static void main(String args[])
{
Balance Balance1 = new Balance();
Balance Balance2 = new Balance();
Balance Balance3 = new Balance();
System.out.println(Balance2.getID());
}
}
package Static.pack2;
public class Balance
{
static int count = 0;
int id;
public Balance()
{
count++;
id= count;
}
public int getID()
{
return id;
}
}
run:
2
36
Opinion
Classification
static variable static method
1)
If you declare any variable as static, it is known
static variable.
 The static variable can be used to refer the common property of all objects (that
is not unique for each object) e.g. company name of employees,college name of students etc.
 The static variable gets memory only once in class area at the time of class loading.
2)
If you apply static keyword with any method, it is known as static method
 A static method belongs to the class rather than object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 static method can access static data member and can change the value of it.
static method
 It is a method which belongs to the class and not to the object(instance)
 A static method can access only static data. It can not access non-static data (instance variables)
 A static method can call only other static methods and can not call a non-static method from it.
 A static method can be accessed directly by the class name and doesn’t need any object
 Syntax : <class-name>.<method-name>
 A static method cannot refer to "this" or "super" keywords in anyway
 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
the initialization of any instance variables
 A single copy to be shared by all instances of the class
 A static variable can be accesseddirectly by the class name and doesn’t need any object
 Syntax : <class-name>.<variable-name>
1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }
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 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.
1. //Program of changing the common property of all objects(static field).
2.
3. class Student9{
4. int rollno;
5. String name;
6. static String college = "ITS";
7.
8. static void change(){
9. college = "BBDIT";
10. }
11.
12. Student9(int r, String n){
13. rollno = r;
14. name = n;
15. }
16.
17. void display (){System.out.println(rollno+" "+name+" "+college);}
18.
19. public static void main(String args[]){
20. Student9.change();
21.
22. Student9 s1 = new Student9 (111,"Karan");
23. Student9 s2 = new Student9 (222,"Aryan");
24. Student9 s3 = new Student9 (333,"Sonoo");
25.
26. s1.display();
27. s2.display();
28. s3.display();
29. }
30. }
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
class Caller{
int rollno;
String name;
static String college ="ITS";
Caller(int r,String n, String m){
rollno = r;
name = n;
college = m;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[])
{
Caller s1 = new Caller(111,"Karan", "SEU");
Caller s2 = new Caller(222,"Aryan", "BAF");
s1.display();
s2.display();
}
}
run:
111 Karan BAF
222 Aryan BAF
BAF because
The static variable can be used to refer
the common property of all objects (that
is not unique for each object)
 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.
1. //Program to get cube of a given number by static method
2.
3. class Calculate{
4. static int cube(int x){
5. return x*x*x;
6. }
7.
8. public static void main(String args[]){
9. int result=Calculate.cube(5);
10. System.out.println(result);
11. }
12. }
Output:125
class Caller
{
static int a =5;
public static void main(String args[])
{
System.out.println("Hello "+a);
}
}
run:
Hello 5
 A static variable can be accessed directly by the class name and doesn’t
need any object
Restrictions for static method
There are two main restrictions for the static method. They are:
 The static method can not usenon static data member or call non-static method directly.
 this and super cannotbe used in static context.
37
public class Stuff {
public static String name = "I'm a static variable";
}
public class Application {
public static void main(String[] args) {
System.out.println(Stuff.name);
}
}
1. class A{
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. System.out.println(a);
6. }
7. }
Output:Compile Time Error
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 wecreate 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 programit firstlook that programwhich has static method & called as a main & defined as
public access modifier
static block
 Is used to initialize the static data member.
 It is executed before main method at the time of classloading.
class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Output:static block is invoked
Hello main
// Demonstrate static variables, methods, and
blocks.
class UseStatic {
static int a = 3;
static int b;
static void meth(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}
Static block initialized.
x = 42
a = 3
b = 12
Outside of the class in which they are defined, static methods and variables can be used
independently of any object. To do so, you need only specify the name of their class followed by the
dot operator. For example, if you wish to call a static method from outside its class, you can do so
using the following general form:
classname.method( )
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
 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
 Abstract class exist to extended they cannot be instantiated


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 wemake the variable final then the value of that variable cannot be changed once assigned.
 Way 2 : Final Method
o We cannot Overridethe final method as we cannot change the method once they are declared final.
 Way 3 : Final Class
o We cannot inherit the final class
 The final keyword is a non-access modifier.
 It can be applied to a class, method(both instance and static) and variable(instance, static, local and parameter).
Examples
Pictures
Explanation
Access level
Opinion
Final Entity Description
final Method is inherited but cannot be overriden so always method fromparent class will be executed.
package com.c4learn.inheritance;
39
Final Value Final Value cannot be modified
Final Method Final Method cannot be overriden
Final Class Final Class cannot be inherited
public class ShapeClass {
final void setShape() {
System.out.println("I am Inherited");;
}
public static void main(String[] args) {
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
Constants
 Fields that are marked as final, static, and public are effectively known as constants
 For example, the following variable declaration defines a constant named PI, whose value is an approximation of pi
1 public static final double PI = 3.141592653589793;
 Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so.
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,
ARRAY_SIZE
MAX_GRADE
PI
If a primitive type or a String is defined as a constantand the value is known at compile time, the compiler replaces the constant name
everywhere in the codewith 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
 Superisusedto referthe immediate parentof 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 Test
{
int i = 20;
void local()
{
int i = 10;
System.out.println("Local i = " + i);
System.out.println("Global this.i = " + this.i);
//this = gloabl
}
public static void main(String args[])
{
Test obj = new Test();
obj.local();
}
}
package personal;
class Student
{
String name;
int roll;
float mark;
Student(String name, int roll, float mark)
{
this.name = name;
this.roll = roll;
this.mark = mark;
}
}
public class ConstructorCallingExplain
{
public static void main(String args[])
{
Student obj1 = new Student("saifur", 67, 70.0f);
Student obj2 = new Student("rasel", 58, 75.5f);
System.out.println(obj1.name);
System.out.println(obj1.roll);
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
Child Class/Derived Class/Inherited class
Parent Class/Base class/Super Class
Child Class/Derived Class/Inherited class
Parent Class/Base class/Super Class
•Likeimport
•Everythinginbase
classshouldbepublic
ifwewanttoaccess
44
45
The History and
Evolution of Java
Object-oriented programming is a programming methodology that helps organize
complex programs through the use of
1. inheritance,
2. encapsulation, and
3. polymorphism.
These 3 musthave been in objectoriented programming language
World Wide Web demanded portable programs.
Perhaps the most important example of Java’s influence is C#. Created by Microsoft to
supportthe .NET Framework, C# is closely related to Java. Forexample, both share the
same general syntax, supportdistributed programming, and utilize the same object model.
There are, of course, differences between Java and C#, but the overall “look and feel” of
these languages is very similar.
Goals of java
1. It should be object oriented
2. A single representation of a program could be executed on multiple
operating systems
3. It should fully supportnetwork programming
4. It should execute codefrom remote sources securely
5. It should be easy to use
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# ?
1. After the creation of Java, Microsoftdevelopedthe 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, supportdistributed programming, and utilize the same object model.
3. Though there are some differences between Java and C#, but the overall feel of these languages is
very similar.
4. If you already know C#, then learning Java will be easy and vice versa
5. Java and C# are optimized for two different types of computing environments.
6. C# and Java Both Languages are drew from C++.
7. Both Languages are capable of creating cross platform portable program code.
Consider Scenario of Java Programming Language
1. Java is created by Sun Micro System.
2. Java Compiler produces Intermediate code calledByte Code.
3. Byte Codei.e intermediate code is executed by the Run Time Environment.
4. In Java Run Time Environment is called as JVM [ Java Virtual Machine]
5. If we have JVM already installed on any platform then JVM can produce machine dependent Code
basedon the intermediate 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–
Java is Considered as Platformindependent becauseof many different reasons which are
listed below –
1. Output of a Java compiler is Non Executable Code i.e Bytecode.
2. Bytecode is a highly optimized set of instructions
3. Bytecode is executed by Java run-time system, which is calledthe Java Virtual
Machine (JVM).
As the output of Java Compiler is Non Executable Code we canconsiderit as Secure
(it cannot be used for automated executionof malicious programs).
Important Note :
As the output of Java Compiler is Non Executable Codewe can consider it as Secure (it
cannot be used for automated execution of malicious programs).
4. JVM is an interpreter.
5. JVM accepts Bytecode as input and execute it.
6. Translating a Java program into bytecodemakes it much easier to run a program in
a wide variety of environments because only the JVM needs to be implemented
for eachplatform.
7. For a given System we have Run-time package , once JVM is installed for
particular systemthen any java program can run on it.
8. However Internal details of JVM will differ from platform to platform but still
all understand the Same Java Bytecode.
Java is a strictly typed language, it checks your code at compile time. However, it
also checks your code at run time
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
The Java Buzzwords
No discussion of Java’s history is complete withouta look at the Java buzzwords. Although
the fundamentalforces that necessitated the invention of Java are portability and security,
other factors also played an important role in molding the final formof the language. The
key considerations were summed up by the Java team in the following list of buzzwords:
• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed
• Dynamic
48
49
50
An Overview of Java
Two Paradigms
All computer programs consistof two elements:
2. codeand
3. data
Furthermore, a programcan be conceptually organized around its code or around its data. That is,
1. some programs are writtenaround“what is happening” (process-orientedmodel.)and
process-oriented model. This approach characterizes a programas a series of linear steps (that is, code). The
process-oriented modelcan be thoughtof as code acting on data
2. others are writtenaround“who is being affected.” ( Object-oriented programming)
Object-oriented programming organizes a programaround its data (that is, objects) and a set of well-defined
interfaces to that data. An object-oriented programcan be characterized as data controlling access to code.
As you will see, by switching the controlling entity to data
The Three OOP Principles
1. Encapsulation ( লুকিয়ে রাখা ) Inheritance is the process bywhich one object acquires the properties of another object.
2. Polymorphism( বহুরূপতা) 1. “many forms”
3. Inheritance( উত্তরাকিিার)
Program
By convention,the name of the mainclassshouldmatchthe name of the file thatholdsthe 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
1. for(initialization; condition; iteration) statement;
2. ( x++ ) = ( x+=1 ) = ( x = x+1 )
3. ( x-- ) = ( x-=1 ) = ( x = x-1 )
package class2;
import java.io.*;
class Class2
{
public static void main(String args[])
{
for(int x = 0; x<10; x++)
{
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.
2. An identifier may be any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore and dollar-sign
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.
4. Again, Java is case-sensitive, so VALUE is a different identifier than Value.
examples of valid identifiers are
AvgTemp count a4 $test this_is_ok
Invalid identifier names include these:
2count high-temp & Not/ok
Separators
Symbol Name Purpose
( ) Parentheses
Used to contain lists of parameters in method definition and invocation.
Also used for defining precedencein expressions, containing expressions in
control statements, and surrounding cast types.
{ } Curly Braces
Used to contain the values of automatically initialized arrays. Also used to
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.
, Comma
Separates consecutive identifiers in a variable declaration. Also used to chain
statements together ins000ide a for statement.
. Period
Used to separatepackage names from subpackages and classes. Also used to
separatea variable or method from a referencevariable.
:: Colons
Used to create a method or constructorreference.(Added byJDK
8.)
52
The Java Keywords
There are 50 keywords currently defined in the
Java language. These keywords, combined with
the syntax of the operators and separators, form
the foundation
abstract continue for new switch
assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
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
{
public static void main(String args[])
{
boolean a = true, b = false;
System.out.println("a = "+ a);
System.out.println("b = "+ b);
}
}
class ex1
{
public static void main(String args[])
{
int a = 10, b = 15;
System.out.println("(a > b) = "+ (a > b));
boolean c = (a < 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
Integer Data Type :
1. Integer Data Type is used to store integer value.
2. Integer Data Type is Primitive Data Type in Java Programming Language.
3. Integer Data Type have respective Wrapper Class – “Integer“.
4. Integer Data Type is able to store both unsigned ans signed integer values so
Java opted signed, unsigned concept of C/C++.
Class IntDemo
{
public static void main(String args[])
{
int number=0;
System.out.println("Total Number : " + number);
}
}
Explanation :
1. Primitive Variable can be declared using “int” keyword.
2. Though Integer contain default Initial Value as 0 , still we
have assign 0 to show
assignment in Java.
3. “+” operator is used to concatenate 2 strings.
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.*;
class ex1
{
public static void main(String args[])
{
DataInputStream in = new DataInputStream(System.in);
char ch;
try{
System.out.print("Enter a character : ");
ch = (char) System.in.read();
System.out.println("You have entered : "+ ch);
}
catch (Exception e){}
}
}
import java.io.*;
class ex1{
public static void main(String[] args){
try{
InputStreamReader IN = new InputStreamReader(System.in);
BufferedReader BR = new BufferedReader(IN);
String s = BR.readLine();
System.out.println(s);
}
catch(Exception E){}
}
}
import java.io.*;
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 age : ");
String s = BR.readLine();
int age = Integer.parseInt(s);
System.out.println("Your age is : " + age);
}
catch(Exception E){}
}
}
Type conversion
String s = BR.readLine();
int age = Integer.parseInt(s);
String s = BR.readLine();
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;
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 how many fibonacci numbers : ");
String s = BR.readLine();
int input = Integer.parseInt(s);
int f0 = 0, f1 = 1, f2;
for (int i = 0; i<input; i++){
f2 = f0 + f1;
System.out.print(f2 + " " );
f0 = f1;
f1 = f2;
}
}
catch (Exception E){}
}
}
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 how many fibonacci numbers :
");
String s = BR.readLine();
int input = Integer.parseInt(s);
int f0 = 0, f1 = 1, f2;
System.out.print("0 1 " );
for (int i = 0; i<input-2; i++){
f2 = f0 + f1;
System.out.print(f2 + " " );
f0 = f1;
f1 = f2;
}
}
catch (Exception E){}
}
}
int f0 = 0, f1 = 1, f2;
System.out.print("0 " );
for (int i = 0; i<input-1; i++){
f2 = f0 + f1;
System.out.print(f2 + " " );
f1 = f0;
f0 = f2;
}
Prime numbers
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
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 series of prime number up to : ");
String s = BR.readLine();
int input = Integer.parseInt(s);
int i = 0, j = 0;
for (i = 2; i<input; i++, j++){
for(j = 2; j<i; j++){
if(i % j == 0){
break;
}
}
if (i == j){
System.out.print(i);
}
}
}
catch (Exception E){}
}
}
import java.util.*;
class Mainthread
{
public static void main(String[] args)
{
try
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter series of prime number up to : ");
int input = sc.nextInt();
int i = 0, j = 0;
for (i = 2; i<input; i++, j++)
{
for(j = 2; j<i; j++)
{
if(i % j == 0)
break;
}
if (i == j)
System.out.print(i+" ");
}
}
catch (Exception E){}
}
59
}
Nested loop
System.out.print("Enter number up to : ");
String s = BR.readLine();
int input = Integer.parseInt(s);
int i, j;
for (i = 1 ; i<=input; i++){
for (j = 1; j<=i; j++){
System.out.print(j);
}
System.out.print("n");
}
System.out.print("Enter number least to : ");
String s = BR.readLine();
int input = Integer.parseInt(s);
int i, j;
for (i = 1 ; i<=input; i++){
for (j = 1; j<=input; j++){
System.out.print(j);
}
System.out.print("n");
}
System.out.print("Enter number least to : ");
String s = BR.readLine();
int input = Integer.parseInt(s);
int i, j;
for (i = 1 ; i<=input; i++){
for (j = input; j>=i; j--){
System.out.print(j + " ");
}
System.out.print("n");
}
System.out.print("Enter number least to : ");
String s = BR.readLine();
int input = Integer.parseInt(s);
int i, j;
for (i = input ; i>=1; i--){
for (j = 1; j<=i; j++){
System.out.print(j + " ");
}
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;
for (int i = 0; i<=4; i++){
total = total + array[i];
}
System.out.println(total);
int marks[] = {40, 55, 69, 89, 78};
for (int i = 0; i<5; i++){
System.out.print("marks[" + i + "] = " + marks[i]);
System.out.print("n");
}
Value assigning while program processing
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);
int array[] = new int[5];
int total = 0;
System.out.println("Enter 5 of your Numbers to Sum : ");
for(int i =0; i<=4; i++){
String s = BR.readLine();
int input = Integer.parseInt(s);
array[i] = input;
}
for (int i = 0; i<=4; i++){
total = total + array[i];
}
System.out.println("Total = "+total);
}
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("Enter Marks ["+ i +"] = ");
String s2 = BR.readLine();
Marks[i] = Float.parseFloat(s2);
}
for (int i=0; i<5; i++){
System.out.println("Roll ["+ i +"] = " + Roll[i]);
System.out.println("Marks["+ i +"] = " + Marks[i]);
}
}
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("Enter Marks ["+ i +"] = ");
String s2 = BR.readLine();
Marks[i] = Float.parseFloat(s2);
}
for (int i=0; i<5; i++){
System.out.println("Roll ["+ i +"] = " + Roll[i]);
System.out.println("Marks["+ i +"] = " + Marks[i]);
}
}
catch (Exception E){
System.out.println("Error in inpuit. Program terminated .....");
System.exit(0);
}
}
}
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{
public static void main(String [] args){
String first_name = new String("Md. Saifur");
StringBuffer last_name = new StringBuffer(" Rahman");
System.out.println(first_name + last_name);
}
}
class ex1{
public static void main(String [] args){
String first_name = new String("Md. Saifur ");
String full_name = first_name + "Rahman";
System.out.println(full_name);
}
}
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet
Java cheat sheet

More Related Content

What's hot

Java programming basics
Java programming basicsJava programming basics
Java programming basicsHamid Ghorbani
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHPLorna Mitchell
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Sagar Verma
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.Tarunsingh198
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonSujith Kumar
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with JavaJussi Pohjolainen
 
Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceOUM SAOKOSAL
 
Lecture - 1 introduction to java
Lecture - 1 introduction to javaLecture - 1 introduction to java
Lecture - 1 introduction to javamanish kumar
 
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Ayes Chinmay
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Sagar Verma
 

What's hot (20)

Java Notes
Java Notes Java Notes
Java Notes
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
Java Programming - 05 access control in java
Java Programming - 05 access control in javaJava Programming - 05 access control in java
Java Programming - 05 access control in java
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
Java API, Exceptions and IO
Java API, Exceptions and IOJava API, Exceptions and IO
Java API, Exceptions and IO
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - Inheritance
 
Lecture - 1 introduction to java
Lecture - 1 introduction to javaLecture - 1 introduction to java
Lecture - 1 introduction to java
 
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
 

Viewers also liked

PostgreSQL Streaming Replication Cheatsheet
PostgreSQL Streaming Replication CheatsheetPostgreSQL Streaming Replication Cheatsheet
PostgreSQL Streaming Replication CheatsheetAlexey Lesovsky
 
Java for android developers
Java for android developersJava for android developers
Java for android developersAly Abdelkareem
 
Android for Java Developers
Android for Java DevelopersAndroid for Java Developers
Android for Java DevelopersMarko Gargenta
 
TEDx Manchester: AI & The Future of Work
TEDx Manchester: AI & The Future of WorkTEDx Manchester: AI & The Future of Work
TEDx Manchester: AI & The Future of WorkVolker Hirsch
 

Viewers also liked (9)

Java cheat sheet
Java cheat sheetJava cheat sheet
Java cheat sheet
 
Cheat Sheet java
Cheat Sheet javaCheat Sheet java
Cheat Sheet java
 
MySQL Cheat Sheet
MySQL Cheat SheetMySQL Cheat Sheet
MySQL Cheat Sheet
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 
PostgreSQL Streaming Replication Cheatsheet
PostgreSQL Streaming Replication CheatsheetPostgreSQL Streaming Replication Cheatsheet
PostgreSQL Streaming Replication Cheatsheet
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java for android developers
Java for android developersJava for android developers
Java for android developers
 
Android for Java Developers
Android for Java DevelopersAndroid for Java Developers
Android for Java Developers
 
TEDx Manchester: AI & The Future of Work
TEDx Manchester: AI & The Future of WorkTEDx Manchester: AI & The Future of Work
TEDx Manchester: AI & The Future of Work
 

Similar to Java cheat sheet

Similar to Java cheat sheet (20)

java basic for begginers
java basic for begginersjava basic for begginers
java basic for begginers
 
Annotation Processing in Android
Annotation Processing in AndroidAnnotation Processing in Android
Annotation Processing in Android
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz
 
Java lab zero lecture
Java  lab  zero lectureJava  lab  zero lecture
Java lab zero lecture
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 
Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
 
Introduction
IntroductionIntroduction
Introduction
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPREC
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Java IO
Java IOJava IO
Java IO
 
Fundamentals of oop lecture 2
Fundamentals of oop lecture 2Fundamentals of oop lecture 2
Fundamentals of oop lecture 2
 
Presentation5
Presentation5Presentation5
Presentation5
 
OOP-Chap2.docx
OOP-Chap2.docxOOP-Chap2.docx
OOP-Chap2.docx
 
CORE JAVA
CORE JAVACORE JAVA
CORE JAVA
 
java traning report_Summer.docx
java traning report_Summer.docxjava traning report_Summer.docx
java traning report_Summer.docx
 
Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software Development
 
1_JavIntro
1_JavIntro1_JavIntro
1_JavIntro
 
Professional-core-java-training
Professional-core-java-trainingProfessional-core-java-training
Professional-core-java-training
 
4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf
 

Recently uploaded

Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 

Recently uploaded (20)

Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 

Java cheat sheet

  • 1. Java Programming Language Md. Saifur Rahman Java Programming Basic Concept
  • 2. 1 Java TABLE OF CONTENTS Chapter Search Topic CHAPTER 1 ............................................................................. # SECTION 1.1 ...........................................................................................# Subsection 1.1.a ...............................................................................# Subsection 1.1.b ...............................................................................# Subsection 1.1.c................................................................................# SECTION 1.2 ...........................................................................................# SECTION 1.3 ...........................................................................................# CHAPTER 2 ............................................................................. # SECTION 2.1 ...........................................................................................# SECTION 2.2 ...........................................................................................# Subsection 2.2.a ...............................................................................# Subsection 2.2.b ...............................................................................# Subsection 2.2.c................................................................................# SECTION 2.3 ...........................................................................................# CHAPTER 3 ............................................................................. # SECTION 3.1 ...........................................................................................# SECTION 3.2 ...........................................................................................# SECTION 3.3 ...........................................................................................# 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.....................................................................................# CHAPTER 3 ............................................................................. # SECTION 3.1 ...........................................................................................# SECTION 3.2 ...........................................................................................# SECTION 3.3 ...........................................................................................# Subsection 3.3.a ...............................................................................# Subsection 3.3.b ...............................................................................# Subsection 3.3.c.....................................................................................# UseCtrl+F STRING TOPIC Complex programs FILE I/O TOPIC THREAD TOPIC CLASS TOPIC INHERITANCE TOPIC CONSTRUCTOR TOPIC OBJECTTOPIC METHODTOPIC POLYMORPHISM TOPIC EXCEPTION TOPIC ENCAPSULATION TOPIC PACKAGES, INHERITANCEANDINTERFACES TOOPIC STATIC KEYWORDTOPIC ABSTRACT KEYWORD TOPIC Link Web resource tutorials http://www.c4learn.com/javaprogramming/ http://www.programmingsimplified.com/java/source-code/java- 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 code Color sample RGB Color code Color sample 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 6+
  • 3. 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
  • 4. 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
  • 5. 4 To compile javac Welcome.java To execute 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
  • 6. 5 (9/29/2014) tools NetBeans ide 8.1 link https://netbeans.org/downloads/ books java the complete reference 9th edition herbert schildt Filecreate File > new Project> java > java Application > projectname + projectlocation > finish Javaprogramworks Few littleconcepts 1. Function = method 2. Add = class name (With starting capital letter) 3. add() = Method (With starting lower case) 4. In java main() is not mandatory but not execute 5. In business wecan give class file not sourcefile but class file can convertinto Sourcecode C Java include import Object 1. Object = set of attributes = like structure OOP must have3 things 1. Encapsulation ( লুকিয়ে রাখা ) 2. Polymorphism( বহুরূপতা) 3. Inheritance( উত্তরাকিিার) Class 1. Domain 2. Idea 3. Environment 4. For object we need an environment that’s why we use class  Suppose messi is the best player. But he cannot play in banani park. He must need an good field or environment where he can play football. Messi = object Environment = class 5. User defined data-type 6. Set of objects  Fruit is a class then object = (mango , jackfruit, banana, etc) Declaration class className { member variable declaration; member fuction defination; } Classnaming conventions/rules 1. Name starts with a uppercase 2. Main class name = file name First program package class2; import java.io.*; class Class2 { public static void main(String args[]) { System.out.println("Hello world"); } } package class2; import java.io.*; public class Method_overloading1 { public static void main(String args[]) { int num = 7; if(num % 2 == 0) { System.out.println("Even"); } else { System.out.println("Odd"); } 1. program begins with a call to main() method. 2. In main( ), there is only one parameter, albeit a complicated one. String args[ ] declares a parameter named args, which is an array of instances of the class String. (Arrays are collections of similar objects.) 3. Output is actually accomplished by the built-in println( ) method & displays the string which is passed to it. & println( ) can be used to display other types of information, too. The line begins with System.out, System is a predefined class that provides access to the system, and out is the output stream that is connected to the console. 4. All statements in Java end with a semicolon. 5. Class Member Member Variable Member Function
  • 7. 6 } } Programprocess 1. Comments // This is a single line comment /* This is a Multiline comment */ Lecture 3 (Wednesday, October 01, 2014) packageclass3; import java.util.Scanner; public class Input { public static void main(String args[]) { System.out.print("Enterta 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 packageclass3; import java.util.Scanner; public class OddEvenCheckWithFuncCall { int oddeven(int input) { if(input %2 == 0) { System.out.println(input+" is even..."); } else System.out.println(input+" is odd "); Process one packageclass3; import java.util.Scanner; class OddEvenCheck { int oddeven(int input) { if(input %2 == 0) { System.out.println(input+" is even..."); } else System.out.println(input+" is odd "); return 0; } Process two packageclass3; import java.util.Scanner; class OddEvenCheck { int oddeven(int input) { if(input %2 == 0) return 1; else return 0; } } public class OddEvenCheckWithFuncCall Output Low Run Execute Interprete Starts from main() High 1. Compile 2. Convert machine code to electric signal
  • 8. 7 return 0; } public static void main(String args[]) { System.out.print("Enterta number to check odd/even = "); Scanner sc = new Scanner(System.in); int input = sc.nextInt(); oddeven(input); non-static method oddeven(int) cannot be referenced from a static context so this cannot run in java but c can compile it } } } public class OddEvenCheckWithFuncCall { public static void main(String args[]) { System.out.print("Enterta number to check odd/even = "); Scanner sc = new Scanner(System.in); int input = sc.nextInt(); OddEvenCheck oec = new OddEvenCheck(); oec.oddeven(input); } } { public static void main(String args[]) { System.out.print("Enterta number to check odd/even = "); Scanner sc = new Scanner(System.in); int input = sc.nextInt(); OddEvenCheck oec = new OddEvenCheck(); int out = oec.oddeven(input); if(out == 1) System.out.println(input+" is even number"); else System.out.println(input+" is odd number"); } } Introduction to Java Applications { = an opening left brace } = the closing right brace C T 
  • 9. 8 Complex programs packageclass3; import java.util.Scanner; public class OddEvenCheckWithFuncCall { public static void main(String args[]) { System.out.print("Enter a number to make a pyramid = "); Scanner sc = new Scanner(System.in); int input = sc.nextInt(); for(intr = 0; r<input; r++) { for(intc = 0; c< input-r-1; c++) System.out.print("t"); for(intc = 0; c<=r*2; c++) System.out.print("*" +"t"); System.out.println(); } } } packageclass2; class Class2 { public static void main(String args[]) { for(intr = 0; r<3; r++) { int p = r; for(intc = 0; c<6; c++) { ++p; System.out.print(p +" "); } System.out.println(); } } } packageclass2; import java.util.Scanner; public class Class2 { public static void main(String args[]) { System.out.print("Enter a number to make a half pyramid = "); Scanner sc = new Scanner(System.in); int input = sc.nextInt(); for(intr = 1; r<=input; r++) { for(intc = input-1; c>=r; c--) System.out.print("t"); for(intc = 1; c<=r; c++) System.out.print("*t"); System.out.println(); } } } package personal; import java.util.Scanner; public class b { public static void main(String args[]) { int i; int pos=0; int neg=0; System.out.print("Enter the value of input : "); Scanner sc = new Scanner(System.in); int input = sc.nextInt(); int a[] = new int[input]; for(i=0; i<input; i++) { a[i] = sc.nextInt(); if(a[i]>0) { pos=pos+1; } else if(a[i]<0) { neg=neg+1; } } System.out.println("Pos = " + pos); System.out.println("Neg = " + neg); } } Entert a number to make a piramid = 3 * * * * * * * * * 1 2 3 4 5 6 2 3 4 5 6 7 3 4 5 6 7 8 Enter a number to make a half pyramid = 3 * * * * * * Enter the value of input : 4 1 2 3 -4 Pos = 3 Neg = 1 package personal; public class ConstructorCallingExplain { public static void main(String args[]) { int f0=0; int f1 = 1, f2; System.out.print("0 1 "); for (int i=0; i<=10; i++) { f2 = f0+f1; System.out.print(f2 + " "); f0 = f1; f1 = f2; } } } import java.util.Scanner; public class Caller { public static void main(String args[]) { System.out.print("Enter the number of elements in array = "); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a[] = new int[n]; int maximum, i, location; maximum = 0; location = 0; mport java.util.*; class PrimeNumbers { public static void main(String args[]) { int n, status = 1, num = 3; Scanner in = new Scanner(System.in); System.out.println("Enter the number of prime numbers you want"); n = in.nextInt(); if (n >= 1) { System.out.println("First "+n+" prime numbers are :- "); System.out.println(2); } for ( int count = 2 ; count <=n ; ) { for ( int j = 2 ; j <= Math.sqrt(num) ; j++ ) { if ( num%j == 0 ) { status = 0; break; } } http://java67.blogspot.com/2014/01/how-to-check-if-given-number-is- prime.html http://www.programmingsimplified.com/java/source-code/java-program- print-prime-numbers http://beginnersbook.com/2014/01/java-program-to-display-prime- numbers/
  • 10. 9 System.out.print("Enter " + n +" integers = "); for (i = 0; i < n; i++) a[i] = sc.nextInt(); 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); } } if ( status != 0 ) { System.out.println(num); count++; } status = 1; num++; } } } 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
  • 11. 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 classMyClass { // field,constructor,and // methoddeclarations } class classname { type instance-variable1; type instance-variable2; // ... type instance-variableN; type methodname1(parameter-list) { // bodyof method } type methodname2(parameter-list) { // bodyof method } // ... type methodnameN(parameter-list) { // bodyof method } } 1. The data, or variables, defined within a class are called instance variables. 2. A class declaration only creates a template; it does not create an actual object. 3. A class creates a new data type that can be used to create objects. That is, a class creates a logical frameworkthat defines the relationship between its members. When you declare an object of a class, 4. You are creating an instance of that class. Thus, a class is a logical construct. An object has physical reality. (That is, an object occupies space in memory.) 4. Here is a class called Box that defines three instance variables: width, height, and depth. classBox { doublewidth; doubleheight; doubledepth; } 5. To actually create a Box object, you will use a statement like the following: Box mybox = newBox(); // createa Box object called mybox ***After this statement executes, mybox will be an instance of Box 1. each time you create an instance of a class, you arecreating an object that contains its own copy of each instance variable defined by the class. 2. Thus, every 3. Box object will contain its own copies of the instance variables width, height, and depth. To 4. access these variables, you will use the dot (.) operator. The dot operator links the name of 5. the object with the name of an instance variable. For example, to assign the width variable of mybox the value 100, you would use the following statement: mybox.width = 100; classBox { double width; double height; double depth; } classClass2 { publicstaticvoidmain(Stringargs[]) { Box myBox = newBox(); } } Class 1. Domain 2. Idea 3. Environment 4. For object we need an environment that’s why we use class  Suppose messi is the best player. But he cannot play in banani park. He must need an good field or environment where he can play football. Messi = object Environment = class 5. User defined data-type 6. Set of objects 7. when we create a class, weare creating a new data type 8. a blueprint of an object 9. a template 10.an environmentto create an object 11.  Fruit is a class then object = (mango , jackfruit, banana, etc)
  • 12. 11 Declaration class className { member variable declaration; member fuction defination; } Thus in short Class have - 1. Class name 2. Properties or Attributes 3. Common Functions 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. class classname { type instance-variable1; type instance-variable2; // ... type instance-variableN; type methodname1(parameter-list) { // body of method } type methodname2(parameter-list) { // body of method } // ... type methodnameN(parameter-list) { // body of method } } Explanation Of Syntax : Class name class classname { 1. class is Keyword in Java used to create class in java. 2. classname is Name of the User defined Class. Class Instance Variable type instance-variable1; type instance-variable2; // ... type instance-variableN; 1. Instance Variables are Class Variables of the class. 2. When a number of objects are created for the same class, the same copy of instance variable is provided to all. 3. Instance variables have different value for different objects. 4. Access Specifiers can be applied to instance variable i.e public,private. 5. Instance Variable are also called as “Fields“ Inheritance Topic  http://www.studytonight.com/java/inheritance-in-java.php 1. Inheritproperty of another class 2. a class to inherit property of another class 3. class Vehicle { ...... } class Car extends Vehicle { ....... //extends the property of vehicle class. }  Vehicle is super class of Car.  Car is sub class of Vehicle.  Car IS-A Vehicle. Pictures Class's Members Member instance Variable Member instance methods/Function Object of another class which is declared in current class
  • 13. 12 Example package encapsulation.pack1; import encapsulation.pack2.Add; public class Caller extends Add { public static void main(String args[]) { // Add obj = new Add(); Caller obj = new Caller(); System.out.println(obj.x); System.out.println(obj.y); } } package encapsulation.pack2; public class Add { public int x = 10; private int y =20; public int show() { return x+y; } } 10 Exception in thread "main" java.lang.RuntimeException: Uncompilable sourcecode - 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/  - Inheritance Single Inheritance Multilevel Inheritance Heirarchical Inheritance
  • 14. 13 package personal; class Vehicle { void method() { System.out.println("class Vehicle is showing"); } } class Car extends Vehicle { void method() { System.out.println("class Car is showing"); } } class Gear extends Car { void method() { System.out.println("class Gear is showing"); } } public class constructor { public static void main(String args[]) { Gear obj = new Gear(); obj.method(); } } package personal; class Vehicle { void method() { System.out.println("class Vehicle is showing"); } } class Car extends Vehicle { void method() { System.out.println("class Car is showing"); } } class Gear extends Vehicle { void method() { System.out.println("class Gear is showing"); } } public class constructor { public static void main(String args[]) { Gear obj = new Gear(); 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; Classname() //constructor { a = 10; b = 20; } } public class constructor { public static void main(String args[]) { Classname obj = new Classname(); // an obj creation System.out.println(obj.a + obj.b); } } package personal; class ClassName // a class definition { int a; int b; ClassName() //constructor { a = 10; b = 20; } int classmethod() { a = 30; b = 40; return 0; // or void } } public class constructor { public static void main(String args[]) { ClassName obj = new ClassName(); // an obj creation System.out.println(obj.a + obj.b); obj.classmethod(); System.out.println(obj.a + obj.b); } } package personal; class Const { int length, width; Const(int len, int wid) { length = len; width = wid; } } public class constructor { public static void main(String args[]) { Const obj = new Const(10, 20); System.out.println("length "+ obj.length); } } Constructors : Initializing an Class Object in Java Programming 1. Objects contain there own copy of Instance Variables. 2. It is very difficult to initialize eachand every instance variable of each and every object of Class. 3. Java allows objects to initialize themselves when they are created. Automatic initialization is performed through the use of a constructor. 4. A Constructor initializes an object as soonas object gets created. 5. Constructorgets calledautomatically after creationof objectand before completion of new Operator. Some Rules of Using Constructor : 1. ConstructorInitializes an Object. 2. Constructorcannotbe calledlike methods. 3. Constructors are calledautomatically as soonas object gets created. 4. Constructordon't have any return Type. (even Void) 5. Constructorname is same as that of "Class Name". 6. Constructorcan acceptparameter. Live Example : How Constructor Works ? class Rectangle { int length; int breadth; Rectangle() { length = 20; breadth = 10; } } class RectangleDemo { 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); Vehicle Car Gear Showing Vehicle Car Gear Showing
  • 15. 14 } } Explanation : 1. new Operator will create an object. 2. As soon as Object gets created it will call Constructor- Rectangle() //This is Constructor { length = 20; breadth = 10; } 3. In the above Constructor Instance Variables of Object r1 gets their own values. 4. Thus Constructor Initializes an Object as soon as after creation. 5. It will print Values initialized by Constructor - System.out.println("Length of Rectangle : " + r1.length); System.out.println("Breadth of Rectangle : " + r1.breadth); class Rectangle { int length; int breadth; Rectangle() { length = 20; breadth = 10; } void setDiamentions() { length = 40; breadth = 20; } } class RectangleDemo { 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); r1.setDiamentions(); System.out.println("Length of Rectangle : " + r1.length); System.out.println("Breadth of Rectangle : " + r1.breadth); } } Explanation : 1. After the Creation of Object , Instance Variables have their own values inside. 2. As soon as we call method , values are re-initialized. ParameterizedConstructors: ConstructorTakingParameters 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". 2. Argument can be of any type i.e Integer,Character,Array or any Object. 3. Constructor can take any numberof Argument. Live Example : Constructor Taking Parameter in Java Programming class Rectangle { int length; int breadth; Rectangle(int len,int bre) { length = len; breadth = bre; } } class RectangleDemo { public static void main(String args[]) { Rectangle r1 = new Rectangle(20,10); System.out.println("Length of Rectangle : " + r1.length); System.out.println("Breadth of Rectangle : " + r1.breadth); } } Explanation: Carefully observe above program You will found something like this Rectangle r1 = new Rectangle(20,10); This is Parameterized Constructor taking argument.These arguments are used for any purpose inside Constructor Body.  New Operator is used to Create Object.  We are passing Parameter to Constructor as 20,10.  These parameters are assigned to Instance Variables of the Class.  We can Write above statement like - Rectangle(int length,int breadth) { length = length; breadth = breadth; } OR Rectangle(int length,int breadth) { this.length = length; this.breadth = breadth; } But if we use Parameter name same as Instance variable then compiler will recognize instance variable and Parameter but user or programmer may confuse. Thus we have used "this keyword" to specify that "Variable is Instance Variable of Object r1". Methodoverloading (exampleofpolymorphism) 1. http://www.beingjavaguys.com/2013/10/method-overloading-in-java.html “Overloading injava occurs when methods in a same class or in childclasses shares a same name witha ‘difference innumber of arguments’ or ‘difference inargument type’ or both.” 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. 1) Have different number of arguments. 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(intempId){ 2. ...... 3. } 4. 5. public void getEmpName(String empName){ 6. ...... 7. } 2. Method Overloadingoccurs when methods are having same name, but 3. A difference in the number of their parameters or type of their parameters or both.
  • 16. 15 8. 9. public void getEmpName(intempId,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; public class constructor { public constructor() { System.out.println("Constructor auto called at the time of initializing object"); } public static void main(String args[]) { constructor obj = new constructor(); //auto called } } package personal; class Student { String name; int roll; float mark; Student() { name = "Md. Saifur Rahman"; roll = 67; mark = 70; } } public class ConstructorCallingExplain { public static void main(String args[]) { Student obj = new Student(); System.out.println(obj.name); System.out.println(obj.roll); System.out.println(obj.mark); } } package personal; class Student { String name; int roll; float mark; Student(String name, int roll, float mark) { this.name = name; this.roll = roll; this.mark = mark; } } public class ConstructorCallingExplain { public static void main(String args[]) { Student obj1 = new Student("saifur", 67, 70.0f); Student obj2 = new Student("rasel", 58, 75.5f); System.out.println(obj1.name); System.out.println(obj1.roll); System.out.println(obj1.mark); System.out.println(obj2.name); System.out.println(obj2.roll); System.out.println(obj2.mark); } } Object Topic 1. http://docs.oracle.com/javase/tutorial/java/concepts/object.html 2. 1. Object = set of attributes = like structure 2. Objects havestates and behaviors. Example: A dog has states - color, name, breed as well as behaviors -wagging, barking, eating. An objectis an instance of a class. 3. Softwareobjects also have a state and behavior. A softwareobject's state is stored in fields and behavior is shown via methods. 4. In softwaredevelopment, methods operate on the internal state of an objectand the object-to- object communication is done via methods. 5. A class provides the blueprints for objects. So basically an objectis created froma class Creating an Object: There are three steps when creating an object froma class: Declaration: A variable declaration with a variablename with an objecttype. 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); Constructor Defaultor argumentless Argumented Copy
  • 17. 16 Rectangle rectOne = new Rectangle(originOne, 100, 200); Rectangle rectTwo = new Rectangle(50, 100); 1. We create an object to create a reference 2. To access class’s members 3. 1. Suppose a gentleman wants to marry a woman who has 3 childs. He wants to take care of them too. 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 4. So, to make the childs as his own he has to marry that woman 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 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, child3. 2. It is important to understand that changes to the instance variables of one object have no effect on the instance variables of another. package class3; class Woman { int child1; int child2; int child3; } public class classObj { public static void main(String args[]) { Woman man1 = new Woman(); man1.child1 = 10; man1.child2 = 12; man1.child3 = 15; Woman man2 = new Woman(); man2.child1 = 5; man2.child2 = 6; man2.child3 = 7; System.out.println("Age of the child1 = " + man1.child1); System.out.println("Age of the child1 = " + man2.child1); } } package class3; //creating a class class Woman { int child1; int child2; int child3; } public class classObj { public static void main(String args[]) { //obj creation //className obj; // declare //man is a reference to an object of type Box. man does not yet refer to an actual object. The next line allocates an object and assigns a reference to it to woman. After the second line executes, you can use woman as if it were a //man object. But in reality, woman simply holds, in essence, the memory address of the actual man object. //obj = new className(); //initialize //or, className obj = new className() Woman man= new Woman(); //accessing the members of the woman class // & 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;
  • 18. 17 Assigning Object Reference Variables Box b1 = new Box(); Box b2 = b1; 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. 3. However, this would be wrong. Instead, after this fragment executes, b1 and b2 will both refer to the same object. The assignment of b1 to b2 did not allocate any memory or copy any part of the original 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; class Rectangle // a class definition { int length; int width; Rectangle(int l, int b) //constructor { length = l; width = b; } void area(Rectangle obj) { System.out.println("Area = " + (obj.length * obj.width)); } } public class constructor { public static void main(String args[]) { Rectangle obj = new Rectangle(20, 8); // an obj creation obj.area(obj); } } package personal; class Rectangle // a class definition { int length; int width; Rectangle(int l, int b) //constructor { length = l; width = b; } void rect (int length, int width) { System.out.println("area = " + (length*width)); } } public class constructor { public static void main(String args[]) { Rectangle obj = new Rectangle(10, 5); obj.rect(obj.length, obj.width); } } Object as method’s argument
  • 19. 18 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 Vehicle Call by Value Call by reference
  • 20. 19 Polymorphism Topic http://beginnersbook.com/2013/03/polymorphism-in-java/ Difference between Overloading & overriding Method Overloading Method Overriding 1. http://www.programmerinterview.com/index.php/java-questions/method-overriding-vs-overloading/ 2. 1. 1. Method overloading in Java occurs when two or more methods in the sameclass have the exact samename but different parameters (remember that method parameters accept values passed into the method). 2. The conditions for method overloading o The number of parameters is different for the methods. o The parameter types are different (like changing a parameter that was a float to an int). 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 samemethod name, return type, number of parameters, and types of parameters as the method in the parent class, and the only difference would be the definition of the method.( overriding amethodeverything remains exactly the same except the methoddefinition) 2. overriding is a run time phenomenon – not a compile time phenomenon like method overloading 3. overloading is static polymorphismwhereas overriding is dynamic polymorphism 4. Argumentlist should be different while doing method overloading. Argumentlist should be same in method Overriding. 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 fastas compareto Overridden method in Java. 8.  Overloadingisthe situationthattwoor more methodsinthe same classhave the same name butdifferentarguments.  Overridingmeanshavingtwomethodswiththe same methodname andarguments(i.e.,methodsignature).One of themisinthe Parentclassand the otherisin the Childclass. Overloading Happening within the same class. Method signature should not be same. It happen at time of compliance or we can say overloading is the early binding or static binding. Method can have any return type. Method can have any access level. Overriding Happening between super class and sub class. Method signature should be same. It happen on time of run time or we can say overriding is dynamic binding or let binding. Method return type must be same as super class method Method must have same or wide access level than super class method access level. Polymorphism Method Overloading Method Overriding
  • 21. 20 package personal; class InA { void method(int l) { System.out.println("Method overloaded in 1"); } void method(float b) { System.out.println("Method overloaded in 2"); } } public class constructor { public static void main(String args[]) { InA obj = new InA(); obj.method(4); } } package personal; class Parent { void method() { System.out.println("Parent is showing"); } } class Child extends Parent { void method() { System.out.println("Child is showing"); } } public class constructor { public static void main(String args[]) { Child obj = new Child(); obj.method(); } } package personal; public class constructor { public static void main(String args[]) { b obj = new b(); obj.method(); } } package personal; class a { void method() { System.out.println("Parent a is showing"); } } package personal; class b extends a { void method() { System.out.println("Child b is showing"); } } Child b is showing Method overriding  is the basis for polymorphism  only applicable in methods  overriding is only applicable for the classes related to each other through inheritance  only between super classes & subclasses   To override the functionality of an existing method.  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:  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 superclass.  The access level cannot be more restrictive than the overridden method's access level. For example: if the superclass method is declared public then the overridding method in the sub class cannot be either private or protected. Instance methods can be overriddenonly if they are inherited by the subclass. RulesforMethodOverriding : 1. Method Must have Same Name as that of Method Declared in Parent Class 2. Method Must have Same Parameter List as that of Method Declared in Parent Class 3. IS-A relation should be maintained in order to Override Method.
  • 22. 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 ; public class Caller{ public static void main(String args[]){ Animal a = new Animal(); // Animal referenceand object Animal b = new Dog(); // Animal reference but Dog object a.move();//runs the method in Animal class b.move();//Runs the method in Dog class } } package overriding ; class Animal{ public void move(){ System.out.println("Animals can move"); } } In compile time, the check is made on the referencetype. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object. Therefore, in the above example, the programwill compile properly since Animal class has the method move. Then, at the runtime, it runs the method specific for that object. class Animal{ public void move(){ System.out.println("Animals can move"); } } class Dog extends Animal{ public void move(){ super.move(); // invokes the super class method System.out.println("Dogs can walk and run"); } } public class TestDog{ public static void main(String args[]){ Animal b = new Dog(); // Animal reference but Dog object b.move(); //Runs the method in Dog class } } package overriding ; class Dog extends Animal{ public void move(){ System.out.println("Dogscan walk and run"); } } run: Animals can move Dogs can walk and run BUILD SUCCESSFUL (total time: 0 seconds)  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 Animals can move Dogs can walk and run package com.c4learn.inheritance; public class Vehicle { public void vehicleMethod() { System.out.println("Method in Vehicle."); } } package com.c4learn.inheritance; public class TwoWheeler extends Vehicle { public void vehicleMethod() { System.out.println("Method" + " in TwoWheeler."); } public static void main(String[] args) { TwoWheeler myBike = new TwoWheeler(); Vehicle myVehicle = new Vehicle(); myVehicle.vehicleMethod(); myBike.vehicleMethod(); } } package encapsulation; publicclassInheritanceRulesextendsbaseClass{ publicintcalculate(intnum1,intnum2) { returnnum1+num2; } publicstaticvoidmain(String[] args) { baseClassb1= newbaseClass(); int result= b1.calculate(10,10); System.out.println("Result:" + result); } } package encapsulation; classbaseClass { publicintcalculate(intnum1,intnum2) { returnnum1*num2; } } Method in Vehicle. Method in TwoWheeler. run: Result: 100 BUILD SUCCESSFUL (total time:0 seconds)
  • 23. 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
  • 24. 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 monitorfor errors } catch(ExceptionType1exOb){ // exceptionhandler for ExceptionType1 } catch(ExceptionType2exOb){ // exceptionhandler for ExceptionType2 } // ... finally { // block of code to be executed after try block ends
  • 25. 24 } Rules Examples class Caller { public static void main(String args[]) { int d = 0; int a = 42 / d; System.out.println(a); System.out.println("Skipping notmaintained"); } } class Caller { public static void main(String args[]) { int d = 0; try { int a = 42 / d; System.out.println(a); } catch(Exception err1) { System.out.println("Skipping maintained & "+ err1); } } } run: Exception in thread "main" java.lang.ArithmeticException: / by zero at interfaces_4.pack1.Caller.main(Caller.java:7) Java Result: 1 run: Skipping maintained & java.lang.ArithmeticException: / by zero 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 programfrom automatically terminating.  Most users wouldbe confused(to say the least) if your program Opinion Classification
  • 26. 25 Loop Topic   Definitions 6. General forms Rules Examples packagesaifur; 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 arebetter 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'tcare....."); } } } Pictures
  • 30. 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    to hide the implementation details from users  Encapsulation is also known as “data Hiding”  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.  Provides abstraction between an object and its clients.  Protects an object from unwanted access by clients.  Example: A bank application forbids a client to change an Account's balance.  Encapsulation is a practice to bind related functionality (Methods) & Data (Variables) in a protective wrapper (Class) with required access modifiers (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 a process of wrapping of data and methods in a single unit is called encapsulation  Encapsulation is the mechanism of binding together the data and the code, so that they are not misused or accidentally modified.  Encapsulation is technique by which we can hide the data with in a class and provide public methods to manipulate the hide data.To achieve encapsulation we can declare variables private and provide public methods to manipulate these private variables.   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; import encapsulation.pack2.Add; public class Caller { public static void main(String args[]) { Add obj = new Add(); System.out.println("x+y = " + obj.show()); } } package encapsulation.pack2; public class Add { private int x = 10, y =20; public int show() { return x+y; } } x + y = 30
  • 31. 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.
  • 32. 31 Packages, Inheritance And Interfaces Toopic No Term Definition 1 Inheritance Inheritance is a process where one object acquires the properties of another object 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{ } public class FourWheeler extends Vehicle{ } public class TwoWheeler extends Vehicle{ 1. Vehicle is the superclass of TwoWheeler class. 2. Vehicle is the superclass of FourWheeler class. 3. TwoWheeler and FourWheeler are sub classes of Vehicle class. 4. WagonR is the subclass of both FourWheeler and Vehicle classes. IS-A relationship of above example is - TwoWheeler IS-A Vehicle FourWheeler IS-A Vehicle WagonR IS-A FourWheeler
  • 33. 32 } public class WagonR extends FourWheeler{ } publicclass Caller { publicstaticvoid main( String[] args ) { FourWheeler v1 = new FourWheeler(); TwoWheeler v2 = new TwoWheeler(); WagonR v3 = new WagonR(); System.out.println(v1instanceofVehicle); System.out.println(v2instanceofVehicle); System.out.println(v3instanceofVehicle); System.out.println(v3instanceofFourWheeler); } } publicclass Vehicle { } true true true true publicclass FourWheeler extends Vehicle { } publicclass TwoWheeler extends Vehicle { } publicclass WagonR extends FourWheeler { } Packages and Interfaces package interfaces_2.pack1; importinterfaces_2.pack2.Balance; publicclassCaller { publicstaticvoidmain(Stringargs[]) { Balance obj[] =newBalance[3]; obj[0] = newBalance("Saifur",100); obj[1] = newBalance("hasan",5000); obj[2] = newBalance("sazzad",100000); //obj[0].show(); //obj[1].show(); //obj[2].show(); for(inti = 0;i<3 ; i++) { obj[i].show(); } } } package interfaces_2.pack2; publicclassBalance { Stringname; floatbalance; publicBalance(Stringname,floatbalance) { this.name =name; this.balance =balance; } publicvoidshow() { if(balance<0) System.out.print("-->"); System.out.println(name +": $" + balance); } } 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 any constructors  You cannot instantiate an interface.  All of the methods in an interface are abstract.  An interface can extend multiple interfaces  An interface is not extended by a class; it is implemented by a class.  An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final  Methods in an interface are implicitly public.  Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.   using interface, you can specify what a class must do, but not how it does it  An interface in java is a blueprint of a class. It has static constants and abstract methods only.  It is used to achieve fully abstraction and multiple inheritance in Java.  Java Interface also represents IS-A relationship  It cannot be instantiated just like abstract class  We can create object for class but not for interface  All the members/fields inside the interface are public & abstract & static & final even if we do not declare them . It’s an automatic/default mechanism  Does not have any method implementation  If the class which implements the interface does not override the method, it should be marked abstract  Interface can extends any numbers of interfaces 
  • 34. 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 Whena class implementsaninterface,youcanthinkof the class as signinga contract, agreeingtoperformthe specificbehaviorsof the interface.If aclassdoes not performall the behaviorsof the interface,the classmustdeclare 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)
  • 35. 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 , hence it is declared as static. 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 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 In this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable, if it is incremented, it won't reflect to other objects. So each objects will have the value 1 in the count variable. Program of counter by static variable As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value. 1. class Counter2{ 2. static int count=0;//will get memory only once and retain its value
  • 36. 35 1. class Counter{ 2. int count=0;//will get memory when instance is created 3. 4. Counter(){ 5. count++; 6. System.out.println(count); 7. } 8. 9. public static void main(String args[]){ 10. 11. Counter c1=new Counter(); 12. Counter c2=new Counter(); 13. Counter c3=new Counter(); 14. 15. } 16. } Test it Now Output:1 1 1 3. 4. Counter2(){ 5. count++; 6. System.out.println(count); 7. } 8. 9. public static void main(String args[]){ 10. 11. Counter2 c1=new Counter2(); 12. Counter2 c2=new Counter2(); 13. Counter2 c3=new Counter2(); 14. 15. } 16. } Test it Now Output:1 2 3 class Caller { int a =5; public static void main(String args[]) { System.out.println(a); } } Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - non-static variable a cannot be referenced from a static context at Static.pack1.Caller.main(Caller.java:11) class Caller { static int a =5; public static void main(String args[]) { System.out.println(a); } } 5 package Static.pack1; import Static.pack2.Balance; class Caller { public static void main(String args[]) { Balance obj = new Balance(); System.out.println(obj.a); } } package Static.pack2; public class Balance { public static int a = 5; } package Static.pack1; import Static.pack2.Balance; class Caller { public static void main(String args[]) { System.out.println(Balance.a); } } package Static.pack2; public class Balance { public static int a = 5; } You can see that we can happily access the “a” instance variable in the “Balance” class without actually creating an object of type “Balance”. We can just use the “Balance” class directly. That’s because the variable is static, and hence belongs to the class, not any particular object of that class. The fact that we declared it public allows us to access it from other classes (Application in this case) 5 5 packageStatic.pack1; import Static.pack2.Balance; class Caller { public static void main(String args[]) { Balance.a = 10; System.out.println(Balance.a); } } packageStatic.pack2; public class Balance { public static int a = 5; } package Static.pack1; import Static.pack2.Balance; class Caller { public static void main(String args[]) { Balance.a = 10; System.out.println(Balance.a); } } package Static.pack2; public class Balance { public final static int a = 5; } Using the Static Keyword to Create Constants One common use of static is to create a constant value that’s 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 constant (in other words, to prevent it ever being changed). 10 error package Static.pack1; import Static.pack2.Balance; class Caller { public static void main(String args[]) { Balance Balance1 = new Balance(); Balance Balance2 = new Balance(); Balance Balance3 = new Balance(); } } package Static.pack2; public class Balance { // Set count to zero initially. static int count = 0; public Balance() { // Every time the constructor runs, increment count. count++; // Display count. System.out.println("Created object number: " + count); } } run: Created object number: 1 Created object number: 2 Created object number: 3 package Static.pack1; import Static.pack2.Balance; class Caller { public static void main(String args[]) { Balance Balance1 = new Balance(); Balance Balance2 = new Balance(); Balance Balance3 = new Balance(); System.out.println(Balance2.getID()); } } package Static.pack2; public class Balance { static int count = 0; int id; public Balance() { count++; id= count; } public int getID() { return id; } } run: 2
  • 37. 36 Opinion Classification static variable static method 1) If you declare any variable as static, it is known static variable.  The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.  The static variable gets memory only once in class area at the time of class loading. 2) If you apply static keyword with any method, it is known as static method  A static method belongs to the class rather than object of a class.  A static method can be invoked without the need for creating an instance of a class.  static method can access static data member and can change the value of it. static method  It is a method which belongs to the class and not to the object(instance)  A static method can access only static data. It can not access non-static data (instance variables)  A static method can call only other static methods and can not call a non-static method from it.  A static method can be accessed directly by the class name and doesn’t need any object  Syntax : <class-name>.<method-name>  A static method cannot refer to "this" or "super" keywords in anyway  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 the initialization of any instance variables  A single copy to be shared by all instances of the class  A static variable can be accesseddirectly by the class name and doesn’t need any object  Syntax : <class-name>.<variable-name> 1. class Student{ 2. int rollno; 3. String name; 4. String college="ITS"; 5. } 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 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. 1. //Program of changing the common property of all objects(static field). 2. 3. class Student9{ 4. int rollno; 5. String name; 6. static String college = "ITS"; 7. 8. static void change(){ 9. college = "BBDIT"; 10. } 11. 12. Student9(int r, String n){ 13. rollno = r; 14. name = n; 15. } 16. 17. void display (){System.out.println(rollno+" "+name+" "+college);} 18. 19. public static void main(String args[]){ 20. Student9.change(); 21. 22. Student9 s1 = new Student9 (111,"Karan"); 23. Student9 s2 = new Student9 (222,"Aryan"); 24. Student9 s3 = new Student9 (333,"Sonoo"); 25. 26. s1.display(); 27. s2.display(); 28. s3.display(); 29. } 30. } Output:111 Karan BBDIT 222 Aryan BBDIT 333 Sonoo BBDIT class Caller{ int rollno; String name; static String college ="ITS"; Caller(int r,String n, String m){ rollno = r; name = n; college = m; } void display () { System.out.println(rollno+" "+name+" "+college); } public static void main(String args[]) { Caller s1 = new Caller(111,"Karan", "SEU"); Caller s2 = new Caller(222,"Aryan", "BAF"); s1.display(); s2.display(); } } run: 111 Karan BAF 222 Aryan BAF BAF because The static variable can be used to refer the common property of all objects (that is not unique for each object)  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. 1. //Program to get cube of a given number by static method 2. 3. class Calculate{ 4. static int cube(int x){ 5. return x*x*x; 6. } 7. 8. public static void main(String args[]){ 9. int result=Calculate.cube(5); 10. System.out.println(result); 11. } 12. } Output:125 class Caller { static int a =5; public static void main(String args[]) { System.out.println("Hello "+a); } } run: Hello 5  A static variable can be accessed directly by the class name and doesn’t need any object Restrictions for static method There are two main restrictions for the static method. They are:  The static method can not usenon static data member or call non-static method directly.  this and super cannotbe used in static context.
  • 38. 37 public class Stuff { public static String name = "I'm a static variable"; } public class Application { public static void main(String[] args) { System.out.println(Stuff.name); } } 1. class A{ 2. int a=40;//non static 3. 4. public static void main(String args[]){ 5. System.out.println(a); 6. } 7. } Output:Compile Time Error 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 wecreate 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 programit firstlook that programwhich has static method & called as a main & defined as public access modifier static block  Is used to initialize the static data member.  It is executed before main method at the time of classloading. class A2{ static{System.out.println("static block is invoked");} public static void main(String args[]){ System.out.println("Hello main"); } } Output:static block is invoked Hello main // Demonstrate static variables, methods, and blocks. class UseStatic { static int a = 3; static int b; static void meth(int x) { System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b); } static { System.out.println("Static block initialized."); b = a * 4; } public static void main(String args[]) { meth(42); } } Static block initialized. x = 42 a = 3 b = 12 Outside of the class in which they are defined, static methods and variables can be used independently of any object. To do so, you need only specify the name of their class followed by the dot operator. For example, if you wish to call a static method from outside its class, you can do so using the following general form: classname.method( ) 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  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  Abstract class exist to extended they cannot be instantiated  
  • 39. 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 wemake the variable final then the value of that variable cannot be changed once assigned.  Way 2 : Final Method o We cannot Overridethe final method as we cannot change the method once they are declared final.  Way 3 : Final Class o We cannot inherit the final class  The final keyword is a non-access modifier.  It can be applied to a class, method(both instance and static) and variable(instance, static, local and parameter). Examples Pictures Explanation Access level Opinion Final Entity Description final Method is inherited but cannot be overriden so always method fromparent class will be executed. package com.c4learn.inheritance;
  • 40. 39 Final Value Final Value cannot be modified Final Method Final Method cannot be overriden Final Class Final Class cannot be inherited public class ShapeClass { final void setShape() { System.out.println("I am Inherited");; } public static void main(String[] args) { 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 } }
  • 41. 40 Pictures Explanation Access level Opinion Additional info Constants  Fields that are marked as final, static, and public are effectively known as constants  For example, the following variable declaration defines a constant named PI, whose value is an approximation of pi 1 public static final double PI = 3.141592653589793;  Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so. 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, ARRAY_SIZE MAX_GRADE PI If a primitive type or a String is defined as a constantand the value is known at compile time, the compiler replaces the constant name everywhere in the codewith 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  Superisusedto referthe immediate parentof 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
  • 43. 42 this keyword  This = global  package personal; class Test { int i = 20; void local() { int i = 10; System.out.println("Local i = " + i); System.out.println("Global this.i = " + this.i); //this = gloabl } public static void main(String args[]) { Test obj = new Test(); obj.local(); } } package personal; class Student { String name; int roll; float mark; Student(String name, int roll, float mark) { this.name = name; this.roll = roll; this.mark = mark; } } public class ConstructorCallingExplain { public static void main(String args[]) { Student obj1 = new Student("saifur", 67, 70.0f); Student obj2 = new Student("rasel", 58, 75.5f); System.out.println(obj1.name); System.out.println(obj1.roll); 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) {
  • 44. 43 this.x = x; this.y = y; } } Inheritance & interfaces Child Class/Derived Class/Inherited class Parent Class/Base class/Super Class Child Class/Derived Class/Inherited class Parent Class/Base class/Super Class •Likeimport •Everythinginbase classshouldbepublic ifwewanttoaccess
  • 45. 44
  • 46. 45 The History and Evolution of Java Object-oriented programming is a programming methodology that helps organize complex programs through the use of 1. inheritance, 2. encapsulation, and 3. polymorphism. These 3 musthave been in objectoriented programming language World Wide Web demanded portable programs. Perhaps the most important example of Java’s influence is C#. Created by Microsoft to supportthe .NET Framework, C# is closely related to Java. Forexample, both share the same general syntax, supportdistributed programming, and utilize the same object model. There are, of course, differences between Java and C#, but the overall “look and feel” of these languages is very similar. Goals of java 1. It should be object oriented 2. A single representation of a program could be executed on multiple operating systems 3. It should fully supportnetwork programming 4. It should execute codefrom remote sources securely 5. It should be easy to use 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# ? 1. After the creation of Java, Microsoftdevelopedthe 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, supportdistributed programming, and utilize the same object model. 3. Though there are some differences between Java and C#, but the overall feel of these languages is very similar. 4. If you already know C#, then learning Java will be easy and vice versa 5. Java and C# are optimized for two different types of computing environments. 6. C# and Java Both Languages are drew from C++. 7. Both Languages are capable of creating cross platform portable program code. Consider Scenario of Java Programming Language 1. Java is created by Sun Micro System. 2. Java Compiler produces Intermediate code calledByte Code. 3. Byte Codei.e intermediate code is executed by the Run Time Environment. 4. In Java Run Time Environment is called as JVM [ Java Virtual Machine] 5. If we have JVM already installed on any platform then JVM can produce machine dependent Code basedon the intermediate 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
  • 47. 46 Delegates Absent Supported Interpreter vs compiler Java compilation process
  • 48. 47 Java is considered as Portable because– Java is Considered as Platformindependent becauseof many different reasons which are listed below – 1. Output of a Java compiler is Non Executable Code i.e Bytecode. 2. Bytecode is a highly optimized set of instructions 3. Bytecode is executed by Java run-time system, which is calledthe Java Virtual Machine (JVM). As the output of Java Compiler is Non Executable Code we canconsiderit as Secure (it cannot be used for automated executionof malicious programs). Important Note : As the output of Java Compiler is Non Executable Codewe can consider it as Secure (it cannot be used for automated execution of malicious programs). 4. JVM is an interpreter. 5. JVM accepts Bytecode as input and execute it. 6. Translating a Java program into bytecodemakes it much easier to run a program in a wide variety of environments because only the JVM needs to be implemented for eachplatform. 7. For a given System we have Run-time package , once JVM is installed for particular systemthen any java program can run on it. 8. However Internal details of JVM will differ from platform to platform but still all understand the Same Java Bytecode. Java is a strictly typed language, it checks your code at compile time. However, it also checks your code at run time 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 The Java Buzzwords No discussion of Java’s history is complete withouta look at the Java buzzwords. Although the fundamentalforces that necessitated the invention of Java are portability and security, other factors also played an important role in molding the final formof the language. The key considerations were summed up by the Java team in the following list of buzzwords: • Simple • Secure • Portable • Object-oriented • Robust • Multithreaded • Architecture-neutral • Interpreted • High performance • Distributed • Dynamic
  • 49. 48
  • 50. 49
  • 51. 50 An Overview of Java Two Paradigms All computer programs consistof two elements: 2. codeand 3. data Furthermore, a programcan be conceptually organized around its code or around its data. That is, 1. some programs are writtenaround“what is happening” (process-orientedmodel.)and process-oriented model. This approach characterizes a programas a series of linear steps (that is, code). The process-oriented modelcan be thoughtof as code acting on data 2. others are writtenaround“who is being affected.” ( Object-oriented programming) Object-oriented programming organizes a programaround its data (that is, objects) and a set of well-defined interfaces to that data. An object-oriented programcan be characterized as data controlling access to code. As you will see, by switching the controlling entity to data The Three OOP Principles 1. Encapsulation ( লুকিয়ে রাখা ) Inheritance is the process bywhich one object acquires the properties of another object. 2. Polymorphism( বহুরূপতা) 1. “many forms” 3. Inheritance( উত্তরাকিিার) Program By convention,the name of the mainclassshouldmatchthe name of the file thatholdsthe program. package class2; import java.io.*; class Class2 { public static void main(String args[]) { System.out.println("Hello world"); } } Control statement The if Statement
  • 52. 51 if(condition) statement; Loop 1. for(initialization; condition; iteration) statement; 2. ( x++ ) = ( x+=1 ) = ( x = x+1 ) 3. ( x-- ) = ( x-=1 ) = ( x = x-1 ) package class2; import java.io.*; class Class2 { public static void main(String args[]) { for(int x = 0; x<10; x++) { 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. 2. An identifier may be any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore and dollar-sign 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. 4. Again, Java is case-sensitive, so VALUE is a different identifier than Value. examples of valid identifiers are AvgTemp count a4 $test this_is_ok Invalid identifier names include these: 2count high-temp & Not/ok Separators Symbol Name Purpose ( ) Parentheses Used to contain lists of parameters in method definition and invocation. Also used for defining precedencein expressions, containing expressions in control statements, and surrounding cast types. { } Curly Braces Used to contain the values of automatically initialized arrays. Also used to 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. , Comma Separates consecutive identifiers in a variable declaration. Also used to chain statements together ins000ide a for statement. . Period Used to separatepackage names from subpackages and classes. Also used to separatea variable or method from a referencevariable. :: Colons Used to create a method or constructorreference.(Added byJDK 8.)
  • 53. 52 The Java Keywords There are 50 keywords currently defined in the Java language. These keywords, combined with the syntax of the operators and separators, form the foundation abstract continue for new switch assert default goto package synchronized boolean do if private this break double implements protected throw byte else import public throws 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
  • 54. 53
  • 55. 54 Chapter 1 (Variables & Data Types) Data Types
  • 56. 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 { public static void main(String args[]) { boolean a = true, b = false; System.out.println("a = "+ a); System.out.println("b = "+ b); } } class ex1 { public static void main(String args[]) { int a = 10, b = 15; System.out.println("(a > b) = "+ (a > b)); boolean c = (a < 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 Integer Data Type : 1. Integer Data Type is used to store integer value. 2. Integer Data Type is Primitive Data Type in Java Programming Language. 3. Integer Data Type have respective Wrapper Class – “Integer“. 4. Integer Data Type is able to store both unsigned ans signed integer values so Java opted signed, unsigned concept of C/C++. Class IntDemo { public static void main(String args[]) { int number=0; System.out.println("Total Number : " + number); } } Explanation : 1. Primitive Variable can be declared using “int” keyword. 2. Though Integer contain default Initial Value as 0 , still we have assign 0 to show assignment in Java. 3. “+” operator is used to concatenate 2 strings. 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); }
  • 57. 56 } Variable Input/Output import java.io.*; class ex1 { public static void main(String args[]) { DataInputStream in = new DataInputStream(System.in); char ch; try{ System.out.print("Enter a character : "); ch = (char) System.in.read(); System.out.println("You have entered : "+ ch); } catch (Exception e){} } } import java.io.*; class ex1{ public static void main(String[] args){ try{ InputStreamReader IN = new InputStreamReader(System.in); BufferedReader BR = new BufferedReader(IN); String s = BR.readLine(); System.out.println(s); } catch(Exception E){} } } import java.io.*; 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 age : "); String s = BR.readLine(); int age = Integer.parseInt(s); System.out.println("Your age is : " + age); } catch(Exception E){} } } Type conversion String s = BR.readLine(); int age = Integer.parseInt(s); String s = BR.readLine(); float age = Float.parseFloat(s); Chapter 2 (Variables & Data Types)
  • 58. 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");
  • 59. 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; 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 how many fibonacci numbers : "); String s = BR.readLine(); int input = Integer.parseInt(s); int f0 = 0, f1 = 1, f2; for (int i = 0; i<input; i++){ f2 = f0 + f1; System.out.print(f2 + " " ); f0 = f1; f1 = f2; } } catch (Exception E){} } } 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 how many fibonacci numbers : "); String s = BR.readLine(); int input = Integer.parseInt(s); int f0 = 0, f1 = 1, f2; System.out.print("0 1 " ); for (int i = 0; i<input-2; i++){ f2 = f0 + f1; System.out.print(f2 + " " ); f0 = f1; f1 = f2; } } catch (Exception E){} } } int f0 = 0, f1 = 1, f2; System.out.print("0 " ); for (int i = 0; i<input-1; i++){ f2 = f0 + f1; System.out.print(f2 + " " ); f1 = f0; f0 = f2; } Prime numbers 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 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 series of prime number up to : "); String s = BR.readLine(); int input = Integer.parseInt(s); int i = 0, j = 0; for (i = 2; i<input; i++, j++){ for(j = 2; j<i; j++){ if(i % j == 0){ break; } } if (i == j){ System.out.print(i); } } } catch (Exception E){} } } import java.util.*; class Mainthread { public static void main(String[] args) { try { Scanner sc = new Scanner(System.in); System.out.print("Enter series of prime number up to : "); int input = sc.nextInt(); int i = 0, j = 0; for (i = 2; i<input; i++, j++) { for(j = 2; j<i; j++) { if(i % j == 0) break; } if (i == j) System.out.print(i+" "); } } catch (Exception E){} }
  • 60. 59 } Nested loop System.out.print("Enter number up to : "); String s = BR.readLine(); int input = Integer.parseInt(s); int i, j; for (i = 1 ; i<=input; i++){ for (j = 1; j<=i; j++){ System.out.print(j); } System.out.print("n"); } System.out.print("Enter number least to : "); String s = BR.readLine(); int input = Integer.parseInt(s); int i, j; for (i = 1 ; i<=input; i++){ for (j = 1; j<=input; j++){ System.out.print(j); } System.out.print("n"); } System.out.print("Enter number least to : "); String s = BR.readLine(); int input = Integer.parseInt(s); int i, j; for (i = 1 ; i<=input; i++){ for (j = input; j>=i; j--){ System.out.print(j + " "); } System.out.print("n"); } System.out.print("Enter number least to : "); String s = BR.readLine(); int input = Integer.parseInt(s); int i, j; for (i = input ; i>=1; i--){ for (j = 1; j<=i; j++){ System.out.print(j + " "); } 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); }
  • 61. 60 } Value assigning when the array declared int array[] = {1,2,3,4,5}; int total = 0; for (int i = 0; i<=4; i++){ total = total + array[i]; } System.out.println(total); int marks[] = {40, 55, 69, 89, 78}; for (int i = 0; i<5; i++){ System.out.print("marks[" + i + "] = " + marks[i]); System.out.print("n"); } Value assigning while program processing 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); int array[] = new int[5]; int total = 0; System.out.println("Enter 5 of your Numbers to Sum : "); for(int i =0; i<=4; i++){ String s = BR.readLine(); int input = Integer.parseInt(s); array[i] = input; } for (int i = 0; i<=4; i++){ total = total + array[i]; } System.out.println("Total = "+total); } 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("Enter Marks ["+ i +"] = "); String s2 = BR.readLine(); Marks[i] = Float.parseFloat(s2); } for (int i=0; i<5; i++){ System.out.println("Roll ["+ i +"] = " + Roll[i]); System.out.println("Marks["+ i +"] = " + Marks[i]); } } 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("Enter Marks ["+ i +"] = "); String s2 = BR.readLine(); Marks[i] = Float.parseFloat(s2); } for (int i=0; i<5; i++){ System.out.println("Roll ["+ i +"] = " + Roll[i]); System.out.println("Marks["+ i +"] = " + Marks[i]); } } catch (Exception E){ System.out.println("Error in inpuit. Program terminated ....."); System.exit(0); } } } 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); } } }
  • 62. 61 Chapter 5 (String) class ex1{ public static void main(String [] args){ String first_name = new String("Md. Saifur"); StringBuffer last_name = new StringBuffer(" Rahman"); System.out.println(first_name + last_name); } } class ex1{ public static void main(String [] args){ String first_name = new String("Md. Saifur "); String full_name = first_name + "Rahman"; System.out.println(full_name); } }