Notes on Java Fundamental(class 8)

You might also like

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

JAVA FUNDAMENTALS

The instructions written to solve a specific problem or do a specific task in a certain programing
language is called program.

Need and Features of a program

1. Program should be simple and easy to understand

2. Program should be easily readable

3. Program should be efficient – ie. Consume less memory space

4. Program should be generalized in nature

5. Program should be platform independent

6. Program should be broken up into number of independent subprograms

7. Program should be flexible so that any upgradation may be done easily.

8. Documentation of the program should be simple

9. Name of the variable should be mnemonic in nature.

10. As Java is case sensitive, so proper naming convention must be followed.

Steps of writing program

1. Programmer need to analyze the program first.

2. After analyzing the problem needs to be described to understand it better. Programmer


should have a clear idea of the output required, the inputs to be given.

3. Draw the flow chart.

4. Then the proper and simplest algorithm leads to the most accurate result, should be written
to solve the problem.

5. Write the code to implement the algorithm in the desired platform in the desired
programming language.

6. Now Test and Debug

7. Test with the realworld users

Components of java program

Character Set

Tokens

– Keywords
– Identifiers
– Literals
– Separators/punctuators
– Operators

Java Character Set


A character set is a set of valid characters that a language can recognize. A character
represents any letter (A to Z or a to z), digit (0 to 9), White space(blank space, horizontal tab,
carriage return, new line and form feed) or other sign.

Java uses UNI code character set. UNI code is 2byte character code set.

Tokens:

The smallest individual unit in a program is known as token. Types:

– Keywords
– Identifiers
– Literals
– Separators
– Operators
Keywords are the words that convey a special meaning to the language compiler.Keywords
are reserved for special purpose and must not be used as normal identifier names.

The reserved words const and goto are not in use now. And true, false null are not keywords
but are reserved words, they are used as literals.

Identifiers

Identifiers are fundamental building blocks of a program and are used as a general
terminology for the names given to different parts of the program viz variable, objects,
classes, functions, array etc.

Identifier forming rules of Java

1. Identifiers can have alphabets, digit and underscore and dollar


2. They must not be a keyword or Boolean literal or null literal
3. They must not begin with a digit
4. They can be of any length
Java is case sensitive

Examples

Here are some valid identifiers: Here are some invalid identifiers

1. aaa 1. 1ab (ERROR: first character starts


2. sales_tax with a digit)
3. _circleArea 2. num-oranges (ERROR: dash is not
4. box100width permitted in identifiers)
5. $directory 3. num oranges (ERROR: space is not
6. ab1234$$ permitted in identifiers)

Literals :

Literals are data items that are fixed data values. Java allows several kinds of literals

Integer literal (whole numbers)

Floating literal (signed and unsigned digits with decimal point)

Boolean literal ( two values – true and false)

Character literal (one character enclosed in single quote)

String literal (multiple character enclosed in double quote)

Null literal (null type has one value)

Separators

Following are the separators.

1. ()
2. {}
3. []
4. ;
5. ,
6. .

Parentheses ( and ) for specifying a precedence change in an expression


Braces { and } for grouping zero or more statements into a block of statements
Square brackets [ and ] for declaring an array or accessing an array element's value
Semicolon (;) for separating one statement from another
Comma (,) for separating variable names
Period (.) for separating fields and methods in a field or method access expression

Operators
Operator in Java is a symbol which is used to perform operations.Operators are symbols that
indicate the type of operation that has to be performed on the data or on the values of
variables.
Types of operators
1. Arithmetic
2. Relational
3. Logical
Operations are represented by operators and objects of the operation(s) are referred to as
operands
Relational Operators
Java has six relational operators that compare two numbers and return a boolean value.
The relational operators are <, >, <=, >=, ==, and !=.
True if x is less than y,
x<y Less than
otherwise false.

True if x is greater than y,


x>y Greater than
otherwise false.

True if x is less than or equal


x <= y Less than or equal to
to y, otherwise false.

Greater than or equal True if x is greater than or


x >= y
to equal to y, otherwise false.

True if x equals y, otherwise


x == y Equal
false.

True if x is not equal to y,


