[go: up one dir, main page]

0% found this document useful (0 votes)
5 views33 pages

STD IX Computer Application Notes

The document provides an overview of Object Oriented Programming (OOP) concepts, including the principles of objects, classes, data abstraction, encapsulation, polymorphism, inheritance, and message passing. It also introduces Java programming, covering types of Java programs, the compilation process, data types, operators, and the structure of Java code. Key features of Java such as platform independence, data types, and constants are discussed, along with rules for identifiers and comments.

Uploaded by

vamshiaarush
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views33 pages

STD IX Computer Application Notes

The document provides an overview of Object Oriented Programming (OOP) concepts, including the principles of objects, classes, data abstraction, encapsulation, polymorphism, inheritance, and message passing. It also introduces Java programming, covering types of Java programs, the compilation process, data types, operators, and the structure of Java code. Key features of Java such as platform independence, data types, and constants are discussed, along with rules for identifiers and comments.

Uploaded by

vamshiaarush
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Chapter 1

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:

Features of procedure oriented Programming:


• The given problem is divided in to a number of sub problems depending upon its
functionality.
• The sub problems are called procedures or Methods.
• Any procedure can be called at any point during the program execution.
• The program has global and local variables.
• Data moves freely from one function to another.
• Most of the functions share common data.
• Emphasis is given for algorithms.

Object Oriented Programming:


Features:
• The Program is divided into number of small units called Object. The data and

function are build around these objects.


• The data of the objects can be accessed only by the functions associated with that
object.
• The functions of one object can access the functions of other object.
• Emphasis is given on data rather than procedures.
• Data structures are designed such that they organize the object.
• Data and function are tied together.
• Data hiding is possible.
• New data and functions can be easily loaded.

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

Let’s learn in detail each of the Object Oriented Programming Concepts:

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

The state/characteristics of an object is otherwise called as


attributes/fields/Property.
The behavior of an object is otherwise called as Method/Function.
In terms of Software Program, An object can be defined as the group of variables
(Memory locations holding values) and functions (code that perform some
operation on variables)
2
Example 2:

➢ Class: A class is a blueprint or template or set of instructions to build a specific type


of object. Every object is built from a class. Infinite number of objects can be created
from the single class.

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 .

Abstraction refers to the act of focusing on important details or


characteristics and filtering out the unwanted details or
explanations.

Example 1:

An Object can have many abstractions.

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:

Encapsulation is a technique used to


protect the information in an object from
the other object.

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.

Real life example of polymorphism:

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:

Messages can be sent to objects via functions defined by the class.

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

Rules for naming an identifier:


1. Should always start with either an alphabet or dollar sign $ or underscore sign _.
2. Should not start with a number, but numbers can be present in between the name
or at the end of the name.
3. Keywords should not be used for naming the identifiers, but keywords can be
prefixed or suffixed with the identifier names.
4. No blank space characters allowed.
5. Identifier can be written either in uppercase alphabets or in lowercase alphabets or
including both.
6. The length (number of characters) depends upon the operating system used.

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

3. Documentation comment: This type of comment is used to produce an HTML file


that documents your program. It starts with /**……… and ends with */, where each
line in between is preceded by *

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

Numeric Non-Numeric Classes Arrays

Boolean boolean
double

Integer Floating point Character

byte float char


short double
int 12
long
Data
Size in bits Size in bytes Range
types
-128 to +127
byte 8 bits 1 byte or
-27 to 27-1
-32768 to +32767
short 16 bits 2 bytes or
-215 to 215-1
int 32 bits 4 bytes -231 to 231-1
long 64 bits 8 bytes -263 to 263-1
float 32 bits 4 bytes -3.4 x 10-38 to3.4 x 1038
double 64 bits 8 bytes -1.7 x 10-308 to 1.7 x 10308
char 16 bits 2 bytes 0 to 65535
boolean 8 bits, but uses 1 bit 1 byte true or false
Integers: Integers are whole numbers with no fractional part such as 45, -10 and 0. This
group includes byte, short, int and long data types. Integer type is for whole numbers that
include both positive and negative numbers.

The default data type for integer constants is int.


The default data type for floating point constant is double.

Floating Point numbers: A number having fractional part is a floating-point number.


This group includes float and double data types. float data type represents single precision
value and double data type represents double precision values. A floating point number
can be represented in two ways:

• Standard Notation or Decimal Notation


• Scientific Notation or Exponent Notation

Example for Standard Notation is 54.6, -67.89 etc.,


Example for Exponent Notation is 1.89E02, where it can be represented as 1.89 X 102 This
type of notation can be used when the precision is more. i.e., no of digits after the decimal
point.

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.

Unicode stands for Universal Code whereas ASCII stands for


