JAVA Language

You might also like

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

JAVA Language

Basic + Advanced

Useful for: Language developed by :


James Gosling at Sun Microsystems since 1991. Previous name ‘Oak’.
• BCA
• BSC CS
• BSC CA
• BSC IT
• BTECH CSE
• BTECH EC
• BTECH IT
• MSC CS
• MSC IT
• MCA
Slides By : KRISHNANDU SIR
M.SC (COMP. SC.)
Contact : 8961402179

youtube.com/Krishnandu Sir 1
Chapter Slide No.

youtube.com/Krishnandu Sir 2
Object Oriented Programming

Topic Slide No.


Programming Methodology 4-7
OOP Terminology 8-11
Development of JAVA 12-13

youtube.com/Krishnandu Sir 3
Topic 1.
Programming Methodology

I. Sequential Programming :-
It means writing a program in one or more steps which are in sequence.
II. Modular Programming :-
Breaking the program but in sequence.
III. Structured Programming :-
A programming concept with looping and branching.
IV. Procedure Oriented Programming (POP)/ Function Oriented Programming :-
It is basically consist of a list of instructions and organizing them into groups
known as functions while developing the functions, very little attention is
given to the data that are being used by various functions.
A typical program structure in POP is given below:
Main
function

Function 1 Function 2 Function 3

Function 4 Function 5

Function 6
youtube.com/Krishnandu Sir 4
Topic 1. (Contd.)
Advantages:
1. Complex program logic can be implemented easily.
2. Global data may access all the functions.
3. Large programs are divided into smaller functions, which are divided into smaller
functions, which are very easy to manage and debug.
4. Same variable names can be used in different functions.
5. Functions transforms data from one for to another.

Disadvantages:
1. Emphasis in on function and not on data.
2. Global data may be changed by functions.
3. In a large program it is difficult to identify what data is used by which function.
4. It doesn’t model real life problem very well.

Characteristics of POP:
1. Emphasis is on algorithms / codes.
2. Large programs are divided into small functions.
3. Most of the functions share global data.
4. Data move openly around the system from function to function.
5. Functions transforms data from one form to another.
6. Implies top-down approach in program design.

youtube.com/Krishnandu Sir 5
Topic 1. (Contd.)

IV. Object Oriented Programming (OOP) :-


It is an approach that provides a way of modularizing programs by creating
partitioned memory area for both data and functions that can be used as
templates for creating copies of such modules, objects when required.
OOP treats data as a critical elements in the program development and
doesn’t allow it to move freely around the system.
It ties data more closely to the functions that operate on it, and protects it
from modification from outside functions. OOP allows decompositions of a
problem into a number of entities called object and then build data and
functions around these objects.
A typical OOP program structure is shown below :-
Object A Object B

Data Data

Function Function

Object C

Data

Function
youtube.com/Krishnandu Sir 6
Topic 1. (Contd.)
Advantages:
1. Data are not allowed to move freely around the system.
2. It tides data more closely to the functions that operate on it.
3. It protects data from accidental modification from outside functions.
4. New data and functions can be easily added whenever necessary.

Disadvantages:
1. Data are hidden and can’t be accessed by external functions.
2. Emphasis is on data rather than functions.

Characteristics of OOP:
1. Emphasis is on data rather than function.
2. Programs are divided in objects.
3. Data are tied together with functions in the data structure.
4. Data are hidden and can’t access outside functions.
5. Objects may communicate with each other through functions.
6. New data and function can be added whenever necessary.
7. Follows bottom-up approach in program design.

youtube.com/Krishnandu Sir 7
Topic 2.
OOP Terminology

Objects:
Objects are basic runtime entities in OOP. Data and functions are built
around these objects. Objects may communicate with each other through
functions. It takes up space in memory and have associated address.
e.g.: A person, A place and bank account etc. are probable objects.
Syntax:
class_name object_name = new class_name() //Constructor call
Object:- Person
Data
Pname
Paddress
City
Pincode
Phoneno.
Function
getdata()
putdata()

