Download as pdf or txt
Download as pdf or txt
You are on page 1of 108

HARE KRISHNA

CORE JAVA

NOTES MADE BY: FACULTY DETAILS:

ROHNAK AGARWAL NIHARIKA NAYAK MADAM


2ND YEAR, CSE CORE JAVA FACULTY
CET, BBSR CTTC, BBSR

JAVA INTERNSHIP COURSE


COURSE DURATION: 1 MONTH (1-6-2019 TO 29-6-2019)
TIMING: 7:00AM-10:00AM AND 10:00AM-1:00PM

Page 1 of 108
CONTENTS
SL. DATE TOPICS TAUGHT PAGE

1 04/06/2019 BASIC CONCEPTS OF C++, JAVA INTRODUCTION 3

2 05/06/2019 KEYWORDS, VARIABLES, ACCESS SPECIFIERS, CAMEL RULE, 6


ARITHMATIC OPERATORS

3 06/06/2019 ARITHMATIC, BITWISE, SHIFT, EQUALITY, ASSIGNMENT, 12


STRING CONCATENATION, new, SHORT-CIRCUIT

4 07/06/2019 instanceof, CONDITIONAL, JVM ARCHITECTURE, Scanner CLASS 17

5 08/06/2019 CONDITIONAL STATEMENTS, ITERATIONAL OPERATOR 22

6 11/06/2019 while LOOP, ARRAY, COMMAND LINE ARGUMENT, PARSING, 37


valueOf()

7 12/06/2019 JAGGED ARRAY, String CLASS, STRING FUNCTIONS 45

8 13/06/2019 STRING FUNCTIONS (contd.), MUTABLE & IMMUTABLE OBJECTS, 49


StringBuffer CLASS, class FUNDAMENTALS, static METHODS

9 17/06/2019 NON-static METHODS, INSTANCE IN JAVA, STATIC VARIABLES, 55


This KEYWORD, LOCAL VARIABLES, METHOD OVERLOADING

10 18/06/2019 CONSTRUCTOR, super(), this(), COMPILER’S BRAIN 57

11 19/06/2019 static BLOCK, NON-static BLOCK, INHERITENCE (SINGLE, 61


MULTILEVEL, HIERARCHICAL), CONSTRUCTORS IN MULTILEVEL
INHERITENCE

12 20/06/2019 METHOD OVERRIDING, INTERFACE, final KEYWORD 68

13 21/06/2019 ABSTRACT CLASS, ABSTRACT METHODS 72

14 22/06/2019 ABSTRACT CLASS vs. INTERFACE, EXCEPTION HANDLING, 73


Try, catch, throw, throws, finally KEYWORDS

15 24/06/2019 FILE HANDLING, FileWriter, BufferedWriter, PrintWriter CLASSES 83

16 25/06/2019 THREADS, MULTI-THREADING 90

17 26/06/2019 CONTROLLING THREAD EXECUTION, Applet (SHAPES) 95

18 27/06/2019 Applet (GIF, AUDIO), AWT (FRAMES, BUTTONS) 101

19 28/06/2019 AWT (CHECKBOX), WRAPPER CLASS, AUTOBOXING, UNBOXING 104

End Page 107

BIBLIOGRAPHY 108

Page 2 of 108
4 JUNE 2019 HK

1. PROGRAM: Set of instructions to do a particular task.

2. SOFTWARE: Collection of programs which execute some specific task.

3. TYPES OF SOFTWARES:

SYSTEM SOFTWARE APPLICATION SOFTWARE


It executes over hardware. It executes over software.
Example: operating system, Example: game, adobe reader
Embedded software, robotic software

4. LEVEL OF PROGRAMMING LANGUAGES:

LOW LEVEL LANGUAGE HIGH LEVEL LANGUAGE


a. These are system-friendly, but a. These are user-friendly, but not
not user-friendly. System-friendly.
b. It can be directly executed by system. b. It can’t be directly executed by the system.
c. It consists of binary digits (0 and 1). c. It consists of general English language and
required to be translated in low level lang.
d. It is architecture dependent, which means d. It is architecture independent, which means
same program may give different outputs a program will give same outputs on different
on different machines. Machines.

Mac OS [will not run]


Compile
Source Code (Program) .exe Linux OS [will not run]

Unix OS [will not run]


PLATFORM DEPENDENT

Mac OS [will run]


Compile JVM
Source Code (Program) .class Linux OS [will run]

Unix OS [will run]

PLATFORM INDEPENDENT

5. PLATFORM DEPENDENT PLATFORM INDEPENDENT


When a .exe file is copied from a Windows When a .class file is copied from a Windows
OS to another OS like MacOS, the copied OS to another OS like MacOS, the copied
file doesn’t work/ run. file is decoded by that OS’s JVM and it
works/ runs.

Page 3 of 108
JAVA
1. It is purely Object Oriented Programming language.
2. It was created by James Gosling in year 1995 for Sun Micro Systems.
3. It is a platform independent programming language that follows the logic – Write once, Run
Everywhere.
4. It is categorized in 3 types:
a. JSE JAVA STANDARD EDITION FOR DESKTOP AND STANDALONES
b. JEE JAVA ENTERPRISE EDITION FOR WEBSITE, DESKTOP AND DISTRIBUTED
c. JME JAVA MICRO EDITION FOR MOBILE APPLICATIONS

JSE
1. It is the standard module of Java, which contains all minimum requirements for application/ java.
2. Using it, we can build desktop applications/ stand-alone applications.

JEE OR J2E
WEB APPLICATION
Here, multiple clients are connected to 1 system.

DISTRIBUTED APPLICATION
Here, software based clients can be connected to the software based server.
Server software can be connected to the client in web application.

1. It is an important module of Java for developing software.


2. It is based on JSE module.
3. Using it, we can build web application/ distributed application or combination of both web and
distributed application.
4. Web application is nothing but a client-server application where fixed client can communicate with
software based server.
5. Distributed application is also a web application but here processing unit is distributed among
multiple servers with clients. So, software based client communicate with software based server is
called distributed application.

JME
It is used to build mobile applications.

FEATURES OF JAVA:
1. SIMPLE
It is purely syntax based, so simple. Java syntax are simple and easy to write and understand.
2. OOPS
3. ROBOSTIC
4. SECURE
5. PLATFORM INDEPENDENT
6. MULTI-THREADING
7. INTERPRETED
8. ARCHITECTURAL NEUTRAL
9. DYNAMIC
10. DISTRIBUTED
11. MULTI-MEDIA
12. PORTABLE

Page 4 of 108
Object Oriented Programming Synopsis (OOPS):

1. CLASS:
a. Collection of similar types of objects.
b. It is a container of data member, behavior and functionality.

2. OBJECT:
a. It is an instance of a class.
b. It can access behavior and member of class.

3. DATA ABSTRACTION:
a. It means displaying necessary information and hiding the background/ code details to
end-user.
b. Due to abstraction, OOPS support security and prevent hacking.

4. DATA HIDING:
a. The internal details are never accessed by outsider directly.
b. Provides security. Only validate users can access the internal details.

5. ENCAPSULATION:
Wrapping and binding code into a single unit execute a specific task.

6. INHERITANCE:
a. All features are available in one software.
b. Creating a new software from existing software/ creating a new class from existing class with
acquiring all properties of existing class.

Page 5 of 108
05 JUNE 2019 HK

COMPONENTS OF A JAVA PROGRAM

1. CHARACTERS:
i. a to z ASCII values : 97 to 122
ii. A to Z ASCII values : 65 to 90
iii. 0 to 9 ASCII values : 48 to 57

2. KEYWORDS (53):
i. MODIFIERS (11): iv. super
i. private iv. DATATYPE (8):
ii. protected i. byte
iii. public ii. char
iv. static iii. short
v. final iv. int
vi. abstract v. long
vii. volatile vi. float
viii. transient vii. double
ix. strictfp viii. boolean
x. synchronized v. CLASS (6):
xi. native i. class
ii. CONTROL STATEMENTS (11): ii. interface
i. if iii. import
ii. else iv. package
iii. switch v. extends
iv. case vi. implements
v. default vi. EXCEPTION (6):
vi. break i. try
vii. continue ii. catch
viii. while iii. throw
ix. do iv. throws
x. for v. finally
xi. return vi. assert
iii. OBJECT (4): vii. NON-RETURN TYPE (1):
i. new i. void
ii. instanceof viii. ENUMERATION (1):
iii. this i. enum

The remaining 5 keywords:


i. Obsolete keywords:
const and goto are reserved keywords, even if they are not currently in use.

ii. Literal cum keywords:


true, false and null are literals, treated as keywords.

Page 6 of 108
IDENTIFIERS OR VARIABLES:
A name in java program is called as an identifier. It can be a method’s name, class’s name or a
variable’s name.

DATATYPES:
It defines the type of data a variable can store.

DATATYPES

PRIMITIVE NON-PRIMITIVE

NUMERIC NON-NUMERIC

INTEGER FLOATING char boolean

byte long float double


short int

SL.NO. DATATYPE SIZE(IN BYTES) RANGE

1 byte 1 -128 to +127


2 char 2 0 to +216-1 (65535)
3 short 2 -215 to +215-1
4 int 4 -231 to +231-1
5 long 8 -263 to +263-1
6 float 4
7 double 8
8 boolean 1 (depends on JVM) true AND false

ACCESS SPECIFIER OR MODIFIER:


It is the restriction for data accessing. Types:
1. private
2. public
3. protected
4. default/ no access specifier

Example:
class Demo
{
private int a;
public int b;
protected int c;
int d;
}

Page 7 of 108
NOTE:
1. ‘a’ can be accessed within same class but not outside the class, not even using the object.
2. ‘b’ can be accessed anywhere within the class, within child class and outside the class (using
object).
3. ‘c’ can be accessed within same class. It is also accessible in child class.
4. ‘d’ has same properties as ‘a’, except the fact that it cannot be accessed outside current package.

CAMEL RULE:
This rule defines the restrictions for naming of classes, methods, instances and variables.
1. CLASS and INTERFACE:
a. First character of class name should be in upper case (as in Java library).
Example: Scanner class.
b. If we take multiple words as one name, first letter of each word should be capital.
Example: BufferedReader class.
2. METHOD:
a. First character of method name should be in lower case (as in Java library).
Example: main()
b. If we take multiple words as one name, first letter of each word (after first word) should be
capital.
Example: myMethod()
3. VARIABLES:
a. Whole name should be in lower case.
Example: name
4. CONSTANTS:
a. Whole name should be in upper case.
Example: PI

OPERATORS:
EXPRESSION: It is a combination of operands and operators.
OPERATOR: It is a symbol which indicates the compiler to perform certain mathematical/ logical
operation.

OPERATORS IN JAVA:
There are 3 types of operators depending on the number of operands:
a. Unary operator
b. Binary operator
c. Ternary operator

Depending on functionality, there are following types of operators:


a. Arithmetic operators + - * / %
b. Increment/ decrement operators ++ --
c. Relational operators > < >= <=
d. Bitwise operators & | ^
e. Short-circuit (logical) operator && || !
f. Equality operator ==
g. Assignment operator = += -= *= /= %= >>= <<=
h. Conditional operator ?:
i. Shift operator >> <<
j. new operator new
k. Concatenation operator +
l. instanceof operator instanceof

Increment/ decrement operator:


++ increases the value of the variable by 1 unit
-- decreases the value of the variable by 1 unit
Page 8 of 108
Examples:

Eg-1: int a=5;


a++;
System.out.pintln(a);

Output:
6