American Standard Code for Information Interchange.
The following are the ASCII range for alphabets and digits.
'A' to 'Z' →65 to 90
'a' to 'z' → 97 to 122
'0' to '9' → 48 to 57

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

Infix notation is operator between two operands.


Prefix notation is operator present before the operand.
Postfix notation is operator present after the operand.

Assignment Operators: These operators are used to assign values to variables.


Sl.no Symbol Description
1 = Simple Assignment
2 op1=op2=op3 Compound assignment
3 Short hand or Complex assignment
op1+=op2 op1=op1+op2
op1-=op2 op1=op1-op2
op1*=op2 op1=op1*op2
op1/=op2 op1=op1/op2
op1%=op2 op1=op1%op2
Example:
int x=10,y=5, z=3;
int a, b, c, d;
a=b=c=d=100;
a+=10; b-=3; c*=a; d/=b; x%=y;
Assigning values during the run-time of the program:
Consider the statement:
int x=10; // the value 10 is assigned during the compilation of the program itself.
If you want to assign values during run-time, the variables have to passed as parameters
to a method.

Parameters

17
When you execute the above program, the following dialog box appears to input
values for the variables x and y.

Like Integer Parameters x and y, we


can also declare parameters of
various data types to accept inputs
for different types of values.
Output:

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

More Examples on Type Conversion:


Consider the expression
byte a=10, b=20,c; c=a+b;
When the above expression is compiled, the compiler generated a syntax error “possible
loss of precision”, because when any calculation is done using byte values, the result is
always promoted to int by default. The above expression can be written in the following
ways:
1. int c=a+b; 2. byte c=(byte)(a+b); //type casting to byte type.

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

Operand1 Operand2 Resultant type Operand1 Operand2 Resultant type


int int Int long long long
int long Long long float float
int float Float long double double
int double Double long char long
int char Int

Oprand1 Operand2 Resultant type Oprand1 Operand2 Resultant type


float float Float double double double
float double Double double char double
float char Float
Oprand1 Operand2 Resultant type Oprand1 Operand2 Resultant type
char char Int boolean boolean boolean

Expression: It is the combination of operands and operators. Expressions are classified


into
Expressions

Arithmetic Boolean
Expressions Expressions

Boolean
Arithmetic
Expressions Expressions

Pure Expression or Impure Expression


Relational Logical Expression
Complex Expression or Mixed Mode
Expression Expression

19
(1) Pure expression has operands of same data type.

Example:

int x=1, y=2;

int z=x+y; //x, y and z belongs to common type int

(2) Impure expression has operands of different data type.

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.

Operator Description Level Associativity

[] access array element


. access object member
() invoke a method 1 left to right
++ post-increment
-- post-decrement

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
!=

&& Conditional short-circuit AND 12 left to right

|| conditional short-circuit OR 13 left to right

?: Conditional [Ternary] 14 right to left


=
+=
-=
*= Assignment 15 right to left
/=
%=

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

byte nextByte() Returns the next token as a byte value (8 bits).

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

Returns the next token as a boolean value (reserves 8 bits


boolean nextBoolean()
but uses 1 bit, 0 for false and 1 for true)

Finds and returns the next complete token as a string; a


String next()
token is usually ended by whitespace.

Returns the next complete token as a string including


String nextLine() whitespaces; a token is usually ended when the user press
enter key.

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

6. Mathematical Library methods:


It is used to perform various mathematical operations such as finding square root,
power, logarithm etc., using the methods of Math class. Math class belongs to java.lang
package.

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

➢ int/long/float/double min(argument1, argument2) - Returns the minimum value


among the arguments.
Example:
System.out.println (Math.min(1,4)); //Output: 1
System.out.println (Math.min(1.2f,8.6f)); //Output: 1.2

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

Note: square root of a negative number results to NaN (Not a Number)

➢ double cbrt(int/float/double) - Returns the cube root value of the argument.


Example:
System.out.println (Math.cbrt(27)); //Output: 3.0
System.out.println (Math.cbrt(-512)); //Output: -8.0
➢ double pow(argument1, argument2) - Returns the result of argument1 raised to
argument2.
Example:
System.out.println (Math.pow(1,2)); //Output: 1.0
System.out.println (Math.pow(1.2f,3.4f)); //Output: 1.858729975419798
System.out.println (Math.pow(2.3,4.5)); //Output: 42.43998894277659
System.out.println (Math.pow('a', 2)); //Output: 9409.0
➢ double ceil(int/float/double) - Returns the value greater than or equal to the
argument.
Example:
System.out.println (Math.ceil(4)); //Output: 4.0
System.out.println (Math.ceil(4.2f)); // Output: 5.0
System.out.println (Math.ceil(5.0)); // Output: 5.0
System.out.println (Math.ceil(5.3)); // Output: 6.0
System.out.println (Math.ceil(-1.2)); // Output: -1.0
➢ double floor(int/float/double) - Returns the value lesser than or equal to the
argument.
Example:
System.out.println (Math.floor(4)); //Output: 4.0
System.out.println (Math. floor (4.2f)); // Output: 4.0
System.out.println (Math. floor (5.0)); // Output: 5.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