youtube.com/Krishnandu Sir 8
Topic 2. (Contd.)
Class:
It is an user defined data structure. In OOP the entire set of data and
function of an object are tied together with the help of a class. In fact
objects are the variables of type class. Once a class is defined, we can
create any number of objects belonging to that class. Thus, a class is a
collection of objects of similar type. First letter of class name should
be in upper case.
Syntax:-
class class_name
{
access_specifier data & method / function();
access_specifier data & method / function();

} [object_name];

Class Object

1. It is a representation of only an abstraction. 1. It is a real and unique entity having some


characteristics and behaviors.
2. It is an object producer and hence called a blue 2. It is created with the use of new operator.
print for a set of objects.
3. It is known as ‘Object Factory’. 3. It is known as an ‘Instance of a Class’.

youtube.com/Krishnandu Sir 9
Topic 2. (Contd.)
Access specifier:-
1. Private :-
It is by default. Data and functions declared within this specifier are private
to that class and may be accessed by other members of the class but may
not access by external functions.
2. Public :-
This access specifier allows data and functions to access outside the class
by other functions of the program.
3. Protected :-
This access specifier allows private data and functions to access outside the
class using inheritance.
E.g. :-
class Student
{
private int roll;
private char name[20];
void getdata()
{ //Method definition
}
void putdata()
{ //Method definition
}
public static void main()
{
}
protected int m1,m2,m3;
youtube.com/Krishnandu Sir 10
};
Topic 2. (Contd.)
• Data abstraction :-
The act of representing essential features without including the background
details is known as data abstraction.
• Encapsulation :-
The binding of data and functions into a single unit (class) is called
encapsulation. Data can’t access to the outside of the class and only the
functions which are bind in the class can access it.
The insulation of data from direct access by the program is called data hiding.
• Modularity :-
It is the property of a system that has been decomposed into a set of
cohesive and loosely coupled modules.
• Inheritance :-
It is the capability of one class of things to inherit capabilities or properties
from another class.
The class, whose properties are inherited, is called Base Class or Super
Class and the class that inherits these properties, is called Derived Class
or Sub Class.
• Polymorphism :-
It is the ability for a message or data to be processed in more than one form.
Polymorphism is a property by which the same message can be sent to objects
of several different classes.
• Dynamic binding :-
It is the process to link the function call with function signature at run-time
i.e., during execution of a program. youtube.com/Krishnandu Sir 11
Topic 3.
Development of JAVA
• Different types of JAVA Programming:
a) Stand Alone System (Java Application) –
It is the source code developed by the users to carry a specific task.
b) Internet Applets (Java Applets) –
It is delivered to the users in the form of java byte code, which can run in a
web browser using a Java Virtual Machine (JVM).
• Basic features of java :
i. It is an object oriented programming language.
ii. Programs are both compiled and interpreted.
iii. Programs are platform language.
iv. It is multithreaded language.
v. It can access data from a local system as well as from net.
vi. Programming is written within a class. The variables and functions or declared
and defined with the class.
vii. Programs can create Applets and Applications are general programs like any
other programming languages.
viii. It is case sensitive. As a programming language, the language distinguishes the
upper case and lower case letters.

youtube.com/Krishnandu Sir 12
Topic 3. (Contd.)

• Complier :
A software that accepts the whole high level instructions at one go and then
converts it to machine level language is said to be compiler. It displays all the
diagnostically found errors at a time on the screen.
• Interpreter :
The software, that is used to convert the Interpreter /
high level instructions line by line to the
machine level language, is known as
interpreter. If an error is found on any
line, the further execution stops till it is
corrected.

Windows
System
Java
Java Byte Java Unix
Source
Compiler Code Interpreter System
Code
OS-2
JVM System

youtube.com/Krishnandu Sir 13
Tokens, Data types, Variables, Constants, Operators and Basic I/O

Topic Slide No.


Tokens, Variables, Constants and Operators 15-26
Data types 27-30
Basic I/O 31-33
Basic programming 34-38
Programs to practice 39-49

youtube.com/Krishnandu Sir 14
Topic 1.

Tokens,Variables, Constants and Operators


Tokens :-
The smallest individual unit in a program is known as a token. java has
following tokens:
a. Keywords
b. Identifiers
c. Literals
d. Punctuators / Separators
e. Operators
f. Assignments