Eg-2: int a=5, b;


b=a++;
System.out.println(a);
System.out.println(b);

Output:
6
5

Eg-3: int a=5, b;


b=++a;
System.out.println(a);
System.out.println(b);

Output:
6
6
Eg-4: int a=5, b;
b=++a + a++;
System.out.println(a);
System.out.println(b);

Output:
7
12
Explanation: b = ++a + a++;
6 6  values at the time of evaluation

++a will be evaluated: value of a will be incremented to 6 and the value 6 is used in the
expression.
a++ will be evaluated: current value of a, 6, will be used in expression, and then the value of
a is incremented to 7.

Eg-5: int a=2, b;


b = ++a + a++ + a++ + a++;
System.out.println(a);
System.out.println(b);
Output:
6
15
Explanation:
b= ++a + a++ + a++ + a++;
3 3 4 5  values at the time of evaluation

Page 9 of 108
Eg-6: int a=2, b;
b = ++a + ++a + ++a + ++a;
System.out.println(a);
System.out.println(b);

Output:
6
18

Explanation:
b = ++a + ++a + ++a + ++a;
3 4 5 6  values at the time of evaluation

Eg-7: int a=2, b;


b = ++a * ++a - ++a;
System.out.println(a);
System.out.println(b);

Output:
5
7

Explanation:
b = ++a * ++a - ++a;
3 * 4 - 5  values at the time of evaluation
b= 12 - 5 = 7 (* and /) before (+ and -)

Eg-8: char ch = ’A’ ;


ch++;
System.out.println(ch);

Output:
B
Eg-9: double d= 8.9;
d++;
System.out.println(d);

Output:
9.9

Eg-10: boolean b=false;


b++;
System.out.println(b);

Output:
Compile time error: bad operand type boolean for unary operator ‘++’.

Eg-11: int a=10, b;


b = ++10;
System.out.println(b);

Output:
Compile time error: unexpected type
Required: variable Found: value

Page 10 of 108
Eg-12: int x=10, y;
y=++(++x);
System.out.println(y);

Output:
Compile time error: unexpected type
Required: variable Found: value

Note: Nesting of increment/ decrement operators is illegal.

Eg-13: byte a=10, b;


b=++a;
System.out.println(b);

Output:
11

Eg-14: byte a=10, b;


b= a+1;
System.out.println(b);

Output:
Compile time error: incompatible types: possible lossy conversion from int to byte.

Eg-15: byte a=10, b;


b = a + (byte)1; //or b = (byte)(a+1);
System.out.println(b);

Output:
11
Note: 1. All mathematical operations on any 2 operands result in :
Max( int, type_A, type_B)
2. In increment/ decrement, internal typecasting is done automatically.

Page 11 of 108
06 JUNE 2019 HK

Note: If we apply any arithmetic operation between two variables/ values a & b, then, the result will be:
Maximum(int, type_a, type_b).

Order of datatypes based on size of result:

char > byte > short > int > long > float > double

Note:
1. char + char = int
2. char + byte = int
3. char + short = int
4. char + int = int
5. char + long = long
6. char + float = float
7. char + double = double
8. byte + byte = int
9. byte + short = int
10. byte + int = int
11. byte + long = long
12. byte + float = float
13. byte + double = double
14. short + short = int
15. short + int = int
16. short + long = long
17. short + float = float
18. short + double = double
19. int + int = int
20. int + long = long
21. int + float = float
22. int + double = double
23. long + long = long
24. long + float = float
25. long + double = double
26. float + float = float
27. float + double = double
28. double + double = double

Example: ‘a’ + 0.45 = 97.45

Eg-1: System.out.println(10 / 0);


Output: Exception in thread “main” java.lang.ArithmaticException : / by zero

Eg-2: System.out.println(10 / 0.0); Output: Infinity

Eg-3: System.out.println(-10 / 0.0); Output: -Infinity

Eg-4: System.out.println(0 / 0);


Output: Exception in thread “main” java.lang.ArithmaticException : / by zero

Eg-5: System.out.println(0.0 / 0); Output: NaN

Eg-6: System.out.println(-0.0 / 0); Output: NaN

Eg-7: System.out.println(0.0 / 0.0); Output: NaN

Page 12 of 108
VIEWING THE FUNCTION AND CONSTANTS LIST OF A CLASS:
>>>javap <class full path>
Eg: >>>javap java.lang.Integer
>>>javap java.lang.Double
>>>javap java.lang.Long
and so on…

java.lang.Integer

java.lang.Float

Page 13 of 108
Note: After seeing the java.lang.Integer Class and java.lang.Float Class (after enlarging the
screenshots), it should be noticed that the Float class contains the constants:

public static final float POSITIVE_INFINITY;


public static final float NEGATIVE_INFINITY;
public static final float NaN;

which are not available in Integer class. This is the reason why ArithmeticException (/ by zero)
occurs when both operands are integers.
While, the same operations result in Infinity, -Infinity and NaN when at least one of the operands is a
float.

RELATIONAL OPERATORS:
> < <= >=

These are used for comparison of values. The result is always a boolean (true OR false).

Example: Expression Result

10 < 20 true
‘a’ < 10 false
‘a’ < 97.6 true
‘a’ < ‘A’ true

Note: 1. These operators are legal for all primitive datatypes except boolean.
2. Strings can’t be compared using these operators.

BITWISE OPERATORS:
& | ^

Example: Expression Result

5 & 4 4
5 | 4 5
5 ^ 4 1

Explanation: TRUTH TABLES:

5 & 4 : 1 & 1 = 1
5  00000101 1 & 0 = 0
4  00000100 0 & 1 = 0
Result  00000100 0 & 0 = 0

5 | 4 : 1 | 1 = 1
5  00000101 1 | 0 = 1
4  00000100 0 | 1 = 1
Result  00000101 0 | 0 = 0

5 ^ 4 : 1 ^ 1 = 0
5  00000101 1 ^ 0 = 1
4  00000100 0 ^ 1 = 1
Result  00000001 0 ^ 0 = 0

Page 14 of 108
SHIFT OPERATORS:
>> <<

Example: Expression Result Explanation Formula

5 << 2 20 5 * 22 a << b = a * 2b
5 >> 2 1 5 / 22 a >> b = a / 2b
-5 << 2 -20 -5 * 22

BITWISE OPERATOR LOGICAL OPERATOR


a. Applicable for both Boolean and a. Applicable for Boolean type data only.
integer type data.
b. Executes all operands to generate b. First operand is executed compulsarily
the result. but execution of second operand depends
on the result of first operand.
c. low performance c. high performance

EQUALITY OPERATOR:
==

Example: Expression Result

‘a’ == 97 true
‘a’ == 97.00 true
false == false true

Note: It is applicable for all primitive datatypes, including boolean.

ASSIGNMENT OPERATORS:
= += -= *= /= %= >>= <<=

Types of expressions:
1. Single: a = 10;
2. Chained: a = b = c = 10;
3. Compound: a += b *= c /= 2;

STRING CONCATENATION OPERATOR:


+

‘+’ is the only overloaded operator in Java.

Example: String a = “xyz”; int b = 10, c = 20, d = 30;

Expression Result

b+c+d+a 60xyz
b+c+a+d 30xyz30
b+a+c+d 10xyz2030
a+b+c+d xyz102030

a=b+c+d Error: incompatible types: int cannot be converted to String.


a=a+b+c value of a  xyz1020

Page 15 of 108
NEW OPERATOR:
new
1. It creates current class object.
2. It is used for allocation of memory.

Eg-1:
class Demo
{
void show()
{
System.out.println(“Hi”);
}

public static void main(String args[])


{
Demo d = new Demo();
d.show();
}
}

Output:
Hi

Eg-2:
class X
{
void show()
{
System.out.println(“class X”);
}
}

class Y
{
public static void main(String args[])
{
X obj = new X();
obj.show();
}
}

Output:
class X

Page 16 of 108
07 JUNE 2019 HK

INSTANCEOF OPERATOR:
instanceof
It is used to check the type of object.

Eg:
class Demo
{
public static void main(String args[])
{
Demo d = new Demo();
System.out.println(d instanceof Demo);
}
}

Output:
true

CONDITIONAL OPERATOR:
?:
It is the only ternary operator in Java.

Syntax: ( Condition ) ? ( Expression_1) : ( Expression_2 ) ;

Eg-1: int a=10, b=20, gr;


gr = (a>b) ? a: b ;
System.out.println(“Greatest number : “ + gr);

Output:
Greatest number : 20

Eg-2: int a=10, b=20;


System.out.println(a>b?a:b);

Output:
20

Page 17 of 108
JVM ARCHITECTURE

JAVA SOURCE FILE


Demo.java

JAVAC COMPILE

JAVA .class FILE


Demo.class

.class FILE IS LOADED IN


JVM
CLASS LOADER SUB-SYSTEM.
CLASS LOADER
LOADING LINKING INITIALISATION
BOOTSTRAP
CLASS LOADER VERIFY
↓ ↓
EXTENSION PREPARE
CLASS LOADER ↓
↓ RESOLVE
APPLICATION
CLASS LOADER

MEMORY
METHOD HEAP STACK PC REGISTER NATIVE
AREA AREA AREA AREA
CLASSES OBJECTS THREADS REGISTER VARIABLES THREADS

EXECUTION ENGINE
After compilation of [.java] file, compiler generates the bytecode or java program files. Number of
[.class] files are generated depending upon the number of classes in the [.java] program. The Class
Loader loads all the [.class] files in the JVM. All JVMs include 1 class loader that is embedded in
the virtual machine.

CLASS LOADER:
1. Loading: Loads all the [.class] files from system into JVM. If a [.class] file is not found, it raises
exceptions like: ClassNotFoundException
NoClassDefinitionFoundException
a. Bootstrap class loader: Bootstrap ClassLoader is responsible for loading
standard JDK class files from rt.jar and it is parent of all class loaders in Java.
Path of the loader: C:\Program Files\Java\jdk1.8.0_201\jre\lib

b. Extension class loader: Extension ClassLoader delegates class loading


request to its parent, Bootstrap and if unsuccessful, loads class
form jre/lib/ext directory or any other directory pointed by java.ext.dirs system
property.
Path of the loader: C:\Program Files\Java\jdk1.8.0_201\jre\lib\ext
Page 18 of 108
c. Application class loader: Application class loader is responsible for loading
application specific classes from CLASSPATH environment variable.

2. Linking: It has 3 parts:


a. Verify: ByteCode verifier verifies original bytecode. It never executes
bytecode directly.
b. Prepare: It initializes all the static members to their default values.
c. Resolve: It resolves/ unresolves symbolic reference to method or original code.

3. Initialisation: All static members are initialized to their original values.

MEMORY:
1. Method Area : It is the class memory, where all static members are allocated memory.
2. Heap Area : Objects and Non-static members are allocated memory here.
3. Stack Area : All local members, methods (main) and garbage collector are allocated
memory here.
4. Native Area : Native methods are allocated memory here.
5. PC Register : According to multiple threads, multiple PC registers are created which hold
address of current execution of instruction.

After memory management, JVM executes bytecode through execution engine.


Execution engine contains both JIT compiler and interpreter.

JIT COMPILER: ( JIT : JUST-IN-TIME )


It is used for performance enhancement IN Java program. Sometimes, execution engine needs
some native library. For that, it uses some interface, i.e. Java Interface.

INPUT FROM KEYBOARD:


Scanner class: 1. Pre-defined class
2. Available in java.lang package

Syntax: Scanner scanner_name = new Scanner(System.in);


