STD IX Computer Application Notes
STD IX Computer Application Notes
Revision of IX Syllabus
1. Introduction to Object Oriented Programming concepts and 2. Elementary Concept
of Objects and Classes.
Paradigms of Programming Languages
The Paradigms of programming Language gives the model to the programmer to write the
programs. The different Paradigms of programming languages are
1. Procedural Programming
2. Object Oriented Programming
Procedural Programming:
1
The Various Principles/features/concepts of Object Oriented Programming are:
1 • Object
2 • Class
3 • Data Abstraction
Object Oriented Programming
4 • Data Encapsulation Concepts
5 • Polymorphism
6 • Inheritance
7 • Message Passing
➢ Object:
Objects are key to understanding object-oriented technology. Look around right now and
you'll find many examples of real-world objects: your dog, your desk, your television set,
your bicycle. Real-world objects share two characteristics: They all
have state and behavior. State is nothing but the characteristics of an object and behavior
is nothing but the actions performed by the object.
Look at the example of an object Car, which has the following characteristics and behavior.
Every Object created from the class is called instance. Class is called as Object
Factory because it is the producer of many number of objects.
Example 1:
Example 2:
3
➢ Data Abstraction: The concept of representing important details and hiding
away the implementation details is called data abstraction. Abstraction tries
to minimize details so that the programmer can focus on a few concepts at a
time. Abstraction is the basis for software development .
Example 1:
Example 2:
4
➢ Data Encapsulation: Data encapsulation, also known as data hiding, is the
mechanism whereby the implementation details of a class are kept hidden
from the user. It is the mechanism that binds code and the data it
manipulates. This keeps both safe from interference and misuse.
Example 1:
In the above example, all the internal parts of a mobile is wrapped together
Example 2:
5
➢ Polymorphism: Polymorphism in java is a concept by which we can perform a single
action by different ways. Polymorphism is derived from 2 greek words: poly and
morphs. The word "poly" means many and "morphs" means forms. So polymorphism
means many forms.
Suppose if you are in class room that time you behave like a student, when you are in
market at that time you behave like a customer, when you at your home at that time
you behave like a son or daughter, Here one person present in different-different
behaviors.
Example 2:
A Person who knows more than two languages he can speak in a language which he
knows. Here person is Object and speak is polymorphism.
Inheritance: Inheritance can be defined as the process where one class acquires the
properties (methods and fields) of another. The class which inherits the properties of other
is known as subclass (derived class, child class) and the class whose properties are
inherited is known as super class (base class, parent class).
6
Message Passing: Message Passing is nothing but sending and receving of information by
the objects same as people exchange information. So this helps in building systems that
simulate real life.
Example:
Introduction to Java:
(a) Types of Java Programs:
(1) Stand alone application
(2) Applets (Web Application)
Stand alone application : this type of programs are written to carry out specific tasks on
a stand-alone local Computer. Example: Working on various concepts of java
Applet programs : are used in internet applications. The java applet will be placed on the
web by embedding into a HTML file. Example: Making and hosting a website online
(b) Steps involved in compilation process:
(i) Source code is compiled to generate byte codes(platform independent codes) by the
compiler.
(ii) Byte codes are converted to machine(object) code by the interpreter (JVM)
(b) Source code is the set of instructions and statements written by a programmer using
a computer programming language. Extension of Java source code is .java
(c) Object code is produced when an interpreter or a compiler translates source code into
recognizable and executable machine code.
7
(d) Byte code is program code that has been compiled from source code into low-level
code designed for a software interpreter. It may be executed by a virtual machine (such
as a JVM) or further compiled into machine code.
(e) Features of Java: Simple language, compiled and interpreted, robust and secure,
platform independent, Architecture neutral, Distributed, Multithreaded, Object Oriented,
Garbage collection etc.,
(f) Java solves the problem of platform independence by using byte code.
3. Values and data types and 4. Operators in Java:
Escape Sequences: Non-graphic characters used to format the output.
\n and \t
If we want to display the output on different positions on the screen, then we can use \n
and \t
\n - represents new line
\t - represents tab space
Example1:
System.out.println ("Low-Level Language\nHigh-Level Language");
Output:
Low-Level Language
High-Level Language
In the above example, first it prints Low-Level Language, and then the cursor moves to
the next line due to \n and prints High-Level Language.
Example2:
System.out.println ("A\tB\tC");
Output:
A B C
Other escape sequence characters are:
\\ - prints \
\" – prints "
\' – prints '
Example: Output:
System.out.println ("\"Java\"");
System.out.println("\\//"); "Java"
\/
System.out.println ("\'Hello\' "); 'Hello'
8
Token: The smallest individual unit in a program is known as token.
Example: keywords, identifiers, punctuation marks, literals (constants), operators.
Identifier
Keywords s
Constant
Punctuators
Operator
Whitespace: Whitespace is a space between two tokens. There should be at least one
whitespace character between two tokens. Tab space (\t) and new line (\n) are also
referred as whitespace.
Whitespace
Whitespace
Keywords: Keywords are the reserved words that convey special meaning to the
language compiler. They are used for special purpose. It is case sensitive.
Example: int, void, static, etc.,
Keywords
Java is a free form language. There is no particular indent style in Java that needs to
be followed specifically. Although, you have to make sure that, keywords, identifiers,
literals, operators, and separators are clearly defined by using whitespaces.
Whitespaces could be space, tab, or newline.
9
Identifiers: Identifiers are the names given to various data items in a program such as
variables, classes, functions/methods, objects, arrays.
Identifier
s
Comments: Comments are used to enhance the readability of the program. It is the
remark given by the programmer. Comments will not be executed by the compiler. The
different styles of expressing comments are
1. Single line comment: It is preceded by //. We can write comment in one line only.
If you want to continue writing the comment in the next line, then every line should
start with // Example: // this is a comment.
2. Multiline comment: It is preceded by /*………….. and the comment ends with */,
where each line in between is preceded by *
We can write multiple line comments.
Example: /* this program is used to input the total purchase of a customer
and calculates the discount amount and the amount to be paid by the
customer. */
10
Separators: Separators are the few characters that are used as punctuators in a program.
1. ( )→Parenthesis: 1. Used to declare input parameters in a method.
Eg: public void input (int a, int b)
2. Used to group expressions.
Eg: (a+b)*c/d
3. Used in type conversion(casting)
Eg: (int)(a+b);
2. { }→ Curly braces:
Used to start and end the class/method block.
Eg: class abc
{
public void input (int a, int b)
{
Statement (s);
}}
3. [ ]→ Square Brackets:
1. Used to declare array type. Eg: int a [ ];
4. ; →Semicolon: Used to end the java statement.
Eg: int a; a=10;
System.out.println (a);
a=a+5;
5. ,→Comma:
1. Used to separate the variables of same data type when declaring its data
type.
Eg: int a,b,c;
2. Used to separate input parameters in a function header.
Eg: public void input (int a, char b, String s)
6 . →Dot/period:
1. Used to separate the object and function
Eg: System.out.println(“Hello”); out→ is an object and println()→ is a function
2. Used to separate the class name and function.
Eg: Math.sqrt (25 ); Math→is a class name and sqrt()→ is a function
11
Constants or Literals: Literals (often referred as constants) are the data items that are
fixed data values. The different types of constants are:
1. Integer constants: These are the whole numbers without any fractional part.
Eg: 50, 457, -20.
2. Floating-point constant: Floating point constant are also called as real constants.
These constants are numbers having fractional parts.
Eg: -50.5, 50.2
3. Character constants: A character constant is a single character enclosed in single
quotes. Java allows you to have certain non-graphic characters in character
constants. Non-graphic characters or escape sequence characters are the
characters that cannot be typed directly from keyboard. Eg: backspace, tab, carriage
return (enter key) etc., These Non-graphic characters can be represented by a
backslash (\) followed by one or more characters. \n→new line or line feed, \t→tab,
\”→ double quotes etc., The following are some examples of character constants 'a',
'%', '\t', '8'………
4. String constant: Multiple characters enclosed within double quotes are treated as
string constants. Eg: "School", "ICSE Computer Applications"
"abc\t" NOTE: \t is one character.
5. Boolean constant: These constants are represented by two values true and false.
Eg: true, false
Data type: Programs typically need to store information. To store information, the
program uses variables. A variable is a symbolic name for computer memory location.
the program must keep track of the type of information to be stored in the variable. The
type in Java is defined by the data type. It is defined as the set of possible values that a
variable can hold. Java data types are classified.
1. Primitive data type or intrinsic data type or basic data type or fundamental data type.
2. Reference data type or composite data type or user defined data type.
Data types
Primitive Reference
Boolean boolean
double
float can be used for representing data like smaller amount in rupees and paisa.
double can be used for representing larger values like area of circle etc.,
Any decimal constant by default is considered as double type by the compiler. If the
user wants to explicitly represent decimal value in float type, then it can be represented
by suffixing f or F with the constant. double values can also be written by suffixing d
or D. For Example 4.5F is a float value where as 4.5 or 4.5D is double value.
13
Characters: This group includes char data type. It stores characters such as alphabets,
digits and symbols. Java uses Unicode to represent characters. Unicode defines a complete
international character set that can represent all the characters found in human
languages. The range of char is 0 to 65, 535. The standard set of characters known as
ASCII ranges from 0 to 127.
Boolean: This group includes boolean data type which is a special type for representing
true/false values. These values are returned by the conditional expressions.
Variable: variable represent named storage locations whose values can be manipulated
during program run. A variable holds a data value of a particular data type.
Creating String: String is referred as the group of characters enclosed in a pair of quotes
" ". It can be used to store more than one character which comprises of data elements like
names, sentences, etc., string is not a primitive type. The memory size of string is
calculated based on the number of characters present in it. strings can be created using
the inbuilt class called String in which object can be created to initialize the characters.
String s="Welcome to Java Programming";
Here String is a class and s is the object of class String.
Variable declaration: It is the data type followed by the variable name.
Syntax: datatype variable;
Example: int age; float amount;
Initialization of variable: Assigning values or storing values into variables is called as
initialization.
Syntax: datatype variable;
variable=value;
[or] datatype variable=value;
Example: int x; x=10; or int x=10;
14
Dynamic Initialization of variable: Initializing the variable during the execution of the
program is known as Dynamic Initialization.
Example1: int x=10, y=20; Math.sqrt (n) returns the root value of the
int z=x+y; argument n.
Math.pow (b, p) returns the value of b raised to p
sqrt () and pow () methods belongs to Math class
Example2: int x=4; and gives output by default in double type.
System.out.println(Math.sqrt(x));
Use of final keyword: It makes a variable as constant.
Example: final int x=100;//the value remains constant and cannot be changed during
the runtime of the program.
Operator: It is a symbol or character used to perform a specific operation on
operands(variables) or values. Based on the number of operands, operators are categorized
as Unary, Binary and Ternary. Unary operator works on single operand. Binary operator
works on two operands and ternary operator work on three operands.
Types of Operators:
Arithmetic Operators: These operators are used to perform arithmetic operations on two
operands. The result of these operators will be Integer or Floating point.
Sl.no Symbol Description
1 + Addition
2 - Subtraction
3 * Multiplication
4 / Division
5 % Modulo
Example:
int x=10,y=5;
System.out.println (x+y);
System.out.println (x-y);
System.out.println (x*y);
System.out.println (x/y); // gives Quotient as output after dividing 2 numbers
System.out.println (x%y); // gives remainder as output after dividing 2 numbers
Relational Operators: These Operators are used to find the relation between two
operands of numeric or character data type. The result of these operators is a boolean
value.
Sl.no Symbol Description
1 < Less than
2 > Greater than
3 <= Less than or equal to
15
4 >= Greater than or equal to
5 == Equal to
6 != Not equal to
Example:
int x=10,y=5;
System.out.println (x<y);
System.out.println (x>y);
System.out.println (x<=y);
System.out.println (x>=y);
System.out.println (x= =y);
System.out.println (x!=y);
Logical Operators: These operators are used to check two or more relational expressions
and gives the result in boolean data type.
Sl.no Symbol Description
1 && AND
2 || OR
3 ! NOT
Example:
int x=10,y=5, z=3;
System.out.println (x<y && z>x);
System.out.println (x>y || z<x);
System.out.println (!(x<y));
Unary Operators: These operators are used to perform operation on single operand only.
Sl.no Symbol Description
Unary + for indicating +ve value and also promotes char or
1 +
byte or short value to int data type
2 - Unary – indicates the number is negative
3 opr++ Postfix or post increment
4 opr-- Postfix or post decrement
5 ++opr Prefix or pre increment
6 --opr Prefix or pre decrement
Example:
int x=10,y=5, z=3;
System.out.println (x++);
System.out.println (++x);
System.out.println (y--);
System.out.println (--y);
16
char ch='a';
System.out.println (+ch); // Unary +
int x=-12; // number is negative.
System.out.println(-x); output is 12 because -(-12)=12
Parameters
17
When you execute the above program, the following dialog box appears to input
values for the variables x and y.
Type Conversion: Conversion of value from one primitive data type to another primitive
data type is called type conversion.
Two types of conversion:
(1) Implicit/Automatic/Widening/COERCION
(2) Explicit/Manual/type casting/Narrowing
Implicit conversion: this type of conversion will be done by the compiler itself.
Example: char ch=65; // stores A
int a='A'; //stores 65
Explicit conversion: This type of conversion will be done by the user using ( ) operator
to convert from higher data type to lower data type.
Example:
int x=10; double y=10.55;
int z=(int)(x+y);
Similarly when the datatype short or char are used in arithmetic expressions, by default
the result is promoted to int. Look at the examples given below:
short a=100, b=200;
int c=a*b; [or] short c=(short)(a*b);
byte a=10; char x='A';
int c=a+b; [or] it can be promoted explicitly to char or byte type.
18
Type Conversion Table
Operand1 Operand2 Resultant type Operand1 Operand2 Resultant type
byte byte Int short short int
byte short Int short int int
byte int Int short long long
byte long Long short float float
byte float Float short double double
byte double Double short char int
byte char Int
Arithmetic Boolean
Expressions Expressions
Boolean
Arithmetic
Expressions Expressions
19
(1) Pure expression has operands of same data type.
Example:
Example:
int x=1; double y=10.5; double z=x+y;
// here x belongs to int and y belongs to double
int a=100; float b=12.3f; char c='A';
float d=a+b+c; //here three operands are involved int, float and char
Java has well-defined rules for specifying the order in which the operators in an expression
are evaluated when the expression has several operators. For example, multiplication and
division have a higher precedence than addition and subtraction. Precedence rules can be
overridden by explicit parentheses.
Precedence order.
When two operators share an operand the operator with the higher precedence goes first.
For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as
(1 * 2) + 3 since multiplication has a higher precedence than addition.
Associativity.
When an expression has two operators with the same precedence, the expression is
evaluated according to its associativity. For example x = y = z = 17 is treated as
x = (y = (z = 17)), leaving all three variables with the value 17, since the = operator has
right-to-left associativity (and an assignment statement evaluates to the value on the right
hand side). On the other hand, 72 / 2 / 3 is treated as (72 / 2) / 3 since the / operator
has left-to-right associativity.
Precedence and associativity of Java operators.
The table below shows all Java operators from highest to lowest precedence, along with
their associativity. Most programmers do not memorize them all, and even those that do
still use parentheses for clarity.
20
++ pre-increment
-- pre-decrement
+ unary plus
2 right to left
- unary minus
! logical NOT
~ bitwise NOT
() cast
3 right to left
new object creation
*
/ Multiplicative 4 left to right
%
+- additive
5 left to right
+ string concatenation
< <=
> >= Relational type comparison 7 left to right
==
Equality 8 left to right
!=
5. Input in Java:
21
Scanner Class
Scanner class: The Scanner class is a class in java.util, which allows the user to read
values of various types. The Scanner looks for tokens in the input. A token is a series of
characters that ends with what Java calls whitespace. A whitespace character can be a
blank, a tab character, or the end of the line. Thus, if we read a line that has a series of
numbers separated by blanks, the scanner will take each number as a separate token.
Numeric and String Methods
Method Description
short nextShort() Returns the next token as a short value (16 bits).
int nextInt() Returns the next token as an int value (32 bits).
long nextLong() Returns the next token as a long value (64 bits).
float nextFloat() Returns the next token as a float value (32 bits).
double nextDouble() Returns the next token as a double value (64 bits).
char next().charAt(0)
Reads a character at 0th Index position of a String
char nextLine().charAt(0)
22
Example:
import java.util.*;
class sccanner1
{
void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter an integer");
int a=sc.nextInt();
System.out.println("Enter a float value");
float b=sc.nextFloat();
System.out.println("Enter a double value");
double c=sc.nextDouble();
System.out.println("Enter a long value");
long d=sc.nextLong();
System.out.println("Integer value "+a);
System.out.println("Float value "+b);
System.out.println("double value "+c);
System.out.println("long value "+d);
}
}
import java.util.*;
class sccanner2
{
void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter your name");
String a=sc.next();//reads characters until first whitespace
System.out.println("Your name is "+a);
}
}
import java.util.*;
class sccanner3
{
void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter your name");
String a=sc.nextLine();//reads characters including whitespaces till the user press
//enter key.
System.out.println("Your name is "+a);
}
}
23
import java.util.*;
class sccanner4
{
void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a character");
char a=sc.next().charAt(0);//reads a character at 0th index position
System.out.println("character is "+a);
}
}
Methods:
➢ int/long/float/double abs(int/long/float/double) - Returns the absolute value of
the argument. [It converts the negative to positive]
Example:
System.out.println (Math.abs(-5)); //Output: 5
System.out.println (Math.abs(-5.5f)); //Output: 5.5
System.out.println (Math.abs(-123.456)); //Output: 123.456
➢ int/long/float/double max(argument1, argument2) - Returns the maximum value
among the arguments.
Example:
System.out.println (Math.max(1,4)); //Output: 4
System.out.println (Math.max(1.2f,8.6f)); //Output: 8.6
System.out.println (Math.max(45.6, 89.90)); //Output: 89.90
System.out.println (Math.max('a','A')); //Output: 97
24
System.out.println (Math.min(45.6, 89.90)); //Output: 45.6
System.out.println (Math.min('a','A')); //Output: 65
➢ double sqrt(int/float/double) - Returns the square root value of the argument.
Example:
System.out.println (Math.sqrt(4)); //Output: 2.0
System.out.println (Math.sqrt(25.0f)); //Output: 5.0
System.out.println (Math.sqrt(625.0)); //Output: 25.0
25
System.out.println (Math. floor (5.3)); // Output: 5.0
System.out.println (Math. floor (-1.2)); // Output: -2.0
➢ int/long round(float/double) - Returns the rounded value of a number from .5 and
above.
Example:
System.out.println (Math.round(5.6f)); //Output: 6
System.out.println (Math.round(4.5)); //Output: 5
Example:
// To input a number and display it on the screen if it is more than 100.
void Check_Number(int x)
{
if(x>100)
System.out.println (x);
}
if else statement: This statement is used to select one alternative statement out of two.
In this case, if the condition is satisfied, the statements following the if will be executed
otherwise it executes the statements following the else.
Syntax:
if(condition) if(condition)
statement; {
else statements;
statement; }
else
other statements; {
statements;
}
other statements;
Example:
// To input the age of user and display the message “Major” if age is more than 17
otherwise display the message “Minor”.
void Check_Age(int age)
{
if(age>=18)
System.out.println (“Major”);
else System.out.println (“Minor”);
}
27
Nested if statement: An if statement that is to be executed as a target of another if or
else. It can also be defined as an if condition within another if or else
Syntax:
if(condition)
{
if(condition)
statement;
}
if(condition)
{
statement;
}
else if(condition)
{
statement;
}
else if(condition)
{
statement;
}
.
.
.
else
{
statement;
} 28
Example:
// To input a number and check it is +ve, -ve or zero
void Check_Number (int n)
{
if(n>0)
{
System.out.println (“Number is positive”);
}
else if(n<0)
{
System.out.println (“Number is negative”);
}
else
{
System.out.println (“Number is zero”);
}
}
switch statement: Java provides a multiple-branch selection statement known as
switch. This selection statement successively tests the value of an expression against a
list of integer or character constants. When a match is found, the statement associated
with that constant are executed until the break statement or the end of switch statement
is reached. The default statement gets executed when no match is found. If the control
flows to the next case below the matching case, in the absence of break, this is called fall
through. The default statement is optional and if it is missing, no action takes place if all
matches fail.
Syntax:
switch(expression)
{
case value1:
statements;
break;
case value2:
statements;
break;
…………
case valueN:
statements;
break;
default:
statements;
break;
}
29
Features of switch statement:
Example:
//To input the no. of players and display how many players are playing the game.
class Players
{
void Display(int a)
{
switch(a)
{
case 1: System.out.println (“1-player is playing the game”); break;
case 2: System.out.println (“2-players are playing the game”); break;
case 3: System.out.println (“3-players are playing the game”); break;
default: System.out.println(“You entered wrong choice”);
}
}
}
class Players
{
void Display(int a)
{
switch(a)
{
case 1: System.out.println (“1-player is playing the game”); break;
case 2: System.out.println (“2-players are playing the game”); break;
case 3: System.out.println (“3-players are playing the game”); break;
default: System.out.println(“You entered wrong choice”);
System.exit (0);
}
}
}
30
Ternary Operator: Java has an operator that can be used as an alternative of if else
statement known as ternary operator or conditional operator?: this operator can be used
to replace if-else statements. Ternary operator involves with the usage of three operands.
Syntax:
var=Expression1?Expression2:Expression3;
? stands for if
Example1:
Example2:
31
Difference between if statement and switch statement
It can be used to compare float and It can compare integers, character and
double values strings
The value of one variable can be compared In this the value of variable can be
with the value of other variable compared with constants(literals) only.
Errors:
Few Syntax Errors with their description
Sl.No Example Error Name
1 int a=10 Statement missing ;
2 int a=1, a=1; Multiple declarations for a
3 int x=12.3; Possible loss of precision. Required int
found double
4 int x; System.out.println(x); Variable x might not have been
initialized.
5 if(a>b); else without if because if condition is
System.out.println(a); terminated by semicolon.
else
System.out.println(b);
6 System.out.println(a); Cannot find symbol a
7 system.out.println(10); Package system does not exist.
8 String s="Hello; Unclosed String literal.
32
9 class Sample Expected {
void display(){ } }
Note: Logical errors occurs due to wrong logic in the program which needs to be
corrected by the user to get the exact output required by the user.
Example:
if(age>=17)
System.out.println(“Minor”);
else
System.out.println(“Major”);
In the above logic, the messages are printed wrong
Like this many errors can be made by the user depending upon the logic.
______________________
33