Valid character sets in JAVA :-


Letters A-Z, a-z
Digits 0-9
Special Symbols Space + - * / ^ \ ( ) [ ] { } = != < > . ‘ “ $ , ; : % ! & ? _ # <=
>= @
White spaces Blank space, Horizontal tab, Carriage return(enter),
Newline, Form feed.
Other Characters JAVA can process any of the 256 ASCII characters as a
data or as a literals.
youtube.com/Krishnandu Sir 15
Topic 1. (Contd.)
ASCII Table

youtube.com/Krishnandu Sir 16
Topic 1. (Contd.)

Keywords :-
Reserve words, that convey a special meaning to the language compiler and
can be accessed by a program. They can’t be used as identifiers (variable
names, function name, etc.).

case switch else break Static


do const throws float char
try int double void goto
for while new import boolean
long if byte package private
catch short public class default

youtube.com/Krishnandu Sir 17
Topic 1. (Contd.)

Identifiers :-
User defined words in a program are identifiers, such as variable, function,
array, class, etc.

Rules for a valid identifier creation :-


i. An identifier is an arbitrarily long sequence of letters and digits.
ii. The first character must be a letter.
iii. _ (underscore) and $(dollar) count as a letter.
iv. Upper and lower case letters are different.
v. White spaces are not allowed.
vi. Cannot start with a digit.
vii. No special character is allowed except _ (Underscore) or $ (dollar).

Valid identifiers – Myfile, DATE9_7$77, _DS, FILE13


Invalid identifiers – DATA-REC, 29CLCT, break, My.file

youtube.com/Krishnandu Sir 18
Topic 1. (Contd.)
Literals :-
These are data items that never change their values during a program
execution.
Types of Literals –
i. Integer literals
An integer constant must have at least one digit and must not
contain any decimal point. It may contain either + or - sign. A
number with no sign is assumed to be positive. Commas cannot
appear in an integer constant.
e.g.: 124, 556, -986, -45
ii. Character constant
A character constant in JAVA must contain one character enclosed
in single quotation marks.
Escape Sequences Non-graphic Characters
\t Horizontal Tab
\v Vertical Tab
\\ Backlash
\’ Single Quote
\” Double Quote
\b Backspace
\f Formfeed
\0 Null
\r Carriage return

Escape Sequences in Java


youtube.com/Krishnandu Sir 19
Topic 1. (Contd.)
iii. Floating / Real constant
A real constant in fractional form must have at least one digit before
a decimal point and at least one digit after the decimal point. It may
also have either + or – sign preceding it. A real constant with no sign
is assumed to be positive.
Valid examples – 2.0, 17.5, -13.0, -0.06
Invalid examples – 7, +17/2, 10,909.87
A real constant in exponent form has two parts: a mantissa and an
exponent.The mantissa must be either an integer or a proper real
constant. The mantissa is followed by a letter E or e and the
exponent.The exponent must be an integer.
Valid examples – 152E05, 1.52E07, 152E+8
Invalid examples – 172.E5, 0.17E2.3, .25E-7
iv. String literal
A string literal is a sequence of characters surrounded by double
quotes.
e.g. ; “abc”, “India 1947”
v. Boolean literal
These are special constants, represented as ‘True’ or ‘False’ and can be used to
ensure that a logical condition is satisfied or not.
vi. Null literal
It is used for special purpose and is represented with the complete word ‘null’.
It is used to initialize an object of a class, and sometimes it denotes
non-availability of character in a string.
youtube.com/Krishnandu Sir 20
Topic 1. (Contd.)

Punctuators/ Separators :-
It enhances a program’s readability and give proper meaning to statements,
expressions etc. as per syntax.
Following characters are used as punctuators :-
[ ] ( ) { } ,. ; : * … = #
Operators :-
These are tokens that trigger some computation or action when applied to
variables and other objects in an expression.
The operations (specific tasks) are represented by Operators and the
objects of the operation(s) are referred to as Operands.
Types of operators –
a. Binary Arithmetic Operators :
i. Addition (+) - a+b; //3+4=7
ii. Subtraction (-) - a-b; //3-4=-1
iii. Multiplication (*) - a*b; //3*4=12
iv. Division or Quotient (/) - a/b; //3/4=0.75
v. Remainder or remnant (%) - a%b; //3%4=3