Eg: Scanner sc = new Scanner(System.in);

Use of Scanner object:


a. char char c = sc.next().charAt(0);
b. byte byte b = sc.nextByte();
c. short short s = sc.nextShort();
d. int int i = sc.nextInt();
e. long long L = sc.nextLong();
f. float float f = sc.nextFloat();
g. double double d =sc.nextDouble();
h. boolean boolean b = sc.nextBoolean();
i. String String s = sc.next(); OR String s = sc.nextLine();

Page 19 of 108
Q1: Input two numbers and interchange them using XOR operator.
Ans:

Q2: Convert given temperature from Fahrenheit to Celsius.


Ans:

Page 20 of 108
Q3: Input the radius of a circle, length and breadth of a rectangle and find the areas.
Ans:

Q4: Input two numbers and interchange them using a third variable.
Ans:

Page 21 of 108
08 JUNE 2019 HK

CONDITIONAL STATEMENTS:
1. if

Syntax:
if ( condition/ boolean )
{
//statements
}

If the condition/ Boolean is evaluated as “true”, then, the statements in the if-block will be
executed.

Example-1: if(10>5)
{
System.out.println(“10 is greater than 5.”);
}
Example-2: if(true)
{
System.out.println(“the condition is true !!”);
}

Note: If the if-block contains only one statement, then the parenthesis are not necessary.

Example-3: if(10>5)
System.out.println(“No parenthesis !!”);

2. if – else

Sysntax:
if ( condition/ boolean)
{
//statement_block-1
}
else
{
//statement_block-2
}
If the condition/ Boolean is evaluated as “true”, then, the statement_block-1 will be executed.
If the condition/ Boolean is evaluated as “false”, then, the statement_block-2 will be executed.

Note:
Ex: if(1==1)
System.out.println(“1”);
System.out.println(“2”);
else
System.out.println(“1”);

Here, a compile time error occurs as : “misplaced else”

Page 22 of 108
3. Multiple if ( if – else ladder )

syntax:
if(cond_1)
{
//statements_1
}
else if(cond_2)
{
//statements_2
}
else if(cond_3)
{
//statements_3
}
else if(cond_4)



else if(cond_n)
{
//statements_n
}
else
{
//statements_e
}
The compiler checks the first condition, cond_1. If cond_1 is evaluated as true, it executes the
statements within the following block, statements_1. But if cond_1 is evaluated false, it goes to
next if condition, cond_2 in the else part of the first condition. Likewise, it checks every condition
till a condition is evaluated true. If all the conditions are evaluated as false, then final else block
statements, statements_e will get executed.