x != y Not Equal
otherwise false.

An Example
Logical Operator
Logical Operators are used to combine two or more conditions.

Java AND Operator Example: Logical &&


The logical && operator doesn't check second condition if first condition is false. It checks
second condition only if first one is true.
class OperatorExample
{
void display()
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c); //false && true = false
}
}
Java OR Operator Example: Logical ||
The logical || operator doesn't check second condition if first condition is true. It checks
second condition only if first one is false.
class OperatorExample
{
void display()
{
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
}

Pre increment/post incrementOperator

It is the unary operator that increment or decrement the value of the variable by 1.

int a = 10;
Int b = 10;
a++;
b--;
System.out.println(a);
System.out.println(b);

Pre increment – here the ++ operator is placed before the operand. Example ++a
Here first the value of the variable is incremented then the value is taken.
post increment - here the ++ operator is placed after the operand. Example a++
Here first the value is taken and then the value of the variable is incremented.
SAME THING HAPPENS IN THE CASE OF PRE DECREMENT AND POST DECREMENT OPERTOR.
Example:
int a = 5, b = 0;
b = ++a;
System.out.println(b);
Output :6
A b
5 0
6 6

int a = 5, b = 0;
b = a++;
System.out.println(b);
Output :5

A b
5 0
6 5

Data Type
Data Type: Data types are means to identify different types of data. Datatypes hold different
values. There are two types of datatypes in JavaScript: Primitive and Non-Primitive.

Primitive data types: The primitive data types are the part of the language which include
boolean, char, byte, short, int, long, float and double.
Non-primitive data types: The non-primitive or reference data types are constructed from
primitive data type, which includes include Classes, Interfaces, and Arrays.

• Numeric Integral type


byte (1 byte)
Byte data type is an 8-bit signed integer
Range -128 (-2^7) to 127 (2^7 -1)
Default value is 0
Example − byte a = 100, byte b = -50

short (2 bytes)
Short data type is a 16-bit signed two's complement integer
Range -32,768 (-2^15) to 32,767 (inclusive) (2^15 -1)
The default value is 0.
Example − short s = 10000, short r = -20000

int (4 bytes)
Int data type is a 32-bit signed integer.
Range is (-2^31) to (inclusive) (2^31 -1)
The default value is 0
Example − int a = 100000, int b = -200000

long (8 bytes)
Long data type is a 64-bit signed integer
Range is (-2^63) to (inclusive)(2^63 -1)
Default value is 0L
Example − long a = 100000L, long b = -200000L

• Fractional Numeric type


float(4 bytes)
Float is mainly used to save memory in large arrays of floating point numbers
Default value is 0.0f
Float data type - precision up to 6 digits
Example − float f1 = 234.5f

double(8 bytes)
Default value is 0.0d
Float data type - precision up to 15 digits
Example − double d1 = 123.4

• boolean type and char type


boolean(1 byte, 1 bit reserved)
boolean data type represents one bit of information
There are only two possible values: true and false
This data type is used for logical testing - true/false conditions
Default value is false
Example − boolean one = true
char(2 bytes)
char data type is a single 16-bit Unicode character
Range is 0 to 65,535 inclusive
Char data type is used to store any character
Example − char letter A = 'A'

Reference/Non-primitive type:
Example:
String is a class and a non-primitive datatype in JAVA which can store values within double quotes.
String nm=”HELLO WORLD”

Note :Math.pow()

The java.lang.Math class contains methods for performing basic numeric operations such as the
elementary exponential, logarithm, square root, and trigonometric functions.

The Math.pow() is the function of java.lang package. It is used to calculate a number raise to the
power of some other number. This function accepts two parameters and returns the value of first
parameter raised to the second parameter.The return type of Math.pow() is double.

System.out.println(Math.pow(a,b));

Math.sqrt()
f
The sqrt() method of java.lang.Math class returns the square root of a number.Return type is double.

Syntax - Math.sqrt(x)

A few programs to do:

1. WAP that will accept marks of English, maths and computer as parameters and calculate
total and average of the marks.

2. WAP in java which will provide the sum, difference, product , quotient and reminder of two
numbers. Two numbers will be passed as the parameter of a function.

3. WAP which will accept the side of a square room and find out the area of the room.
Calculate the number of marbles required to cover the floor by the marbles of 2 X 2 size. If
each marble costs rs 150, what will be the total cost to cover the floor.

4. WAP to determine the length of the wooden strip required to frame a photograph of length
is 30 cm and breadth is 25 cm.

5. WAP to accept the length and breadth of a park. If you want to fence it with 4 rows of wires
at each side, how much wire is required?

6. A proof reader is paid rs50 per page for proofreading. WAP to accept the number of pages
he reads in 1st, 2nd, 3rd and 4th week of a month and calculate his earning of the month.
7. WAP that will accept the temperature in Celsius and change to Fahrenheit. Display both the
temperature. Enter the temperature by passing it as the parameter of a function.

8. WAP to find the area of the triangle using Heron’s formula. Accept the value of side by
passing the parameter to the function.

Area = (s(s-a) (s-b) (s-c))1/2

S = (a+b+c)/2

9. WAP to find the area of equilateral triangle. Accept the value of side by passing the
parameter to the function.

Area of an Equilateral Triangle = A = (√3)/4 × side2

10. WAP to find the area of right angle triangle. Accept the value of base and height by passing
the parameter to the function.

Area of a Right Triangle = A = ½ × Base × Height(Perpendicular distance)

11. Write the corresponding java expression for the following:-

Sample example: 2- y2 + 4y5 ( Ans: 2-y*y+4*Math.pow(y,5))

1. (a+b)/(3ab – b3)

2. p + q/ (r + s)4

3. (a2 + b2 + c2)1/2

12. WAP in java to check whether a number is ODD or not.

13. WAP in java to check the divisibility of number by 3.

14. WAP in java to check the divisibility of number by 5.

15. WAP in java to check the divisibility of number by 7.

16. WAP in java where you will pass the product name, quantity you want to buy and the unit
price as the parameter of the method. Calculate and print total price and discount which will
be calculated as per the following table.

Total Discount
<10000 0%
10001 - 30000 10%
30001 – 50000 20%
>50000 30%

17. WAP in java where you will pass the student name and marks of 3 subjects as the parameter
of the method. Calculate and print total and average and grade as per the following table.

Assume the marks are out of 100.

AVG GRADE
>= 90 A
70 – 89 B
50 – 69 C
< 50 D
18. WAP in java where you will pass the annual income as the parameter of the method.
Calculate and print taxable amount which will be calculated as per the following table.

INCOME TAX
<=100000 NO TAX
100001- 250000 10%
250001 – 500000 20%
>500000 30%

19. WAP in java which will accept water consumption of a consumer as parameters of a method
and calculate water tax based on the following chart.

Water consumed in Tax


gallons
>500 2000.00
300 – 499 1650.00
150 – 299 1250.00
75 – 149 750.00
<75 450.00

20. WAP in java which will accept total sales of a salesman as parameters of a method and
calculate the commission based on the following chart.

Sales commission
>100000 25%
80001-100000 22%
60001 – 80000 20%
40001- 60000 15%
Less than equal to 40000 12%

21. WAP in java which will accept two numbers as parameters of a method and check whether
number 1 is greater lesser or equal to number 2.

22. 2. Write a Java program that accepts a number as the parameter of the method and
generates an integer between 1 and 7 and displays the name of the weekday.

Input: 3

Output : Tuesday

Input: 5

Output : Thursday

Input : any number other than 1 to 7

Output : Wrong Entry

23. Write a Java program that takes a year as the parameter of the method and print whether
that year is a leap year or not.

Clue: Check if year is divisible by 4 but not 100

Check if year is divisible by 400

24. Wap to calculate and print the side of the room whose area is 240.25 sqm and is square in
shape.
25. Predict the final output from the codes given:
a. int a=3,b=4;
a+=a++ - ++b - a + b;
b-=b-- / ++a;
System.out.println(a+","+b);

b. int a=2,b=6;
if(a/b>2 || b%3!=0)
b-=--a - ++b - a + b-- ;
else
b%=b-- / ++a;
System.out.println(a+","+b);
END

You might also like