youtube.com/Krishnandu Sir 21
Topic 1. (Contd.)

b. Unary Operators :
Unary (+) operator- It is used before the operand. e.g. : a=+8
Unary (-) operator - It is used before the operand. e.g. : a=-6
Unary Increment - pre-increment (++a)
post-increment (a++)
Unary Decrement - pre-decrement (--a)
post-decrement (a--)
The postfix form of ++, -- operators follows the rule use-then
change and prefix form follows the rule change-then-use.

c. Relational Operators :
i. < (less than) - a<b
ii. <= (less than or equals to) - a<=b
iii. > (greater than) - a>b
iv. >= (greater than or equals to) - a>=b
v. == (equals to) - a==b
vi. != / <> (not equals to) - a!=b

youtube.com/Krishnandu Sir 22
Topic 1. (Contd.)
d. Logical Operators :
i. logical OR operator (||) - It evaluates to true (i.e., 1) if either of its
operand evaluate to true.
e.g. : (a==10)||(b==10)
ii. logical AND operator (&&) - It evaluates to true (i.e., 1) iff both of
its operand evaluate to true.
e.g. : (a==10)&&(b==10)
iii. logical NOT operator (!) - It negates or reverses the truth value of
the expression following it i.e., if the exp.
is true, then !exp. is false. It is unary op.
e.g. : !(a==10)
Relational operators have higher precedence over logical operators AND and OR.
Hence, while using AND and OR operators you need not to enclose the operands
within parenthesis. NOT (!) operator has the highest precedence, so it is required to
enclose the operand under parenthesis.
e. Ternary Operators (?:):
It stores a value depending upon a condition. It is ternary operator
i.e., it requires three operand.
Syntax - expression1 ? expression2 : expression3
If expression1 is true the value of expression2 is used else the value
of expression 3 will be used.
e.g.: result = marks >= 50? ‘P’ : ‘F’;
Nested conditional operator e.g.: max = (a>b)?(a>c)?a:c: (b>c)?b:c
youtube.com/Krishnandu Sir 23
Topic 1. (Contd.)
f. Bitwise operators:
It perform operations on bit level of the operands. These operators use byte, short int
and long type operands. Float and double types are not allowed. These are binary
operators.
Operators Meaning Use
& Bitwise AND a=12,b=10; (a&b); // 8
| Bitwise OR a=12,b=10; (a|b); // 14
^ Bitwise XOR a=12,b=10; (a^b); // 6
~ Bitwise Complement a=5; (~a); // 10
<< Left shift a=12; (a<<2); // 48
>> Right shift a=12; (a>>2); // 3
>>> Zero fill right shift a=12; (a>>>2); // 3
<<= Left shift assignment
>>= Right shift assignment
>>>= Zero fill right shift assignment
g. Other operator:
Memory management operators –
new operator :
i. To create memory locations of class type.
Syntax - class_name object_name = new class_name();
e.g., Array ob = new Array();
ii. To create array dynamically.
Syntax - data_type variable [] = new type_size[size];
e.g., int p[ ] =new int[10];
youtube.com/Krishnandu Sir 24
Topic 1. (Contd.)

Creating a 1-D array using new operator:


Scanner ob = new Scanner(System.in);
int p[ ]=new int [4];
for (i=0;i<4;i++)
p[i]=ob.nextInt();

Creating a 2-D array using new operator:


Scanner ob = new Scanner(System.in)
int p[ ][ ]=new int [4][3];
for (i=0;i<4;i++)
for (j=0;j<3;j++)
p[i][j]=ob.nextInt();

youtube.com/Krishnandu Sir 25
Topic 1. (Contd.)

Precedence of operators in Java