➢ double random() - Returns a random number between 0(inclusive) and 1(exclusive)


Example: System.out.println (Math.random()); //Output: 0.3
System.out.println ((int)Math.random()*10); // Output: 4
// returns
To generate any number
random in in
numbers the
a range 0 range.
specific to 9 Use the given formula:
Random_number = min + (int) (Math.random ( )* (max-min +1));
Example: To generate random numbers from 5 to 10
int min=5, max=10, rn;
rn= min + (int) (Math.random ( )* (max-min +1));
System.out.println (rn);

7. Conditional Constructs in Java:


In a Program, the execution of statements takes place in two ways,
1. Normal flow of execution
2. Conditional flow of execution
In Normal flow of execution, all the statements in a program gets executes, whereas in
conditional flow of execution, the statements gets executed depending upon the
condition satisfied in the program. The conditional statements are also called as
selection statements or decision making statements. There are various forms of decision
making statements in java, they are:
1. if statement
2. if else statement
3. Nested if statement
4. if else if statement
5. switch statement
Let’s learn in detail the uses of each of the above decision making statements.
if statement: This is a fundamental decision making statement which checks the
specific condition. If the condition is true, then it executes the statement(s) that follows
the condition, otherwise no action takes place if the condition is false. If there are any
26
other statements in the program following if block, then those statements will be
executed though the condition in “if” is true or false.
Syntax:
if(condition) if(condition)
statement; {
statements;
other statements; }
other statements;

When there are multiple statements to be executed for a condition


then the statements need to grouped with in the pair of { } which is
called compound statement or block.
When there is only one statement to be executed for an if condition,
then { } are not compulsory.

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

// To input a number and check it is in the range 100-200


void Check_Number (int n)
{
if(n>=100)
{
if(n<=200)
System.out.println (“Number in range”);
else
System.out.println (“Number not in range”);
}
else
System.out.println (“Number not in range”);
}
if else if statement: A common programming construct in java is the if else if ladder,
which is often also called the if-else-if staircase because of its appearance. The
expressions are evaluated from the top downward. As soon an expression evaluates to
true, the statement associated with it is executed and the rest of the ladder is bypassed.
If none of the expressions are true, the final else gets executed. If the final else is
missing, no action takes place if all other conditions are false.
Syntax:

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:

• It can only work for equality expressions.


• No two case constants can have identical values.
• It works only with int, char and String types.
• It executes faster than if else if statements and it is more efficient.
• We can have nested switch statement. i.e. a switch statement within another
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”);
}
}
}

System.exit (0) – to indicate successful termination. Terminates the program at


any stage.

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;

Expression1 – Conditional Expression

Expression2 - gets evaluated if the Expression1 is satisfied

Expression3 - gets evaluated if the Expression1 is not satisfied

Ternary Operator is called as Conditional Operator.

? stands for if

: stands for else

Example1:

//To input a number and check it is divisible by 5 or not.


class Check_Divisible
{
void Check_Number(int a)
{
String s=a%5==0?”Divisible”:”Not Divisible”;
System.out.println(s);
}
}

Example2:

//To input 2 no’s and find greater number.


class Greater
{
void Check_Numbers (int a, int b)
{
String s=a>b?”a is greater”: b>a?”b is greater”:”Numbers are equal”;
System.out.println(s);
}
}

31
Difference between if statement and switch statement

if statement switch statement

Comparison can be done between a Comparison is done between variable and


variable and range of values a value

Logical expression can be used Logical condition cannot be used

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.

Difference between Ternary operator and if-else statement

Ternary operator If else statement

It can have more than one statement in a


It can return only one value
block

It makes the program more concise Consumes much space

In Nested form it is more complex In nested form it is not complex

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

Few Runtime error or exceptions with their description


Sl.No Example Error Name
1 int x=10, y=0; ArithmeticException-Divide By Zero. A
int z=x/y; Number cannot be divided by zero.
System.out.println(z);
2 In Scanner Class: During the execution, if the user enter
System.out.println("Enter an any other value other than integer,
integer"); then it raises the error as
int a=sc.nextInt(); InputMismatchException
3 System.out.println(Math.sqrt(-4)); NaN(Not a Number) Runtime error,
cannot find square root of –ve numbers

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

You might also like