4. Nested if
Syntax:
if(cond_11)
{
if(cond_12)
{
if(cond_1n)
{
//statements
}
else
{
//statements
}
}
else
{
//statements
}
Page 23 of 108
}
else
{
if(cond_21)
{
if(cond_22)
{
if(cond_2m)
{
//statements
}
}

Here, if cond_11 is evaluated true, control moves to inner condition, cond_12 and so on till
the conditions are evaluated as true. When the condition is evaluated as false, the control
moves to the else part of the if statement, if exists. If cond_11 is evaluated false, then the
control moves to else part and checks for cond_21. And the same process follows and the
control moves deeper into the block till the conditions are evaluated as true.

Q1: Input a number and display whether the number is odd or even.
Ans:

Page 24 of 108
Q2: Input two numbers and display the greatest one.
Ans:

Q3: Input a year and display if the year is a leap year or not. Use logical operators. (&& , || , ! ).
Ans:

Page 25 of 108
Q4: Input a character and check if it is a vowel or not.
Ans:

Q5: Input 3 numbers and find the greatest among them.


Ans:

Page 26 of 108
Q6: Input five numbers and display them.
Ans:

Q7: Input two numbers and a choice.


If choice is 1, then display the sum.
2, then display the difference.
3, then display the product.
4, then display the quotient.
Ans:

Page 27 of 108
Q8: Input a number and a choice.
If choice is 1, then display whether the number is +ve, -ve or zero.
2, then display whether the number is odd or even.
Ans:

Q9: Input student grade.


If age>=25 and grade is A The person is eligible for post.
age>=25 but grade not A The person is not eligible for post.
age<25 Invalid age.
Ans:

Page 28 of 108
5. switch STATEMENT

Syntax:
switch(int/char)
{
case 1 : //statements_1; break;
case 2 : //statements_2;break;
case 3 : //statements_3;break;
.
.
.
case n : //statements_n;break;
default : //statements_d
}

Here, the integer/ character written in the brackets of switch statement is checked for EQUALITY
with the values in the cases. The cases may not be sorted. The default statement can be placed
anywhere within switch block. Only values can be used in case statements for equality check.
When the integer/ character is successfully matched with any of the test case values, the control
moves to the statement block and executes all the statements even in other test cases till either
break statement is encountered or end of block. Block statement is optional. The break
statement in last case is not necessary if there is no default statement.

Ex-1: int a=1;


switch(a)
{
case 1 : System.out.println(“1”);
case -1 : System.out.println(“-1”);
case 1000 : System.out.println(“1000”);
}

Output:
1
-1
1000

Ex-2: int a=1;


switch(a)
{
case 1 : System.out.println(“1”);break;
case -1 : System.out.println(“-1”);break;
case 1000 : System.out.println(“1000”);
}

Output:
1

Page 29 of 108
Ex-3: int a=1, b=1, c=-1, d=1000;
switch(a)
{
case c : System.out.println(“b”);
case b : System.out.println(“c”);
case d : System.out.println(“d”);
}
Output:
Error : non-values in case statements. Expected : values

Ex-4: int a=2;


switch(a)
{
case 1 : System.out.println(“1”);break;
case -1 : System.out.println(“-1”);break;
case 1000 : System.out.println(“1000”);break;
default : System.out.println(“default”);
}
Output:
default

Ex-5: int a=2;


switch(a)
{
case 1 : System.out.println(“1”);break;
default : System.out.println(“default”);break;
case -1 : System.out.println(“-1”);break;
case 1000 : System.out.println(“1000”);
}
Output:
default

Ex-6: int a=2, b=3;


switch(a>3)
{
case 1 : System.out.println(“1”);break;
case -1 : System.out.println(“-1”);break;
case 1000 : System.out.println(“1000”);break;
default : System.out.println(“default”);
}
Output:
Error : Expression in switch statement. Expected : value

Ex-7: int a=2, b=3;


switch(a)
{
case a>b : System.out.println(“1”);break;
case -1 : System.out.println(“-1”);break;
case 1000 : System.out.println(“1000”);break;
default : System.out.println(“default”);
}
Output:
Error : Expression in case statement. Expected : value
Page 30 of 108
Ex-8: boolean b=true;
switch(b)
{
case true : System.out.println(“true”);break;
case false : System.out.println(“false”);break;
default : System.out.println(“default”);
}

Output:
Error : only integer and character variables are allowed in switch statement.

Ex-9: switch(1)
{
case 1 : System.out.println(“1”);break;
case -1 : System.out.println(“-1”);break;
case 1000 : System.out.println(“1000”);
}

Output:
1

ITERATION/ LOOP CONTROL STATEMENTS:


for while do ... while

for AND while LOOPS ARE CALLED ENTRY-CONTROLLED LOOPS.


do...while LOOP IS CALLED EXIT-CONTROLLED LOOP

1. for LOOP:

Syntax:
for(initialization; condition; updatation)
{
//statements
}
Ex:
for(int i=1; i<=5; i++)
System.out.println(i);

Output:
1
2
3
4
5

2. while LOOP:

Syntax:
initialization;
while(condition)
{
//statements and updatation
}
Page 31 of 108
Ex:
int i=1;
while(i<=5)
{
System.out.println(i);
i++;
}

Output:
1
2
3
4
5

3. do...while LOOP:

Syntax:
initialization;
do{
//statements and updatation
}while(condition);

Ex: int i=1;


do{
System.out.println(i);
i++;
}while(i<=5);

Output:
1
2
3
4
5

Note: The do...while block will be executed at least once even if the condition is false from
beginning.

NESTING OF LOOPS:
A loop within another is called nesting of loop.
Ex: for(int i=1;i<=5;i++)
for(int j=1;j<=5;j++)
System.out.print(i+j+” “);
Output:
2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9 6 7 8 9 10

INFINITE LOOP:
A loop that iterates forever is called an infinite loop.
Applications: 1. Gaming
2. Antivirus
Ex: for( ; ; ) while(true) do{
{ } { } }while(true);
Page 32 of 108
Q1: Write a program to print the following pattern:
11115
222210
333315 ...
Ans:

Q2: Write a program to print the following pattern:


54321
5432
543
54
5
Ans:

Page 33 of 108
Q3: Write a program to print the following pattern:
12345
1234
123
12
1
Ans:

Q4: Write a program to print the following pattern:


*
**
***
****
*****
Ans:

Page 34 of 108
Q5: Write a program to print the following pattern:
1
22
333
4444
55555
Ans:

Q6: Write a program to print the following pattern:


*
***
*****
***
*
Ans:

Page 35 of 108
Q7: Write a program to print all prime numbers from 1 to n.
Ans:

Q8: Write a program to print the following pattern:


1
23
456
7 8 9 10
11 12 13 14 15
Ans:

Page 36 of 108
11 JUNE 2019 HK

Q1: Input a number and check whether the number is Armstrong number or not.
Ans:

Q2: Input a number and check whether the number is palindrome or not.
Ans:

Page 37 of 108
Q3: Write a program to print Fibonacci series.
Ans:

Q4: Input some values and print their sum.


Ans:

Page 38 of 108
Q5: Input 5 numbers into an array and find the smallest and largest.
Ans:

Q6: Convert decimal to binary.


Ans:

Page 39 of 108
Q7: Input five numbers in an array. Display the value in ascending order.
Ans:

Q8: Write a program to search a particular element in an array.


Ans:

Page 40 of 108
Q9: Write a program to delete an element from an array.
Ans:

ARRAY
1. It is a collection of similar types of data.
2. It is called linear data structure.
3. It allocates contiguous memory locations.
4. Indexing starts from zero(0).

TYPES OF ARRAY:
a. Single Dimensional Array:
Syntax: datatype name[] = new datatype[size];
Ex: int a[] = new int[10];

b. Multidimensional Array:
Syntax: datatype name[][] = new datatype[row_size][col_size];
Ex: int a[][] = new int[5][5];

Page 41 of 108
COMMAND LINE ARGUMENT

The Java command line arguments are the argument passed at the time of execution. These arguments
are received from the console directly and can be used as an input.

The args[] receives the arguments passed in the console


class r using command line argument.
{
public static void main(String args[])
{
System.out.println(“Command Line Argument.”);
}
}

NOTE:
1. The arguments passed in the console can be accessed using the args[] variable.

2. The arguments are by default treated as strings, and required to be converted into other datatypes
for specific operations.

Page 42 of 108
LENGTH PROPERTY:
length is a property used to find number of elements in an array of unknown size.
Syntax : int var = arr_name.length;
Ex: int len = myArray.length;
Example:

PARSING:
It is a method of converting a string to another datatype.
Syntax: datatype var = wrapper_class.parseDatatype(string_variable);
Ex: int a = Integer.parseInteger(args[0]); //in netbeans
int a = Integer.parseInt(args[0]); //in Java 1.8(Notepad)
Example:

Page 43 of 108
valueOf() FUNCTION:
This method is present in all Wrapper classes except java.lang.Boolean.
This method is similar to parse method.
Syntax: datatype var = Wrapper_class.valueOf(string_variable);
Ex: int d = Integer.valueOf(“5”);
Example:

for-EACH LOOP:
This loop is used when the size of the collection is not known.
This loop can be used only for accessing and modifying every element of the collection.
Syntax: for(datatype var : collection_name)
{ //statements }
Example:

Page 44 of 108
12 JUNE 2019 HK

JAGGED ARRAY:

An array within array is called jagged array.


It is like a 2-D array, except the fact that number of columns can be different in different rows.

2-D Array Jagged Array

Syntax: datatype var[][] = new datatype[row][];


var[0] = new datatype[col_1];
.
.
.
var[row-1] = new datatype[col_n];

Example:

Page 45 of 108
STRINGS
String is basically an object that represents sequence of character values.
An array of character works same as Java String.

METHODS TO CREATE STRINGS:


1. Using String literal:
Syntax: String var = “string literal”;
Example: String s1 = “abcd”;

2. Using ‘new’ keyword:


Syntax: String var = new String(“string literal”);
Example: String s2 = new String(“abcd”);

Difference in the two methods:


The variables created using literals having same literal values have same references and
hashCodes. The variables created using new keyword having same literal values have same hashCodes
but different references.

STRING CONSTANT POOL:


Each time you create a string literal, JVM checks the String Literal Pool for existence of the literal.
If the string literal already exists, then a reference to the pooled instance is returned.
If the string literal doesn’t exist, then a new string instance is created and the reference to that new object is
returned.

== vs equals() vs hashCode() for comparing strings:

== : It checks if the reference of two variables are equal.


equals() : It checks if the value of the literals in two variables are equal.
hashCode() : It is used to find the memory location of the literal.

Example to show the difference:

Page 46 of 108
Explanation:
1. When ‘a’ was created with value “x”, a new literal constant “x” was created in String Constant Pool,
and the reference was returned.
2. When ‘b’ was created with same value “x”, JVM searched the String Constant Pool. There already
a literal with same value was present. So, no new literal was created, rather, b was assigned the
same reference as ‘a’.
3. Variables ‘a’ and ‘b’ have been created using string literals, hence, comparing:
a. a==b true Same reference
b. a.equals(b) true Same values of literals
c. a.hashCode()==b.hashCode() true Same address of literals
4. When value of ‘a’ was changed from “x” to “xy”, a new literal was created in String Constant Pool
and the reference was returned. Hence, the reference is changed. The value is also changed to
“xy”. And lastly, as a new literal is created, and allotted a different memory, the hashCode too
changes from the initial values. Now, ‘b’ is the initial copy of ‘a’. Now, comparing:
a. a==b false Different references
b. a.equals(b) false Different values of literals
c. a.hashCode()==b.hashCode() false Different address of literals
5. Now, using the new keyword, ‘c’ and ‘d’ are created with values “x” each. As this literal is already
present in the String Constant Pool, no new literal is created, hence both hashCodes are same. But
as they are created using new keyword, they have different references. And lastly, they both have
same values. Now comparing:
a. c==d false Different references
b. c.equals(d) true Same values of literals
c. c.hashCode()==d.hashCode() true Same address of literals
6. When value of ‘c’ was changed from “x” to “xy”, a new literal was not created in String Constant
Pool and the previous reference of ‘a’ was returned. Hence, the reference of ‘c’ is changed. The
value is also changed to “xy”. And lastly, as the value of the string is changed being allotted a
different memory, the hashCode too changes from the initial values. Now, ‘d’ is the initial copy of
‘c’. Now, comparing:
a. c==d false Different references, like earlier
b. c.equals(d) false Different values of literals
c. c.hashCode()==d.hashCode() false Different address of literals
7. Two new variables ‘g’ and ‘h’ are created with values “xy” and “x y”. ‘g’ has value that already
exists in String Constant Pool. So, the same hashCode of ‘a’ and ‘c’ is allotted to it. But as it is
created using new keyword, this has a different reference with respect to that stored in ‘a’ or ‘c’.

Note:
1. If two String objects have same literal values, then their hashCodes must be same. Reverse is not
true.
2. If two objects have same references, then their literal values must be same. Reverse is not true.

Page 47 of 108
STRING FUNCTIONS:
String str = “abcdef”; char ch[7];

1. length() : It is used to find the length(number of characters) of String literal.


Syntax:
int var = String_var.length();
Ex: int len = str.length(); //6

2. charAt() : It is used to get the character of string at specified position.


Syntax:
char var = String_var.charAt(pos); //pos  integer type
Ex: char ch = str.charAt(2); //c

3. getChars() : It is used to extract characters from one string and to store them in another.
Syntax:
char var[] = String_var.getChars(src_beg, src_end, dst, dst_beg);
src_beg : Beginning position in source String
src_end : Ending position in source string
dst : Destination string, where the substring is to be put
dst_beg : The starting position in Destination string where the substring is to be put
Ex : s.getChars(1, 3, ch, 4); //“ bc”

4. getBytes() : It is used to get the sequence of characters converted to bytes.


Syntax:
byte var[] = String_var.getBytes();
Ex : byte b[] = str.getBytes(); //{97,98,99,100,101,102}

5. compareTo() : compares two strings and returns the difference of first mis-match.
Syntax:
int var = str_1.compareTo(str_2);
Note: difference value = chr_1 – chr_2
where chr_1 is the character in str_1 where first mis-match occurs.
and chr_2 is the character in str_2 where first mis-match occurs.
Ex : int diff = “abcd”.compareTo(“ABCD”); //‘a’ – ‘A’ = 32
int dif = “aBCD”.compareTo(“abcd”); //‘B’ – ‘b’ = -32
int d = “abcd”.compareTo(“abcd”); //‘a’ – ‘a’ = 0

6. equalsIgnoreCase() : Compares two string values ignoring the case.


Syntax:
boolean var = String_1.equalsIgnoreCase(String_2);
Ex : boolean f = str.equalsIgnoreCase(“AbCdEf”); //true
boolean t = “abcd”.equalsIgnoreCase(“ABCD”); //true

(To Be Continued...)

Page 48 of 108
13 JUNE 2019 HK

STRING FUNCTIONS: (continued)

7. startsWith() : Checks whether the given string starts at the given position in parent string.
It matches whole sub-string in the parent string, not just first character.
Syntax:
boolean var = parent_str.startsWith(sub_str,pos);
Ex : boolean b1 = “abcd”.startsWith(“abd”,0); //false
boolean b2 = “abcd”.startsWith(“abc”,0); //true

8. indexOf() : It returns the first index of the character/ sub-string to be searched.


It returns -1 if the character/ sub-string is not found in parent-string.
Syntax:
int var = parent_str.indexOf(character or sub_str);
Ex : int a = “acbdb”.indexOf(‘b’); //2
int b = “abcbd”.indexOf(“bc”); //1
int c = “abcdb”.indexOf(“bd”); //-1

9. lastIndexOf() : It returns the first index of the character/ sub-string to be searched.


It returns -1 if the character/ sub-string is not found in parent-string.
Syntax:
int var = parent_str.lastIndexOf(character or sub_str);
Ex : int a = “abcbd”.lastIndexOf(‘b’); //3
int b = “abbcbd”.lastIndexOf(“bc”); //2
int c = “abcdb”.lastIndexOf(“bd”); //-1

10. concat() : It concatenates the given string at the end of parent-string.


Syntax:
String var = parent_str.concat(sub_str);
Ex : String str1 = “abcd”.concat(“e”); //“abcde”

11. toLowerCase() : It returns a string after converting the parent string into lower case.
Syntax:
String var = parent_str.toLowerCase();
Ex : String str1 = “AbCdEf”.toLowerCase(); //“abcdef”

12. toUpperCase() : It returns a string after converting the parent string into upper case.
Syntax:
String var = parent_str.toUpperCase();
Ex : String str1 = “AbCdEf”.toUpperCase(); //“ABCDEF”

13. toCharArray() : It returns the sequence of characters in the string.


Syntax:
char var[] = str_var.toCharArray();
Ex : char ch[] = “abcd”.toCharArray(); //{‘a’,‘b’,‘c’,‘d’}

Page 49 of 108
14. split() : It returns an array of sub-strings, which are the parts of parent-string, split at
specified characters.
Syntax:
String var[] = parent_str.split(character);
Ex : String str[] = “a b c d”.split(“ ”); //{“a”,“b”,“c”,“d”}
String str[] = “a-b-c-d”.split(“-”); //{“a”,“b”,“c”,“d”}
String str[] = “arbrcrd”.split(“r”); //{“a”,“b”,“c”,“d”}

15. replace() : It is used to replace all occurrences of old_chr or old-str with new_chr or new_str.
Syntax:
String var = parent_string.replace(old_chr/old_str , new_chr/new_str);
Ex : String str1 = “abede”.replace(‘e’,‘c’); //“abcdc”
String str2 = “abyfy”.replace(“y”,“cde”); //“abcdefcde”
Note: Only a chr can replace another chr. Similarly, only a str can replace another str.

16. replaceAll() : It replaces all occurrences of old-string with new_str.


Syntax:
String var = parent_str.replaceAll(old_str, new_str);
Ex : String str1 = “acbcdc”.replaceAll(“c”,“ab”); //“aabbabdab”

17. replaceFirst() : It replaces only the first occurrence of old_str with new_str.
Syntax:
String var = parent_str.replaceFirst(old_str, new_str);
Ex : String str1 = “acbcdc”.replaceFirst(“c”,“ab”); //“aabbcdc”

18. trim() : It removes all the extra spaces from both sides of a string.
Syntax:
String var = parent_str.trim();
Ex : String str1 = “ a b c d ”.trim(); //“a b c d”
Note: It doesn’t removes spaces between alpha-numeric characters.

19. contains() : It checks if the parent string contains the given sub-string or not.
Syntax:
boolean var = parent_str.contains(sub_str);
Ex : boolean b1 = “abcdef”.contains(“bcd”); //true
boolean b2 = “abcdef”.contains(“bdc”); //false

20. substring() : It returns a part of the parent string.


Syntax:
String var = parent_str.substring(start_pos);
String var = parent_str.substring(start_pos, end_pos);
Ex : String str1 = “abcdef”.substring(2); //“cdef”
String str2 = “abcdef”.substring(2,4); //“cd”
Note: The character at end_pos position is excluded.

21. isEmpty() : It checks if the string is empty or not.


Syntax:
boolean var = str.isEmpty();
Ex : boolean b1 = “abc”.isEmpty(); //false
boolean b2 = “”.isEmpty(); //true

Page 50 of 108
MUTABLE and IMMUTABLE OBJECTS:

IMMUTABLE OBJECTS MUTABLE OBJECTS


1. Here, the value cannot be changed. 1. Here, the value can be changed.
2. A new value should be assigned to 2. The existing value is modified, and no value is
the variable to change its value. assigned again.
Ex: all primitive datatypes, String, Ex: StringBuffer, StringBuilder

STRINGBUFFER CLASS:
StringBuffer class is similar to the String class which provides much functionality than the String class.
A StringBuffer class object is a growable and writable character sequence.

Declaration Syntax:

1. StringBuffer var = new StringBuffer();


var.append(str);
2. StringBuffer var = new StringBuffer(str);

Note : Method_1 is preferred over Method_2.

StringBuffer FUNCTIONS:

StringBuffer sb1 = new StringBuffer(); sb1.append(“123”);


StringBuffer sb2 = new StringBuffer(“123”);
StringBuffer sb3 = new StringBuffer(“123218”);
char ch[7];

1. length() : It returns the length of the string literal stored in it.


Ex:
int var = sb1.length(); //3

2. capacity() : It returns the maximum number of characters which can be stored in it.
Ex:
int var1 = sb1.capacity(); //16
int var2 = sb2.capacity(); //19

Note: The default value of capacity is 16, (if declared according to Method_1);
While using Method_2, capacity is initialized with 16+length_of_agrument.

Note: The capacity increment is automatic and follows a particular pattern:


new_capacity = (old_capacity * 2) + 2

3. ensureCapacity(): It increases the capacity according to the pattern, till it is greater than or
equal to the required capacity.
Syntax:
strbfr.ensureCapacity(cap);
Ex : sb1.ensureCapacity(18); //capacity of sb1 = 34

Page 51 of 108
4. charAt() : It returns the character at a specified position.
Syntax:
char var = SB_var.charAt(pos);
Ex : char ch = sb1.charAt(0); //1

5. getChars() : It is used to extract characters from one string and to store them in another.
Syntax:
char var[] = SB_var.getChars(src_beg, src_end, dst, dst_beg);
src_beg : Beginning position in source String
src_end : Ending position in source string
dst : Destination string, where the substring is to be put
dst_beg : The starting position in Destination string where the substring is to be put
Ex : sb1.getChars(0, 2, ch, 4); //“ 12”

6. append() : It is used to add characters at the end of existing string literal in StringBuffer object.
Syntax:
SB_var.append(any_datatype);
Ex : sb1.append(true); //“123true”
sb1.append(“true”); //“123true”
sb1.append(‘a’); //“123a”
sb1.append(1); //“1231”
sb1.append(1.0); //“1231.0”
...

7. delete() : It is used to delete characters from the literal.


Syntax:
SB_var.delete(start_pos, end_pos);
Ex : sb1.delete(0,2); //“3”
Note: end_pos character is excluded.

8. deleteCharAt() : It is used to delete only the character at the specified position.


Syntax:
SB_var.deleteCharAt(pos);
Ex : sb1.deleteCharAt(1); //“13”

9. replace() : It is used to replace a sub-string with given sub-string.


Syntax:
SB_var.replace(start_pos, end_pos, str);
Ex : sb1.replace(0,2,“ab”); //“ab3”

10. substring() : It is used to get a sub-string from the parent-string.


Syntax:
SB_var.substring(start_pos);
SB_var.substring(start_pos, end_pos);
Ex : sb1.substring(1); //“23”
sb1.substring(0,2); //“12”

Page 52 of 108
11. insert() : It is used to insert character(s) at any position in the literal.
Syntax:
SB_var.insert(pos, any_datatype);
Ex : sb1.insert(1,true); //“1true23”
sb1.insert(1,8); //“1823”
. . .

12. indexOf() : It returns the index of first occurrence of a string.


Syntax:
int var = SB_var.indexOf(sub_str);
Ex : int d1 = sb1.indexOf(“12”); //0
int d2 = sb1.indexOf(“23”); //1
int d3 = sb1.indexOf(“13”); //-1

13. lastIndexOf() : It returns the index of last occurrence of a string.


Syntax:
int var = SB_var.lastIndexOf(sub_str);
Ex : int d = sb3.lastIndexOf(“2”); //3

14. reverse() : It reverses the content of a StringBuffer.


Syntax:
SB_var.reverse();
Ex : sb1.reverse(); //“321”

15. setCharAt() : It sets the given character at the specified position.


Syntax:
SB_var.setCharAt(pos,chr);
Ex : sb1.setCharAt(0,‘a’); //“a23”

CLASS FUNDAMENTALS:
Java is a class-based programming language.

Defining a class :
class Class_name
{
static variables
static methods
constructor(s)
instance variables/ non-static variables
instance methods/ non-static methods
}

Method:
1. It is a self-content part of program which executes to perform a specific task.
2. Due to methods, program support modularization, where a large program is divided into smaller
sub-programs.

Advantages of methods:
1. Errors can be easily detected and corrected.
2. Ease to access code.
3. Program time complexity reduces due to execution of certain parts instead of whole program.
Page 53 of 108
Parts of a function/ method:
1. Declaration: It is the prototype which informs the compiler of the existence of the function.
Syntax:
access_specifier return_type function_name(arg_type_list);

2. Defination: It is the function body which contains executable code.


Syntax:
access_specifier return_type function_name(arg_list)
{
//function body
}

3. Call: It is the process of accessing the function and its functionality.


Syntax:
return_type var = function_name(arg_list);

Types of Methods:
1. static: These methods are declared using the keyword “static”.
a. These can be accessed using class-name, object-name.
b. These can also be accessed with direct function-name, but only within same class.
c. These are called class-level methods.
d. These can be accessed even before object creation.
e. A static method can access static variable and other static methods directly.
f. A static method cannot access instance variable/ instance method without object creation.

Page 54 of 108
17 JUNE 2019 HK

2. non-static: These methods are declared without using any “static” keyword.
a. These can only be accessed using object-name.
b. These are called object-level methods.
c. These can be accessed using objects, and hence, cannot be used before object creation.
d. An instance method can access all members of the class (static/ instance variable/ method).
e. These are allocated memory in heap area.

DATA-MEMBERS/ VARIABLES OF CLASS:

TYPES OF VARIABLES:
1. Local: These are the variables declared in methods, constructors, static blocks etc.
a. These are temporary.
b. They are created when their declaration is encountered.
c. These are created to meet the temporary requirements of users like loop variables.
d. These are stored in stacks.
e. These get destroyed when execution of their block ends.
f. These have higher priority than instance and static variables.

2. Instance: These are the variables declared in the class, without the use of “static” keyword.
a. The values of these variables can vary from object to object.
b. For every object, a separate copy of variable is created.
c. These can be initialized during class declaration.
d. These are created during object creation.
e. These are allocated memory in the heap area.
f. These are destroyed along with the object.

3. static: These are the variables declared in the class, using the “static” keyword.
a. The values are same for every object.
b. These are class-level members, declared using “static” keyword.
c. These are created at the time of loading the class in the ClassLoader.
d. These are destroyed at the end of program.
e. These can be initialized. If not initialized, they are initialized with the default values.
f. These can be accessed using object-name, class-name.
g. These can be accessed directly, only within same class.

Page 55 of 108
this KEYWORD:
When instance variable name and local variable names are same, the access priority will be given
to the local variable. To access the instance variable, we use the “this” keyword.
Example:

METHOD OVERLOADING:
This is a concept of polymorphism.
Here, same function is declared multiple times, having different argument lists.
Example:

Page 56 of 108
18 JUNE 2019 HK

CONSTRUCTOR:
1. It is a member function whose name is same as the class-name.
2. It doesn’t have a return type.
3. It is used to initialize the data members.
4. When an object is created, this is automatically called.
5. Other than initialization, any other task can also be done using it.
6. Instance initialization blocks (non-static blocks) are executed before the constructors.

TYPES OF CONSTRUCTORS:
1. Default constructor:
a. It takes no arguments.
Syntax:
class_name()
{
//statements
}
Ex : class Demo
{
Demo()
{
System.out.println(“Hi”);
}
public static void main(String args[])
{
Demo d = new Demo();
}
}
Output:
Hi

2. Parameterized constructor:
a. It takes argument.
Syntax:
class_name(arg_list)
{
//statements
}
Ex : class Demo
{
Demo(int i)
{
System.out.println(“Hi”+i);
}
public static void main(String args[])
{
Demo d = new Demo(5);
}
}
Output:
Hi5

Page 57 of 108
Note : If there is no constructor provided by the user, JVM automatically provides a default constructor.
The constructor provided by JVM contains only one statement in it : super();

Programmer’s Code Compiler’s Code


class Demo class Demo
{ {
Demo()
} {
super();
}
}
public class Demo public class Demo
{ {
public Demo()
} {
super();
}
}
class Demo class Demo
{ {
Demo(int i) Demo(int i)
{ {
super();
} }
} }
class Demo class Demo
{ {
Demo(int i) Demo(int i)
{ {
super(); super();
} }
} } //No change
class Demo class Demo
{ {
Demo() Demo()
{ {
super();
} }
} }
class Demo class Demo
{ {
Demo() Demo()
{ {
super();
} }
Demo(int i) Demo(int i)
{ {
super();
} }
} }

Page 58 of 108
class Demo class Demo
{ {
Demo() Demo()
{ {
this(10); this(10); //No change
} }
Demo(int i) Demo(int i)
{ {
super();
} }
} }
class Demo class Demo
{ {
Demo() Demo()
{ {
this(10); this(10); //No change
} }
Demo(int i) Demo(int i)
{ {
super(); super(); //No change
} }
} }
class Demo class Demo
{ {
Demo() Demo()
{ {
super(); super(); //No change
} }
Demo(int i) Demo(int i)
{ {
super(); super(); //No change
} }
} }
class Demo class Demo
{ {
Demo() Demo()
{ {
this(); this(); //No change
} }
} }
//ERROR: Recursive constructor invocation
//this() again calls Demo()
class Demo class Demo
{ {
Demo() Demo()
{ {
this(10); this(10); //No change
} }
Demo(int i) Demo(int i)
{ {
this(); this(); //No change
} }
} }
//ERROR: Recursive constructor invocation
//this() calls Demo() AND
//this(10) calls Demo(int), forms cycle.
Page 59 of 108
class Demo class Demo
{ {
Demo() Demo()
{ {
System.out.println(“hi”); System.out.println(“hi”);
super(); super();
} }
} }
//ERROR: super() must be first statement
class Demo class Demo
{ {
Demo(int i) Demo(int i)
{ {
System.out.println(“hi”); System.out.println(“hi”);
this(); this();
} }
} }
//ERROR: this() must be first statement
class Demo class Demo
{ {
Demo(int i) Demo(int i)
{ {
this(); this();
super(); super();
} }
} }
//ERROR: super() must be first statement
//this() and super

this & super VS this() & super():

this & super this() & super()


These are keywords, used to refer the current These are calls to current class constructor and
class instance and super class instance. super class constructor.
These can be used anywhere except the static These can be used in the constructor(s), only as
area. first statement.
These can appear in same block, even more than These cannot appear in same constructor.
once.

Page 60 of 108
19 JUNE 2019 HK

BLOCKS IN JAVA:

Block is a group of related statements. Generally, blocks refer to the group of statements exterior to
all functions.

TYPES OF BLOCKS:
1. static: Any block declared using the keyword “static” is known as a static block.
a. These are class-level blocks.
b. Class related codes are implemented inside it.
c. It do not allows the non-static references, i.e., this and super.
d. It is executed implicitly when class is loaded in class loader.
e. It is allocated memory from method area.
f. If multiple blocks static blocks are declared, all the blocks are executed according to the
declaration order.

2. non-static: Any block declared without using the keyword “static” is known as a non-static block.
a. These are object-level blocks.
b. These execute according to object behavior or pre-task.
c. These are executed at the time of object creation, just before constructor execution.
d. If multiple blocks are declared, all blocks are executed according to the declaration order.
e. A non-static block which is used to initialize the data-members is known as the Instance
Initialization Block (IIB).

Example:

Note: Static blocks got executed even when no object is created.

Page 61 of 108
Order of execution:
1. static blocks
2. non-static blocks
3. constructor

INHERITANCE:
Generating a new class from existing class with acquiring all the properties of existing class into new class
is called Inheritance.
The existing class is called: parent-class OR super-class OR base-class
The new class is called: child-class OR sub-class OR derived-class

TYPES OF INHERITANCE:
1. Single:
PARENT_CLASS

CHILD_CLASS
2. Hierarchical:
PARENT_CLASS

CHILD_1 CHILD_2
3. Multilevel:
PARENT_CLASS

INTERMEDIATE_PARENT_CLASS

CHILD_CLASS
Page 62 of 108
4. Muliple: [NOT ALLOWED IN JAVA USING CLASS] [INTERFACE CONCEPT]
5. Hybrid: [NOT ALLOWED IN JAVA USING CLASS] [INTERFACE CONCEPT]

extends AND implements KEYWORDS:

class interface interface


↓ extends ↓ extends ↓ implements
class interface class

extends: It is used when one class is inherited from another class or when one interface is inherited
from another.

implements: It is used when one class is inherited from one interface.

Note: A class can be inherited from an interface, but reverse is illegal (invalid).

IMPORTANT POINTS OF INHERITANCE:

Sl. Base class can be accessed by can be accessed


No. member derived class by derived class
specifier member ? object ?
1 public YES YES
2 default YES YES
3 private NO NO
4 protected YES YES

Note:
1. Except Object class, which has no super-class, every class has one and only one direct super-
class.
2. In the absence of any other explicit super-class, every class is implicitly a subclass of Object class.
3. A super-class can have any number of sub-classes.
4. A class can have only one super-class, because Java doesn’t support multiple inheritance.
5. Constructor(s) of base class are not inherited, but they can be invoked from derived-class.
6. Private members of base class are not inherited. But the public and protected member functions of
base class can access the private members of the base-class.

Page 63 of 108
SINGLE INHERITANCE:

Structure: parent_class

child_class

Java equivalent code:

class Parent_class
{
//parent_class definition
}

class Child_class extends Parent_class


{
//child_class definition
}

Example of SINGLE INHERITANCE:

Page 64 of 108
MULTILEVEL INHEERITANCE:

Structure: parent_class

intermediate_parent

child_class

Java equivalent code:

class parent_class
{
//parent_class definition
}

class intermediate_parent extends parent_class


{
//intermediate_parent definition
}

class child_class extends intermediate_parent


{
//child_class definition
}

Example of MULTILEVEL INHERITANCE:

Page 65 of 108
HIERARCHICAL INHERITANCE:

Structure: parent_class

child_class_1 child_class_2

Java equivalent code:

class parent_class
{
//parent_class definition
}

class child_class_1 extends parent_class


{
//child_class_1 definition
}

class child_class_2 extends parent_class


{
//child_class_2 definition
}

Example of HIERARCHICAL INHERITANCE:

Page 66 of 108
CONSTRUCTOR CALL ORDER IN MULTILEVEL INHERITENCE:

The constructor of base class executes before the execution of derived class constructor.

Example:

Page 67 of 108
20 JUNE 2019 HK

METHOD OVERRIDING:

 The child-class gets all the methods and properties of the parent-class.
 Sometimes, the child-class may not get satisfied with the parent-class’s method implementation.
 Then, the child is allowed to redefine the methods based on requirements.

Note:
 The parent-class method which has been redefined in the child-class, is called the overridden
method.
 The child-class method which redefines the parent-class method is called the overriding method.

Example:

METHOD OVERLOADING vs METHOD OVERRIDING:

SL.NO. PROPERTY OVER-LOADING OVER-RIDING


1 Method’s name must be same must be same
2 Argument list must be different must be same
3 Method signature may be different must be same
4 Return type No restriction must be same
5 private/ static/ final methods cannot be overloaded cannot be overridden

Page 68 of 108
INTERFACE:

1. It is a Java keyword using which Java supports 100% abstraction because all methods available are
by default abstract or public.
2. We cannot create objects of an interface directly.
3. We can declare object reference for interface.
4. An interface works like a skeleton of class where all reference or interface are implemented inside
child class.
5. All variables available inside interface are by default final.

Example:

Note:
1. obj1 is created using interface A’s reference and class B’s memory allocation(constructor).
2. obj2 is created using class B’s reference and class B’s memory allocation.
3. Both the ways of creating objects are legal and acceptable.

Page 69 of 108
MULTIPLE INHERITANCE:
Example:

Note: Even if the derived class inherits two functions with same prototype from two interfaces, it doesn’t
generate any error.

HYBRID INHERITANCE:

Example:

Page 70 of 108
final KEYWORD:
1. It is a keyword used as a modifier in java.
2. It is applicable for classes, methods and variables.
3. The variable’s value never changes when declared using final.
4. The method cannot be over-loaded or over-ridden which is declared as final.
5. A final class can’t be inherited.

Page 71 of 108
21 JUNE 2019 HK

ABSTRACT METHOD:
Syntax for declaring an abstract method:
abstract return_type func_name(arg_list);

1. An abstract method don’t have a body.


2. It cannot be called directly without overriding.
3. A class can have more than one abstract methods.
4. Only an abstract class can have abstract members.
5. Constructor(s) and static functions cannot be declared abstract.

ABSTRACT CLASS:
Syntax for declaring an abstract class:
abstract class class_name
{
//abstract methods and
//data members (instance & static) allowed
}

1. Abstract classes are incomplete.


2. Sub-classes must declare the missing pieces to become concrete classes from which we can create
objects.
3. The purpose of an abstract class is to provide appropriate super class from which other classes can
be inherited and share common design.
4. A class must be declared abstract if one or more member functions are declared abstract.
5. We cannot create objects of abstract classes directly without inheriting them.

Example:

Page 72 of 108
22 JUNE 2019 HK

ABSTRACT CLASS vs INTERFACE:

Sl.No. ABSTRACT CLASS INTERFACE


An abstract class can have both abstract and An interface can have only abstract methods.
1 non-abstract methods. Since Java 8, an interface can have default and
static methods as members also.
2 It doesn’t support multiple inheritance. It supports multiple inheritance.
It can have final, non-final, static, non-static It can have only static and final data members.
3
data members.
It can provide implementation to an interface. it can’t provide implementation to an abstract
4
class.
5 abstract keyword is used in declaration. interface keyword is used in declaration.
It can extend another Java class and can It can extend another Java interface only.
6
implement multiple Java interfaces.
It can be extended using extends keyword. It can be implemented using implements
7
keyword.
8 The members can be private and protected. The members are public by default.

ERROR vs EXCEPTION:

SL.NO. ERROR EXCEPTION


Recovering from error is not possible. We can recover from exceptions using
1 try-catch blocks or
by throwing exceptions back to caller
All errors in Java are of unchecked type. Exceptions include both checked and unchecked
2
types.
Errors are mostly caused by the Program itself is responsible for causing
3
environment in which program runs. exceptions.
Errors occur at runtime and are not known All exceptions occurs at runtime, but checked
4 to the compiler. exceptions are known to compiler, while
unchecked are not.
They are defined in java.lang.Error They are defined in java.lang.Exception
5
package. package.
Example(s) : Example(s) :

java.lang.StackOverflowError Checked Exceptions:


java.lang.OutOfMemoryError SQLException
IOException
6
Unchecked Exceptions:
ArrayIndexOutOfBoundException
NullPointerException
ArithmaticException

Note: Both java.lang.Error and java.lang.Exception are sub-classes of java.lang.Throwable.

Page 73 of 108
EXCEPTION:
An exception is an unwanted or unexpected event, which occurs during execution (run time) of a program,
which disrupts the normal flow of program’s instructions. Due to exceptions, program may terminate or
abort.Types of exceptions:
SL.NO. CHECKED EXCEPTION UNCHECKED EXCEPTION
1 These occurs at compile time. These occur at run-time.
2 These are called compile-time exceptions. These are called run-time exceptions.
3 These cannot be ignored during compilation. These can be ignored during compilation.

EXAMPLE OF CHECKED EXCEPTION:

EXAMPLE OF UNCHECKED EXCEPTION:

Page 74 of 108
try BLOCK:

try is a keyword used to define a block where all the code is written when there is a chance of exception.

Syntax:
try
{
//statements
}

catch BLOCK:

catch is a keyword used to define a block to handle the exceptions raised by the try block.
1. It always appears after try block.
2. The type of exception occurred in try block must match with the type of argument in the catch
block or to the super type.
3. For a single try block, multiple catch blocks may be defined.

Syntax:
catch(Exp_name var)
{
//statements
}

throw STATEMENT:

throw is a keyword used to explicitly throw an exception from any method or block of code.
Syntax:
throw Instance;
Ex : throw ArithmeticException(“/ by zero”);

throws STATEMENT:

throws is a keyword used in the signature (prototype) of a method to indicate that the method might throw
one of the listed type exceptions. The caller to these methods use try-catch block.

finally BLOCK:

finally is a keyword used to define a block which is guaranteed to execute whether exception occurs in
try block or not. A finally block always appears after try block.

Page 75 of 108
Example of basic try-catch-finally blocks:

Example of throw and throws statements:

Page 76 of 108
Note:
1. throws reports an exception even if no try block is used in the method.
2. throw reports an exception even if no exception practically exists.
3. finally is always executed, whether try block executes or catch block.

ILLEGAL WAYS OF USING try-catch-finally:

SL.NO. CODE COMPILE TIME ERRORS


try No error.
{
//statements
}
1
catch(Exception e)
{
//statements
}
try No error.
{
//statements
}
catch(ArithmeticException ae)
{
2
//statements
}
catch(Exception e)
{
//statements
}
try error: exception ArithmeticException
{ has already been caught.
//statements
}
catch(Exception e)
{
3
//statements
}
catch(ArithmeticException ae)
{
//statements
}
try No error.
{
//statements
}
catch(Exception e)
{
4
//statements
}
finally
{
//statements
}
Page 77 of 108
No error.
try
{
//statements
}
5
finally
{
//statements
}

error: 'try' without 'catch',


try 'finally' or resource declarations
{
//statements
}
try
{
6
//statements
}
catch(Exception e)
{
//statements
}

error: 'try' without 'catch',


try 'finally' or resource declarations
{
//statements
}
try
{
7
//statements
}
finally
{
//statements
}

No error.
try
{
//statements
}
catch(Exception e)
{
//statements
}
8
try
{
//statements
}
catch(Exception e)
{
//statements
}

Page 78 of 108
No error.
try
{
//statements
}

finally
{
//statements
}
9
try
{
//statements
}
finally
{
//statements
}

No error.
try
{
//statements
}
catch(Exception e)
{
//statements
}
10
try
{
//statements
}
finally
{
//statements
}

No error.
try
{
//statements
}
finally
{
//statements
}
11
try
{
//statements
}
catch(Exception e)
{
//statements
}

Page 79 of 108
No error.

try
{
//statements
}
catch(Exception e)
{
//statements
}
finally
{
//statements
12
}
try
{
//statements
}
finally
{
//statements
}

No error.

try
{
//statements
}
finally
{
//statements
}
try
{
13
//statements
}
catch(Exception e)
{
//statements
}
finally
{
//statements
}

Page 80 of 108
error: 'try' without 'catch',
'finally' or resource declarations

try
{
//statements
}
try
{
//statements
}
14
catch(Exception e)
{
//statements
}
finally
{
//statements
}

No error.
try
{
//statements
}
catch(Exception e)
{
//statements
}
finally
{
//statements
15 }
try
{
//statements
}
catch(Exception e)
{
//statements
}
finally
{
//statements
}
try error: 'try' without 'catch',
{ 'finally' or resource declarations
16 //statements
}

Page 81 of 108
catch(Exception e) error: 'catch' without 'try'
{
17
//statements
}
finally error: 'catch' without 'try'
{
18
//statements
}
try error: 'finally' without 'try'
{
//statements
}
catch(Exception e)
{
19 //statements
}
System.out.println(“hi”);
finally
{
//statements
}

Page 82 of 108
24 JUNE 2019 HK

FILE HANDLING:

FILE: When some data is to be stored permanently, the data is stored in files in secondary memory.
When a small amount of data is to be stored, file is recommended.
When a large amount of data is to be stored, database is recommended.

GENERAL FILE OPERATIONS:


1. File creation
2. Data writing (in file)
3. Data reading (from file)
4. Appending a file

CLASSES REQUIRED TO PERFORM OPERATIONS:


1. File
2. FileReader
3. FileWriter
4. BufferedReader
5. BufferedWriter
6. PrintWriter

File CLASS:
import java.io.File; //used to access the functions.
import java.io.IOException; //it is used with main() using the “throws” keyword
1. Constructor: Its used to create a logical file/directory.
Syntax:
1. File file_name = new File(String path_name);
Ex: File f1 = new File(“abcd”); //creates a new directory, logically
File f2 = new File(“x.txt”); //creates a new text file, logically

2. File file_name = new File(String parent, String child);


Ex: File f3 = new File(“C:\\temp”, “y.txt”);
//creates a new text file in given directory(C:\abcd)

3. File file_name = new File(File parent, String child);


Ex: File f4 = new File(f1, “z.txt”);
//creates a new file in the directory indicated by another File object

2. getAbsolutePath(): Used to get the full path of the file/ directory.


Syntax:
String var = file_obj.getAbsolutePath();
Ex: String s1 = f1.getAbsolutePath(); //C:\java1\rohnak\abcd
String s2 = f2.getAbsolutePath(); //C:\java1\x.txt
String s3 = f3.getAbsolutePath(); //C:\temp\y.txt
String s4 = f4.getAbsolutePath(); //C:\java1\rohnak\abcd\z.txt

3. canRead(): It returns true if file is readable, and returns false if file is not readable.
Syntax:
boolean var = file_obj.canRead();
Ex: boolean b1 = f1.canRead(); //true
Page 83 of 108
4. canWrite(): It checks if any data can be written in the file.
Syntax:
boolean var = file_obj.canWrite();
Ex: boolean b2 = f1.canWrite(); //true

5. exists(): It checks if the file/ directory exists physically.


Syntax:
boolean var = file_obj.exixts();
Ex: boolean b3 = f1.exists(); //false
boolean b4 = f2.exixts(); //false
Note: The file/ directory exists logically, not physically.

6. isDirectory(): It checks if the given path is a directory or not.


Syntax:
boolean var = file_obj.isDirectory();
Ex: boolean b5 = f1.isDirectory(); //false
boolean b6 = f2.isDirectory(); //false
Note: The file f1 is a directory, still shows false.
This is because, it checks for physical existence.

7. isFile(): It checks if the given path is a file or not.


Syntax:
boolean var = file_obj.isFile();
Ex: boolean b7 = f1.isFile(); //false
boolean b8 = f2.isFile(); //false
Note: The file f2 is a file, still shows false.
This is because, it checks for physical existence.

8. length(): It returns the number of characters in the file.


Syntax:
long var = file_obj.length();
Ex: long len = f1.length(); //0

9. createNewFile(): It generates the physical file of the logical entity of file defined by file object.
Syntax:
1. boolean var = file_obj.createNewFile();
2. file_obj.createNewFile();
Ex: boolean b9 = f2.createNewFile(); //true
f3.createNewFile();
boolean b10 = f2.createNewFile(); //false, file already exists
Note: true is returned if file is created successfully.
false is returned if file couldn’t be created or if file already exists.

Page 84 of 108
10. delete(): It deletes the file/ directory defined by the file object.
Syntax:
1. boolean var = file_obj.delete();
2. file_obj.delete();
Ex: boolean b11 = f2.delete(); //true
f3.delete();
boolean b12 = f2.delete(); //false, file already deleted
Note: a. true is returned if file is deleted successfully.
b. false is returned if file couldn’t be deleted or if file has already been deleted.
c. A directory can only be deleted when it doesn’t contain any other file/ directory.

11. list(): It returns a list of all files and directories in the directory defined by the file object.
Syntax:
String var[] = file_obj.list();

12. mkdir(): It creates the physical existence of the directory, defined by the file object.
Syntax:
boolean var = file_obj.mkdir();
Ex: boolean b13 = f1.mkdir(); //true
boolean b14 = f1.mkdir(); //flase
Note: true is returned if directory is created successfully.
false is returned if directory couldn’t be created or if directory already exists.

FileWriter CLASS:
It is one of the classes used to write data into a file.
This class is used to write strings or text.

Functions:
File f = new File(“C:\\java1\\rohnak”,“x.txt”); char ch[]={‘a’,’b’,’c’};
f.createNewFile();

1. Constructor: It is used to open a file to write data.


Syntax:
1. FileWriter fw_obj = new FileWriter(file_location);
Ex: FileWriter fw1 = new FileWriter(“C:\\java1\\rohnak\\x.txt”);

2. FileWriter fw_obj = new FileWriter(file_obj);


Ex: FileWriter fw2 = new FileWriter(f);

2. write(): It is used to write data/ text in file.


Syntax:
1. fw_obj.write(chr);
Ex: fw1.write(97); //‘a’ is written
fw1.write(‘b’); //‘b’ is written

2. fw_obj.write(str);
Ex: fw1.write(“hi”); //“hi” is written

3. fw_obj.write(chr[]);
Ex: fw1.write(ch); //“abc” is written
Page 85 of 108
3. flush(): It is used to write the data buffered in the memory and has not been written yet.
It guarantees that all data has been written successfully.
Syntax:
fw_obj.flush();
Ex: fw1.flush();

4. close(): It is used to close the FileWriter.


Syntax:
fw_obj.close();
Ex: fw1.close();

FileReader CLASS:
It is used to read data/ text from a file.

Functions:
File f = new File(“C:\\java1\\rohnak”,“x.txt”); char ch;

1. Constructor: It is used to open a file to read data.


Syntax:
1. FileReader fr_obj = new FileReader(file_location);
Ex: FileReader fr1 = new FileReader(“C:\\java1\\rohnak\\x.txt”);
2. FileReader fr_obj = new FileReader(file_obj);
Ex: FileRedaer fr2 = new FileReader(f);

2. read(): It returns a character in ASCII form. At the end of file, it returns -1.
Syntax:
int var = fr_obj.read();
OR char var = (char)fr_obj.read();
Ex: char ch = (char)fr1.read(); //a

3. close(): It is used to close the FileReader object.


Syntax:
fr_obj.close();
Ex: fr1.close();

Page 86 of 108
BufferedWriter CLASS:
It is used to write data/ text in a file.
It provides the FileWriter efficiency.
A file cannot be opened directly for writing, using the BufferedWriter. BufferedWriter object requires
a FileWriter object to write data.

Functions:
File f = new File(“C:\\java1\\rohnak”,“x.txt”);
char ch[] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’};

1. Constructor: It is used to open a file in which data is to be written.


Syntax:
1. BufferedWriter BW_obj = new BufferedWriter(new FileWriter(file_path));
Ex:
BufferedWriter bw1 = new BufferedWriter(new FileWriter(“C:\\java1\\rohnak\\x.txt”));

2. BufferedWriter BW_obj = new BufferedWriter(new FileWriter(file_obj);


Ex:
BufferedWriter bw2 = new BufferedWriter(new FileWriter(f));

2. write(): It is used to write data in the file.


Syntax:
1. BW_obj.write((int)chr);
Ex: bw1.write((int)‘a’);

2. BW_obj.write(str,start_pos,no_of_chars);
Ex: bw1.write(“abcdefghij”,2,3); //“cde” will be written

3. BW_obj.write(chr[],start_pos,no_of_chars);
Ex: bw1.write(ch,1,2); //“bc”

3. newline(): It is used to insert a new line in the file.


Syntax:
BW_obj.newLine();
Ex: bw1.newLine();

4. flush(): It is used to write all the buffered unwritten data in the file.
Syntax:
BW_obj.flush();
Ex: bw1.flush();

5. close(): It closes the file.


Syntax:
BW_obj.close();
Ex: bw1.close();

Page 87 of 108
BufferedReader CLASS:
It is used to read data from file.
It provides the FileReader efficiency.
A file cannot be opened directly for reading, using the BufferedReader. BufferedReader object
requires a FileReader object to write data.

Functions:
File f = new File(“C:\\java1\\rohnak”,“x.txt”);

1. Constructor: It is used to open a file to read data.


Syntax:
1. BufferedReader BR_obj = new BufferedReader(new FileReader(file_path));
Ex:
BufferedReader br1 = new BufferedReader(new FileReader(“C:\\java1\\rohnak\\x.txt”));

2. BufferedReader BR_obj = new BufferedReader(new FileReader(file_obj);


BufferedReader br2 = new BufferedReader(new FileReader(f));

1. read(): It returns a character in ASCII form. At the end of file, it returns -1.
Syntax:
int var = BR_obj.read();
OR char var = (char)BR_obj.read();
Ex: char ch = (char)br1.read(); //‘a’

2. readLine(): It reads a line of text from the file.


Syntax:
String var = BR_obj.readLine();
Ex: String line = br1.readLine();

3. skip(): It skips the given number of characters from current position.


Syntax:
long var = BR_obj.skip(no_of_chars);
Ex: long d = br1.skip(10);
Note: It returns the actual number of characters skipped, in case, number of characters in
file < no_of_chars.

4. close(): It closes the file.


Syntax:
BR_obj.close();
Ex: br1.close();

Page 88 of 108
PrintWriter CLASS:
It is used to write data into file.

Functions:
1. Constructor: It opens the file to write data.
Syntax:
1. PrintWriter pw_obj = new PrintWriter(file_path);
2. PrintWriter pw_obj = new PrintWriter(file_obj);
3. PrintWriter pw_obj = new PrintWriter(new FileWriter(file_path));
4. PrintWriter pw_obj = new PrintWriter(new FileWriter(file_obj));

2. print(): It is used to write any type of data in file.


Syntax:
1. pw_obj.print(char_var);
2. pw_obj.print(int_var);
3. pw_obj.print(long_var);
4. pw_obj.print(byte_var);
. . .

3. println(): It writes any type if data, and then inserts a new line.
Syntax:
1. pw_obj.println(char_var);
2. pw_obj.println(int_var);
3. pw_obj.println(str);

4. append(): It writes data at the end of file, preventing over-writing.


Syntax:
1. pw_obj.append(char_var);
2. pw_obj.append(str);

5. flush(): It is used to write all the buffered unwritten data in file.


Syntax:
pw_obj.flush();
Ex: pw.flush();

6. close(): It is used to close the file.


Syntax:
pw_obj.close();
Ex: pw.close();

FileWriter BufferedWriter PrintWriter


It can create physical link to file. It can’t create physical link to file, It can create physical link to file.
takes help of FileWriter.
‘\n’ is used for next line. newline() is used. println() is used.
Can’t write all primitive Can’t write all primitive Can write all primitive datatypes.
datatypes. datatypes.
Allowed : char, String Allowed : char, String

Page 89 of 108
25 JUNE 2019 HK

Multi-Threading
Executing several tasks simultaneously is the concept of multi-tasking.
There are 2 types of multi-tasking:
1. Process Based Multi-Tasking
2. Thread Based Multi-Tasking

Process Based Multi-Tasking Thread Based Multi-Tasking


It means executing several tasks simultaneously It means executing several tasks simultaneously
where each task is a separate independent where each task is a separate independent part of
process. same program.
It is best suitable at OS level. It is best suitable at programmatic/ program level.

Whether Process based or Thread based, the main purpose of multi-tasking is to reduce response time and
improve performance of system.
The main areas of application:
1. Developing multimedia graphics
2. Developing video games
3. Developing animations
4. Developing web and application servers
...

Defining and stating a new Thread:


There are 2 methods of defining threads:
1. By extending Thread Class
2. By implementing Runnable Interface

By Extending Thread CLASS:


a. Constructor: It is used to create a new Thread.
Syntax:
1. Thread thr_obj = new Thread();
Ex: Thread thr1 = new Thread();
Note: Threads are automatically named implicitly in the format : “Thread – i”.
i starts from 0.

2. Thread thr_obj = new Thread(thread_name);


Ex: Thread thr2 = new Thread(“Thread-1”);

b. start(): It is not a normal method call.


It will start a new flow of execution, new Thread.
It implicitly calls run() method on the thread.
It is responsible for performing all activities required for thread, like registering
the thread with Thread Scheduler.
Syntax:
thr_obj.start();
Ex: thr1.start();

c. run(): It is used to perform action for a thread.


Syntax:
thr_obj.run();
Ex: thr1.run();

Page 90 of 108
d. Thread Scheduler:
If multiple threads are waiting, then the order in which threads will execute is
decided by Thread Scheduler. It is a part of JVM and it’s exact behavior cannot be
expected. It is JVM Vender dependent. So, the order of execution of threads cannot
be expected. Hence, the exact output cannot be estimated.

e. getName(): It returns the name of the thread.


Syntax:
String var = thr_obj.getName();
Ex: String name = thr1.getName(); //Thread-0

f. setName(): It changes the name of the thread.


Syntax:
thr_obj.setName(name_str);
Ex: thr1.setName(“MyThread-1”);

g. currentThread(): It returns the reference of currently executing thread.


Syntax:
Thread var = Thread.currentThread();
Ex: Thread thr3 = Thread.currentThread();

h. getId(): It returns the ID of the thread.


Syntax:
int var = thr_obj.getId();
Ex: int id1 = thr1.getId(); //10

Page 91 of 108
Note:

1. run() can be overridden by the class extending the Thread class.

2. run() can be overloaded.

Page 92 of 108
3. start() always calls the default run() with no argument.

LIFECYCLE OF A THREAD:

if run() is
start() completed.
New Runnable
or or Running Dead
Born Ready

After starting a thread, if we try to restart same thread once again, a run-time exception will be displayed
saying: IllegalThreadStateException

Note: When start() is re-called, IllegalThreadStateException is generated.


But run() can be called any number of times.

Page 93 of 108
Runnable INTERFACE IMPLEMENTATION:
run() is the only available method.

THREAD PRIORITY:
Every thread has some priority.
It may be explicitly provided by the programmer or may be set by default by the JVM.
The valid range of thread priority is 1 to 10.
Where 1 is the thread with least priority and 10 is the thread with most priority.
Thread class defines the following constants to represent some standard priorities:
MIN_PRIORITY 1
NORM _PRIORITY 5
MAX_PRIORITY 10

Page 94 of 108
26 JUNE 2019 HK

THREAD METHODS TO CONTROL THE THREAD EXECUTION:

1. yield(): It causes to pause the currently executing thread to give chance to remaining waiting
threads of same priority. If there are no waiting threads or all other threads have
lower priority than the current thread, then the current thread will continue to
execute.
Syntax:
thr_obj.yield();
Ex: thr1.yield();

2. sleep(): It is used to pause the current thread execution for given milliseconds.
Syntax:
thr_obj.sleep(time_in_ms);
Ex: thr1.sleep(1000); //1 second pause

3. join(): It keeps a thread waiting until the completion of some other thread.
Every join() throws InterruptedException which is a checked Exception.
Syntax:
thr_obj.join();
Ex: thr1.join();

Page 95 of 108
APPLET
It is a small web program using which we can build small web applications.
Using applet program, programmer is able to build graphics, audio and multi-media application.
Due to applet, java is known as “Hot Java”.
Applet program can be embedded with client browser to execute dynamic content and applet
program can directly run in browser or execute in the front-end port.
So, it takes less time of execution, also provide security.

LIFE CYCLE OF APPLET:

INITIALIZE  STARTED  DRAW APPLET  STOP APPLET  DESTROY APPLET

INITIALIZE: First applet object create/ initialize when loaded into the browser.

STARTED: After initialization of an applet object, applet can start/ execute, or in other words, when
the browser is maximized, applet will maximize/ start.

DRAW: Here, all the graphical implementations are represented with applet.
The graphical components may be images or string messages.

STOP: When applet/ browser is minimized, applet is automatically stopped.

DESTROY: When the applet/ bowser is closed, applet object is automatically destroyed.

Note: Initialization and destruction of applet object should execute only once for an applet program.

LIFE CYCLE METHODS:


1. public void init(); It is used for initialization of object.
2. public void start(); It is used to start the applet object.
3. public void stop(); It is used to stop the applet object.

METHODS USED FOR BASIC GRAPHICS PROGRAM:


paint()
Use after importing java.awt.Components;

Page 96 of 108
HOW TO RUN APPLET:

1) HTML file:
Automatically run in browser.
<Applet code=”class_name” height=”height” width=”width”></Applet>

2) Applet Viewer:
>>>javac MyFile.java
>>>appletviewer MyFile.java

Example:

Page 97 of 108
paint(): It is the method used to represent the Text/ graphics on the Applet Screen.
This function is automatically executed when an applet starts.
Syntax:
public void paint(Graphics g);

FUNCTIONS FOR Graphics OBJECT:

1. drawString(): It is used to print string on the applet screen.


Syntax:
drawString(“string”, x_pos, y_pos);
Ex: drawString(“Hello Applet”, 50, 60);

2. drawLine(): It is used to draw a line.


Syntax:
drawLine(start_x, start_y, end_x, end_y);
Ex: drawLine(20,20,50,50);

3. setColor(): It is used to set the color used for the next graphics object.
Syntax:
setColor(java.awt.Color.<colorname>);
Ex: setColor(java.awt.Color.blue);

4. drawRect(): It is used to draw the outline of a rectangle.


Syntax:
drawRect(x_pos, y_pos, width, height);
Ex: drawRect(20,20,30,30);
Note: The (x_pos,y_pos) is the coordinate of top-left corner.

5. fillRect(): It is used to draw a solid rectangle filled with color.


Syntax:
fillRect(x_pos, y_pos, width, height);
Ex: fillRect(20,20,30,30);
Note: The (x_pos,y_pos) is the coordinate of top-left corner.

6. drawOval(): It is used to draw the outline of an oval in the specified rectangle.


Syntax:
drawOval(x_pos, y_pos, width, height);
Ex: drawOval(10,80,30,30);
Note: The (x_pos,y_pos) is the coordinate of top-left corner of the rectangle.

7. fillOval(): It is used to draw a solid oval filled with color in specified rectangle.
Syntax:
fillOval(x_pos, y_pos, width, height);
Ex: fillOval(80,80,30,30);
Note: The (x_pos,y_pos) is the coordinate of top-left corner of the rectangle.

8. drawArc(): It is used to draw the outline of an arc.


Syntax:
drawOval(x_pos, y_pos, width, height, startAngle, arcAngle);
Ex: drawOval(10,80,30,30,0,180);
Note: Positive arcAngle means anti-clockwise sweep, negative means clockwise.

Page 98 of 108
9. fillArc(): It is used to draw a solid arc filled with color.
Syntax:
fillOval(x_pos, y_pos, width, height, startAngle, arcAngle);
Ex: fillOval(80,80,30,30,0,-270);
Note: Positive arcAngle means anti-clockwise sweep, negative means clockwise.

10. drawImage(): It is used to show an image on the applet screen.


Syntax:
drawImage(Image_obj, x_pos, y_pos, this);

Examples:

Ex-1: Strings Rectangles Oval

Page 99 of 108
Ex-2 Lines Arcs

Ex-3 Image

Page 100 of 108


27 JUNE 2019 HK

AudioClip CLASS of java.awt PACKAGE:

Ex: audio

PLAYING GIF FILES:


Ex:

Page 101 of 108


FRAME:
A frame is a window which can be used instead of the Applet Viewer.
Ex:

Ex:

Page 102 of 108


BUTTON:
Ex:

After clicking the button…

Page 103 of 108


28 JUNE 2019 HK

CHECKBOX:
Ex:

After checking the checkboxes…

Page 104 of 108


WRAPPER CLASS:
In J2SE 5.0, Wrapper Class concept was introduced in Java. Here, for each primitive type, Java
provides wrapper classes.
Due to wrapper classes, Java couldn’t be called as a purely Object Oriented Programming
Language.

Sl.No. Primitive Datatype Wrapper Class


1 byte java.lang.Byte
2 short java.lang.Short
3 int java.lang.Integer
4 char java.lang.Char
5 float java.lang.Float
6 long java.lang.Long
7 double java.lang.Double
8 boolean java.lang.Boolean

Ex:
Integer i = new Integer(100); //100
Integer j = new Integer(“100”); //100
Integer k = new Integer(“hi”); //error

Float f = new Float(5.2); //5.2


Float g = new Float(“5.2”); //5.2
Float h = new Float(“hi”); //error

Note: If any primitive type variable tends to store a string type value which is the same datatype’s type
value but enclosed in double quotes, then the compiler implicitly converts it in the datatype’s type.
Ex: Integer j = new Integer(“100”); //100

If any variable tends to store another datatype’s type value, then error is generated.
Ex: Integer t = new Integer(“1.1”); //error

AUTOBOXING vs UNBOXING:

AUTOBOXING UNBOXING
It refers to the conversion of primitive type value to It refers to the conversion of wrapper class type
the wrapper class type value. value to the primitive type value.
Ex: Ex:
int i = 10; Integer i = new Integer(10);
Integer j = new Integer(20); int j = 20;
j=i; //10 j=i; //10

Page 105 of 108


USER- DEFINED PACKAGE:

DECLARING A PACKAGE:

//This file is to be saved by the name : “Class_name.java”


package package_name;
public class Class_name
{
public static void main(String args[])
{
//main() body
}
}

Ex:

// This file is to be saved by the name : “R1.java”


package A;
public class R1
{
public static void main(String args[])
{
System.out.println(“A”);
}
}

COMPILING A PACKAGE:

Syntax if package is in same directory:


>>> javac –d . Class_name.java
or
>>>javac –d path/Class_name.java

Ex:
>>>javac –d . R1.java
or
>>>javac –d C:/java1/rohnak/R1.java

RUNNING A PACKAGE:

Syntax:
>>>java package_name.Class_name

Ex:
>>>java A.R1

Page 106 of 108


Ex:

USING ONE PACAKAGE IN ANOTHER JAVA PROGRAM:


Syntax:

//Another program
import package_name;
//program body

Ex:

//program : “R2.java”
package B;
public class R2
{
public void display()
{
System.out.println("displayed.'");
}
}

//Program : “R3.java”
import B;
public class R3
{
public static void main(String args[])
{
R2 obj = new R2();
obj.display();
}
} //Output: displayed.

Page 107 of 108


BIBLIOGRAPHY
1. Niharika Madam’s notes
2. Google
3. Core Java (An Integrated Aproach) 2009 edition by R. Nageswara Rao

֍֍֍

Page 108 of 108

You might also like