youtube.com/Krishnandu Sir 26
Topic 2.
Data types
Java data types are of three types –
i. Primitive/Built-in types :
Primitive (Atomic) data types are those that are not composed of other data
types. There are mainly four data types –
a. Integer type –
• byte Data type // byte a=5;
• short Data type // short a=12;
• int Data type // int a=214;
• long Data type // long a=45687;
b. Floating type –
• float Data type // float a=34.25;
• double Data type // double a=0.00056435869;
c. Character type –
• char Data type // char a=‘A’;
d. Boolean type –
• boolean Data type // boolean a=true;
NOTE:
1. A character is enclosed within single quotes(‘ ‘).
2. String is enclosed within double quotes(“ “).
3. A boolean type is expressed without quotes and assumes one of the values true
or false.
youtube.com/Krishnandu Sir 27
ii. Non-primitive/ Reference data types :
The Reference Data Types will contain a memory address of variable value
because the reference types won’t store the variable value directly in
memory. There are five non-primitive data type –
a. Array // int arr[5]={3,7,1,4,2}
b. String // String a=“JAVA”; or String a= new String(“JAVA”);
b. Function // void func(int a, float b);
c. Class //class Main { int x = 5; }
d. Object // class Main
{ int x = 5;
public static void main(String[] args)
{
Main myObj = new Main(); System.out.println(myObj.x);
}
}
e. Interface // interface Animal
{ public void animalSound();
// interface method (does not have a body) }
**Constant must be initialized at the time of declaration.

youtube.com/Krishnandu Sir 28
Topic 2. (Contd.)

JAVA Data types

Primitive Non-Primitive
Array
String
Boolean Numeric Function
Class
Object
Interface
Character Integral

Integer Floating type

boolean char byte short int long float double

youtube.com/Krishnandu Sir 29
Topic 2. (Contd.)

Size table

Type Size (in bytes) Default Range


byte 1 0 -2n-1 to 2n-1-1
short 2 0 -32768 to 32767 (2n-1 to 2n-1-1)
int 4 0 -2n-1 to 2n-1-1
long 4 0 -2n-1 to 2n-1-1

char 2 \u0000 -2n-1 to 2n-1-1


float 4 0.0 3.4x10-38 to 3.4x1038
double 8 0.0 1.7x10-308 to 1.7x10308
boolean 1-bit False

NOTE:
\u0000 is the decimal equivalent of 00 char in unicode.

youtube.com/Krishnandu Sir 30
Topic 3. Basic I/O
• Standard I/O :-

i. System.in –
This is the standard input stream that is used to read characters from the
keyboard or any other standard input device.
ii. System.out –
This is the standard output stream that is used to produce the result of a program
on an output device like the computer screen.Various types of print functions :
 print() – Syntax : System.out.print(parameter);
e.g.: System.out.print(“same line");
 println() – Syntax : System.out.println(parameter);
e.g.: System.out.println(“new line ");
 printf() – Syntax : System.out.printf(parameter);
e.g.: System.out.printf(“Value = %d\n“,x);
iii. System.err –
This is the standard error stream that is used to output all the error data that a
program might throw. It use all the print methods.
youtube.com/Krishnandu Sir 31
Topic 3. (Contd.)
• Scanner methods –

e.g.: Scanner object = new Scanner(System.in);


a=object.nextInt();
• Buffer reader –
Class to import: import java.io.BufferedReader;
import java.io.InputStreamReader;
Use: BufferedReader object = new BufferedReader(new
InputStreamReader(System.in))
String str=object.readLine();
a=Integer.parseInt();
NOTE: The parse() method receives some string as input, "extracts" the necessary
information from it and converts it into an object of the calling class.
youtube.com/Krishnandu Sir 32
Topic 3. (Contd.)
• Types of streams in Java :-
1. Input Stream –
These streams are used to read data that must be taken as an input from a
source array or file or any peripheral device.

2. Output Stream –
These streams are used to write data as outputs into an array or file or any
output peripheral device.

youtube.com/Krishnandu Sir 33
Topic 4. Basic programming
• Import –
The import keyword is used to import a package, class or interface.
• Package –
A package in Java is used to group related classes. Packages are divided into two
categories :
a. Built-in Packages –
A library of prewritten classes, that are free to use. The library is divided
into packages and classes i.e., either import a single class (along with its
methods and attributes), or a whole package that contain all the classes that
belong to the specified package.
e.g.: import java.util.*; // Whole package
import java.util.Scanner; // Specific class
b. User-defined Packages –
These are packages defined by user. To use the package user has to define it
in same directory.
e.g.: package mypackage;
class MyClass
{
public static void main(String[] args)
{
System.out.println(“user defined package");
}
} youtube.com/Krishnandu Sir 34
Topic 4. (Contd.)
• Mathematical functions
a) Math.sqrt() - e.g.: a=Math.sqrt(4.0); //Returns double type
b) Math.min() - e.g.: a=Math.min(4,6); //Returns minimum
c) Math.max() - e.g.: a=Math.max(4,6); //Returns maximum
d) Math.pow() - e.g.: a=Math.pow(2,3); //Returns double type
e) Math.log() - e.g.: a=Math.log(6.25); // Returns double type
f) Math.abs() - e.g.: a=Math.abs(-8); // Returns absolute value
g) Math.rint() - e.g.: a=Math.rint(8.2); //Returns nearest integer
//.0 to 0.5 will return floor
h) Math.round() - e.g.: a=Math.round(8.5); //Returns rounded
//.0 to 0.4 will return floor
i) Math.floor() - e.g.: a=Math.floor(8.7); //Returns double type
j) Math.ceil() - e.g.: a=Math.ceil(8.7); //Returns double type
k) Math.sin() - e.g.: a=Math.sin(x); //Angle should be in radian
l) Math.cos() - e.g.: a=Math.cos(x); //Angle should be in radian
m) Math.tan() - e.g.: a=Math.tan(x); //Angle should be in radian
n) Math.asin() - e.g.: a=Math.asin(x); //Angle should be in radian
//It returns degree.
o) Math.acos() - e.g.: a=Math.sin(x); //Angle should be in radian
p) Math.atan() - e.g.: a=Math.atan(x); //Angle should be in radian
q) Math.exp() - e.g.: a=Math.exp(6.2); //Returns exp value,
//Return double type
r) Math.random() - e.g.: a=Math.random(); //Returns value (0-1)
youtube.com/Krishnandu Sir 35
Topic 4. (Contd.)

Comments:
// - Single line comment
/*------*/ - Multiple line comment
youtube.com/Krishnandu Sir 36
Topic 4. (Contd.)

youtube.com/Krishnandu Sir 37
Topic 4. (Contd.)

youtube.com/Krishnandu Sir 38
Topic 5.

Programs to practice

1. WAP to calculate addition, multiplication, division & subtraction based on user’s


input.
2. WAP to calculate (a-b)2 using expanded equation.
3. WAP to calculate (a+b)3 using expanded equation.
4. WAP to calculate Simple Interest based on user’s input.
5. WAP to calculate Compound Interest based on user’s input.
6. WAP to calculate perimeter and area of square and rectangle.
7. WAP to calculate circumference and area of a circle.
8. WAP to calculate area of a triangle.
9. WAP to print your name and user’s given number.
10. WAP to calculate user’s age. [take current year from user also]

youtube.com/Krishnandu Sir 39
Topic 5. (Contd.)

youtube.com/Krishnandu Sir 40
Topic 5. (Contd.)

youtube.com/Krishnandu Sir 41
Topic 5. (Contd.)

youtube.com/Krishnandu Sir 42
Topic 5. (Contd.)

youtube.com/Krishnandu Sir 43
Topic 5. (Contd.)

youtube.com/Krishnandu Sir 44
Topic 5. (Contd.)

youtube.com/Krishnandu Sir 45
Topic 5. (Contd.)

youtube.com/Krishnandu Sir 46
Topic 5. (Contd.)

youtube.com/Krishnandu Sir 47
Topic 5. (Contd.)

youtube.com/Krishnandu Sir 48
Topic 5. (Contd.)

youtube.com/Krishnandu Sir 49
Topic Slide No.
Expressions 51-53
Statements 54-56
Alternative to if statements 57-59
Jump Statements 60
Errors 61
Basic programming 62-68
Wrapper Class 69
Programs to practice 70

youtube.com/Krishnandu Sir 50
Topic 1.

Expressions

An expression in Java is any valid combination of tokens.


e.g.,
 Pure arithmetic expression –
K+X-Y+count (K,X,Y & count are int type)
-J+K*Y (K,J &Y are float type)

 Mixed arithmetic expression –


qty/amount (qty is int type & amount is float type)

An arithmetic expression may contain just one signed or unsigned variable or a


constant, or it may have two or more variables or/and constants, or two or more
expressions joined by valid arithmetic operators. Two or more variables or operators
should not occur in continuation.

youtube.com/Krishnandu Sir 51
Topic 1. (Contd.)
•Type conversion/ Type casting :-
The process of converting one predefined type into another is call type conversion.
The explicit conversion of an operand to a specific type is called type casting.
a. Implicit Type conversion –
The conversion which is performed by the compiler without programmer’s
Intervention is called implicit type conversion or coercion.
byte Hierarchy char C int I; float F; double D;
char
D = C + I * F / D
short
int float double
long int
float double
char
double
double

b. Explicit Type Conversion – double


An explicit type conversion is user-defined that forces an expression to be
of specific type.
Syntax: (type) expression;
e.g., int a;
char b;
a=(int) b; youtube.com/Krishnandu Sir 52
Topic 1. (Contd.)

• Logical expression :-
x>y
(y+z)>=(x/z)
(a+b)>c&&(c+d)>a
x||y&&z
(x>y)&&(!y<z)
• Shorthands :-
Syntax: var=var operator expression
var operator = expression
e.g., x-=b;
x+=b;
x*=b;
x/=b;
x%=b;
These are also part of assignment operator (=).

youtube.com/Krishnandu Sir 53
Topic 2.
Statements
a. empty or null statement –
; // it is a null statement
b. Compound statement (block) –
{
statement 1;
statement 2;
---
}
c. Selection statements –
i. if statement :
Syntax: if(expression)
statement;
e.g.: if (a==‘ ‘)
space++;
ii. if-else statement :
Syntax: if(expression)
statement;
else
statement;
e.g.: if (a==‘ ‘)
space++;
else
other_char++;
youtube.com/Krishnandu Sir 54
Topic 2. (Contd.)

iii. if-else-if statement :


Syntax: if(expression)
statement;
else if(expression)
statement;
else
statement;
e.g.: if(a>0)
positive++;
else if(a<0)
negative++;
else
zero++;

youtube.com/Krishnandu Sir 55
Topic 2. (Contd.)

iv. Nested if statement :


Syntax: if(expression)
if(expression)
statement;
else
statement;
else
if(expression)
statement;
else
statement;
e.g.: if(a>b)
if(a>c)
System.out.print(“a is greatest”);
else
System.out.print(“c is greatest”);
else if(b>c)
System.out.print(“b is greatest”);
else
System.out.print(“c is greatest”);

youtube.com/Krishnandu Sir 56
Topic 3.
Alternative to if statements
• Ternary Operators (?:) –
Syntax - expression1 ? expression2 : expression3
If expression1 is true the value of expression2 is used else the value of
expression 3 will be used.
e.g.: result = marks >= 50? ‘P’ : ‘F’;
• Switch Statement :-
Syntax: switch(expression)
{
case constant_1: statement_1;
break;
case constant_2: statement_2;
break;

default: statement_n;
}
e.g.: switch(ch)
{
case 1: System.out.print(“one”);
break;
case 2: System.out.print(“two”);
break;
default: System.out.print(“Not a digit!”);
} youtube.com/Krishnandu Sir 57
Topic 4.
• Iterative Statements :-
A. for loop –
Syntax: for(initializaion expression(s);test-expression;update expression(s))
body-of-the-loop;
e.g.: for(i=1;i<=n;i++)
System.out.println(i);

B. while loop –
Syntax: initializaion expression(s);
while(test-expression)
{
body-of-the-loop;
update expression(s)
}
e.g.: i=1;
while(i<=n)
{
System.out.println(i);
i++;
}

youtube.com/Krishnandu Sir 58
Topic 4. (Contd.)
C. do-while loop –
Syntax: initializaion expression(s);
while(test-expression)
{
body-of-the-loop;
update expression(s)
}
e.g.: i=1;
do
{
System.out.println(i);
i++;
} while(i<=n);
• Nested loops :-
for(i=1;i<4;i++)
output
{
*
for(j=1;j<=I;++j)
**
System.out.print(“*”);
***
System.out.print(“\n”);
}

youtube.com/Krishnandu Sir 59
Topic 5.
Jump Statements
i. break statement –
while(test expression) for(initialize; test expression; update) do
{ { {
statement1; statement1; statement1;
if(val>2000) if(val>2000) if(val>2000)
break; break; break;
statement2; statement2; statement2;
} } } while(test expression);
statement3; statement3; statement3;

ii. continue statement –


while(test expression) for(initialize; test expression; update) do
{ { {
statement1; statement1; statement1;
if(val>2000) if(val>2000) if(val>2000)
continue; continue; continue;
statement2; statement2; statement2;
} } } while(test expression);
statement3; statement3; statement3;

iii. return statement –


It is used to explicitly return from a method. That is, it causes a program control to
transfer back to the caller of the method. class Prog
{
public static void main(String args[])
{
statement2;
return;
}
} youtube.com/Krishnandu Sir 60
Topic 6.
Errors
Testing Debugging
Testing is a process in which a program is Debugging is a process in which the errors
validated. in the program are removed.
Testing is complete when all desired Debugging is finished when there are no
verifications against specifications have errors and the program is ready for
been performed. execution.
• Types of errors :-
a) Syntax error –
These error occur when the syntax or the grammar of the programming
statements are not followed.
e.g.: c=a+b //(;) is missing at the end of the statement.

b) Semantic / Logical error –


It is an error in planning the program’s logic.
e.g.: int a=5,b=10,c;
c=a/b;
System.out.print(“The sum is: ”+c); //Logic is wrong

c) Run time error –


These errors occur during the execution of program.
e.g.: a=c/0; // Cannot be divided by 0.
youtube.com/Krishnandu Sir 61
Topic 7.
Basic programming

youtube.com/Krishnandu Sir 62
Topic 7. (Contd.)

youtube.com/Krishnandu Sir 63
Topic 7. (Contd.)

youtube.com/Krishnandu Sir 64
Topic 7. (Contd.)

youtube.com/Krishnandu Sir 65
Topic 7. (Contd.)

youtube.com/Krishnandu Sir 66
Topic 7. (Contd.)

youtube.com/Krishnandu Sir 67
Topic 7. (Contd.)

youtube.com/Krishnandu Sir 68
Topic 8.
Wrapper Class

• It provide the facility to contain primitive data values in terms of objects. It is


needed for the following reasons:
 To store the primitive values in objects
 To provide conversion system from character/ string type to other primitive
types.
• A data type is represented with a lower case letters whereas, its wrapper class is
represented with uppercase letter.
Wrapper classes Data Types
Character char
Byte byte
Short short
Integer int
Long long
Float float
Double double

youtube.com/Krishnandu Sir 69
Topic 9.
Programs to practice

1. WAP to print Square and cube of all numbers in a range.


2. WAP to check whether a given integer is even or odd, and terminates as soon as
user enter 0.
3. WAP to check whether a number is prime or not.
4. WAP to print Factorial of a given number.
5. WAP to check whether a number is perfect number or not : e.g. 6=sum of
factors(1,2,3)
6. WAP to check whether a number is duck number or not : e.g. 1090,209 if zero
present.
7. WAP to check whether a number is Armstrong or not : e.g. 153=13+53+33
8. WAP to check whether a number is Automorphic or not : e.g. 252=625
9. WAP to calculate: s=1-4+9-16+… to n terms
10. WAP to print the patterns :
a. 8 b. 8 c. 8888 c. ABCDEFEDCBA
88 888 888 ABCDE EDCBA
888 88888 88 ABCD DCBA
8888 8888888 8 ABC CBA
AB BA
A A
youtube.com/Krishnandu Sir 70
Topic Slide No.
Expressions 51-53
Statements 54-56
Alternative to if statements 57-59
Jump Statements 60
Errors 61
Basic programming 62-68
Wrapper Class 69
Programs to practice 70

youtube.com/Krishnandu Sir 71

You might also like