0% found this document useful (0 votes)
29 views22 pages

Program Coding

Uploaded by

Rishav Roy
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
29 views22 pages

Program Coding

Uploaded by

Rishav Roy
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 22

Computer program: It can be defined as a collection of instructions to perform a specific

task.
The process of writing a program is called program coding or programming.
All the programs running on a computer are written by using different types of
programming languages.

Procedural-Oriented programming or POP in brief. It is a programming language that is


based on structured programming. The code in POP is written to break down the tasks into
data structures, subroutines, and a collection of variables.

POP is the oldest form of programming language. The codes in the POP generally carry
sequences of procedural steps that will be performed during the program's running.
Examples of Procedural-Oriented programming are C, BASIC, PASCAL, COBOL, FORTRAN,
etc.

Object-Oriented Programming or OOP is another type of high-level programming


language. The OOP is based on the concept of object. It is one of the most widely used
programming languages. The object in OOP are instances of classes known as the blueprint
of objects.

Object-Oriented programming is the most popular programming language which carries


data as attributes and code-like methods. The popular example of OOP in Java, C++, C#,
Python, Objective-C, Scala, PHP, JavaScript, Dart, Swift, Ruby, Perl, etc.

Procedural-Oriented Programming Object-Oriented Programming


It is a procedural model-oriented It is an object model-based
programming language. programming language.
It is known as POP It is known as OOP.
Top-down approach. Bottom-up approach.
Access modifiers are not supported. Access modifiers are supported.
Security and accessibility are
Functions are preferred over data.
preferred.
Runs faster than OOP. Runs slower than POP.
Low -Level : Machine language(0 and 1)

Assembly language

JAVA is an object-oriented and high-level programming language. It was developed by James


Gosling at Sun Microsystems in 1995.
It was acquired by Oracle in 2010.
Initially Java was used to develop internet-based applications called Applets.
Java follows the Write Once Run Anywhere (WORA) principle.
Java is a platform-independent language.
FEATURES of Java
 Simple: Java is a relatively simple structure and clearly defined syntax.
 Case Sensitive: Java is a case-sensitive language.
 Object-Oriented: Support object-oriented programming concepts of classes and
objects. The programs are built around objects that combine both data and
functionality.
 Platform independent: A Java program can run on any platform without making
changes to it.
 Secure: Java is a secure programming language. It provides different types of
authentication techniques that are based on public-key encryption.
 Robust: Java makes an effort to eliminate error-prone situations by emphasizing
mainly on compile time error checking and runtime checking.
Classes and Objects.
 Object − Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behaviors – wagging the tail, barking, eating. An object
is an instance of a class.

 Class − A class can be defined as a template/blueprint that describes the


behavior/state that the object of its type support.

Objects in Java

If we consider the real-world, we can find many objects around us, cars, dogs, humans, etc.
All these objects have a state and a behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking,
wagging the tail, running.
If you compare the software object with a real-world object, they have very similar
characteristics.
Software objects also have a state and a behavior. A software object's state is stored in
fields and behavior is shown via methods.
So in software development, methods operate on the internal state of an object and the
object-to-object communication is done via methods.
Classes in Java
A class is a blueprint from which individual objects are created.
Following is a sample of a class.
Class: Car – No of Wheel, Colour, Speed, SafetyFeatures (Property/data/state)
Class: behaviour – Running(), turning(),

Object: Swift, i10, HondaCity.

Example
public class Dog {
String breed;
int age;
String color;

void barking() {

void hungry() {

void sleeping() {

}
}

Where to write JAVA program ?


Initially we used simple text editors such as Notepad to develop JAVA programs.
Now we have different types of IDE (Integrated Development Environment) available free of
cost.
1. Netbeans
2. Eclipse
3. BlueJ: It is for beginners. Has inbuilt editor, debugger and viewer.

Structure of a JAVA Program

Basic Fundamentals of JAVA

TOKENS in JAVA
For example, consider the following code.

public class Demo


{
public static void main(String args[])
{
System.out.println("javatpoint");
}
}

In the above code snippet, public, class, Demo, {, static, void, main, (, String, args, [, ], ),
System, ., out, println, javatpoint, etc. are the Java tokens.

Types of Tokens
Java token includes the following:

o Identifiers
o Keywords
o Literals
o Operators
o Separators
o Comments

Identifier: Identifiers are used to name a variable, constant, function/method, class, and
array. It usually defined by the user. It uses letters, underscores, or a dollar sign as the first
character.

Remember that the identifier name must be different from the reserved keywords.

There are some rules to declare identifiers are:

o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot
start with digits but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.
o No special symbols like !, @, #, % etc can be used

Some valid identifiers are:

1. PhoneNumber
2. PRICE
3. radius
4. a
5. a1
6. _phonenumber
7. $circumference
8. jagged_array
9. 12radius //invalid

Keywords: These are the pre-defined reserved words of any programming language.
Each keyword has a special meaning to the JAVA compiler. It is always written in lower
case. Java provides the following keywords:

Note (in the list): const, goto not used


(not in the list): true, false, null used in java

Literals: In programming, literal is a notation that represents a fixed value (constant) in the
source code. It is defined by the programmer. Java provides five types of literals are as
follows:

o Integer
o Floating Point
o Character
o String
o Boolean
Literal Type

23 int

9.86 double

false, true boolean

'K', '7', '-' char

"Sajal", “java”, “This is my school” String

Operators: In programming, operators are the special symbol that tells the compiler to
perform a special operation. Java provides different types of operators that can be
classified according to the functionality they provide. There are five types of operators in
Java, are as follows:

o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Unary Operators
o Logical Operators

Operator Symbols

Arithmetic +,-,/,*,%

Unary ++ , - - , !

Assignment = , += , -= , *= , /= , %=

Relational ==, != , < , >, <= , >=

Logical && , ||

Logical AND &&


Condition1 Condition2 Result
True True True
True False False
False True False
False False False
Logical OR ||
Condition1 Condition2 Result
True True True
True False True
False True True
False False False

Separators: The separators in Java is also known as punctuators. There are nine separators
in Java, are as follows:

separator ; , . ( ) { } [ ]

o Square Brackets []: It is used to define array elements. A pair of square brackets
represents the single-dimensional array, two pairs of square brackets represent the
two-dimensional array.
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a code block.
o Comma (,): It is used to separate two values, statements, and parameters.
o Semicolon (;): It is the symbol that can be found at end of the statements. It
separates the two statements.
o Period (.): It separates the package name form the sub-packages and class. It also
separates a variable or method from a reference variable.

Comments: Comments allow us to specify additional information about the Java code for
understanding the code better. Java compiler do not execute comments. Java provides the
following two types of comments:

o Line Oriented: It begins with a pair of forwarding slashes (//).


o Block-Oriented: It begins with /* and continues until it founds */.
What is a Variable in Java?

Variable in Java is a data container that stores the data values during Java program
execution. Variable is a memory location name of the data.

Every variable is assigned data type which designates the type and quantity of value it can
hold.

Variable Declaration:
To declare a variable, you must specify the data type & give the variable a unique name.

Examples of other Valid Declarations are


int a,b,c;

float pi;

double d;

char a;

String name;

Variable Initialization:
To initialize a variable, you must assign it a valid value.

Example of other Valid Initializations are


pi =3.14f;

do =20.22;
a=’v’;

name = “Sajal”;

You can combine variable declaration and initialization.

Example :
int a=2,b=4,c=6;

float pi=3.14f;

double do=20.22;

char a=’v’;

String name = “Sajal”;

What is Data Type in Java?


Data Types in Java are defined as specifiers that allocate different sizes and types of values
that can be stored in the variable or an identifier. Java has a rich set of data types. Data
types in Java can be divided into two parts :

1. Primitive Data Types :- which include integer, character, boolean, and float
2. Non-primitive Data Types :- which include classes, arrays and interfaces.
Data Type Default size Min Value Max Value
Byte 1 byte -128 127
Short 2 bytes -32768 32676
Int 4 bytes -2147483648 2147483647
Long 8 bytes
Float 4 bytes
Double 8 bytes
Boolean 1 bit 0 1
Char 2 bytes

public class _HelloWorld


{
static void main()
{
byte a; // 1 byte
short b; // 2 bytes
int c; // 4 bytes
long d; // 8 bytes
char e; // 2 bytes
float f; //4 bytes
double g;// 8 bytes
boolean h;// 1 bit
String name; // non-primitive

a = -128; // -128 to +127


b = 32767; //-32768 to 32767
c = 435345 ; // -2147483648 to 2147483647
d = 734; //-9223372036854775808 to 9223372036854775807

e = 'K'; //65536 chan]racters; code against each character is called ASCII - Americal
Standard Code for Information Interchange
f = 1.2f;

g = 1.2;
h = false;
name = "Sajal";

System.out.println(-128+7.8); // -120.2
System.out.println(23.5+7.8); // 31.3
System.out.println('g'+7.8); // 103 + 7.8= 110.8
System.out.println("Hello World !"+ 7.8); //Hello World7.8
System.out.println(false);

Java Variable Type Conversion & Type Casting


A variable of one type can receive the value of another type. Here there are 2 cases –
Case 1) Variable of smaller capacity is be assigned to another variable of bigger capacity.

This process is Automatic, and non-explicit is known as Conversion

Case 2) Variable of larger capacity is be assigned to another variable of smaller capacity

In such cases, you have to explicitly specify the type cast operator. This process is known
as Type Casting.

In case, you do not specify a type cast operator; the compiler gives an error. Since this rule
is enforced by the compiler, it makes the programmer aware that the conversion he is
about to do may cause some loss in data and prevents accidental losses.

Exercise
A. Tick the correct option
1. Which of these is not a feature of the Java language?
a) it is a platform-dependent language
2. Which of the following symbols are used to write comments in Java?
d) all of these
3. Which of these is used to store values in memory?
a) variables
4. Which of the following is the developer of Java?
b) James Gosling
5. Which of the following variables is invalid?
c) Priya $Pay
B. True/False
1. In Java, keywords are reserved words. T
2. Java code is converted into bytecode by its compiler. T
3. The values on which an operator works are called operands. T
4. IDE stands for Integrated Document Environment. F
5. The = operator is used to check the equality between two values. F
C. Matching
1. == c. Equality operator
2. = a. Assignment operator
3. || d. Logical OR operator
4. ++ b. Unary operator

D. Fill in the blanks


1. Java is a High-level language.
2. The println() method displays the output on the terminal.
3. Operators are special symbols used to perform arithmetic or logical
computations.
4. An identifier is the name given to an object in a Java program.
5. The int is a primitive data type.

A. Short answer type questions


1. What is Java?
Java is an object-oriented and high-level programming language. It was
developed by James Gosling at Sun Microsystems in 1995. Java is a platform-
independent language.
2. Explain the use of assignment operator.
Assignment operators are used to assign values to operands. Assignment
operator is equal (=).
Eg., x = 5;
This operator can also be used with arithmetic operators to make the
shorthand assignment operators. The shorthand assignment operators perform
calculations and assign the results to the variable present on the left hand side
of the operator.
E.g, x += 5
3. Define arithmetic operator
Arithmetic operators are used to do basic mathematical calculations. These are
known as binary operators, which means they require two operands to
perform calculations.
e.g, a+b , a-b, a*b, a/b, a%b
B. Long answer type questions
1. List any four features of Java
 Case Sensitive: Java is a case-sensitive language.
 Object-Oriented: Support object-oriented programming concepts of classes
and objects. The programs are built around objects that combine both data
and functionality.
 Platform independent: A Java program can run on any platform without
making changes to it.
 Secure: Java is a secure programming language. It provides different types
of authentication techniques that are based on public-key encryption.

2. What are logical operators? Write the names of any two logical operators.
Logical operators are used to combine multiple conditions and evaluate them.
They return a Boolean true or false as result.
e.g,
&& (AND) -> (a>4 && b<5)
|| (OR) -> (a>4 || b<5)
! (NOT) -> !(a>4)

3. What is the use of unary operators? How many unary operators are there in Java?
Unary operators are special operators that require only one operand or value to
perform operations.
Java provides only two unary operators, which are increment and decrement.

++ -> b = a++;
‘-- -> b = a--;

b = a++ + ++a;

b = a++ + a++;
b = ++a + a++;

b = ++a + ++a;

C. What will be output of these Java codes

1 public class rad 14.444


{
public static void Main()
{
double r,c;
r = 2.3;
c = 2 * 3.14 * r;
System.out.println(c);
}
}
2 public class A GST to be paid:0.1
{ Total invoice value:2.1
public static void Main()
{
double s,GST, inv;
s = 2;
GST = 5 * s/100;
inv = s + GST;
System.out.println("GST to be paid:"+ GST);
System.out.println("Total invoice value:"+ inv);
}
}
3 public class program Value of a is20
{ Value of b is10
public static void Main()
{
int a,b,c;
a = 10;
b = 20;
c = a;
a = b;
b = c;
System.out.println("Value of a is:"+ a);
System.out.println("Value of b is:"+ b);
}
}
4 public class A1 Kittu Sharma
{
public static void Main()
{
String first_name = "Kittu";
String last_name = "Sharma";
String name = first_name +" "+last_name;
System.out.println(name);
}
}
5 public class B 20
{
public static void Main()
{
int age = 17;
age += 1;
age++;
++age;
System.out.println(age);
}
}
6 public class C6 false
{ true
public static void Main()
{
int a = 5;
int b = 5;
System.out.println(a > b);
System.out.println (a == b);
}
}
7 public class C7 12
{ 14
public static void Main()
{
int a = 5;
int b = 6;
System.out.println(a++ + ++a);
System.out.println (++b + b++);
}
}

D. Find the errors in the following Java codes

111111 public class program int b = 20;


{
public static void Main()
{
int a = 10;
int b = 20
int c = a + b;
System.out.println("The value of c
is:"+c);
}
}
2 public class program Int a = 10;
{
public static void Main()
{
int a == 10;
System.out.println(a);
}
}
3 public class D3 }
{
public static void Main()
{
int a = 5;
String name = "Chirag";
System.out.println(a+name);
}
}|
4 public class D4
{ System.out.println("Welcome");
public static void Main()
{
System.out("Welcome");
}
}

1. WAP a program to accept 3 sides of a triangle as argument and find the area.
Class area {
void display(double a, double b, double c) {
double s, t, area;
s = (a+b+c)/2;
t = s*(s-a)*(s-b)*(s-c);
area = Math.sqrt(t);
System.out.println("The area is ="+area);
}}
Variable list
Name Type Description
a Double First side of the triangle
b Double Second side of the triangle
c Double Third side of the triangle
s Double Stores half of the perimeters
t Double Temporary storage for intermediate calculation
area Double Stores the area of the triangle

2. WAP a program to accept 3 integers and find their average.


Class calc_avg {
void display(int a, int b, int c) {
double avg;
avg = (a+b+c)/3.0;
System.out.println("The average is ="+avg);
}}
Variable list
Name Type Description
a Int First integer
b Int Second integer
c int Third integer
Avg Double Stores the average of 3 integers

3. WAP to accept the price of 3 items, and find the total bill amount if 18% GST is
applied.
Class bill {
Void display(double a, double b, double c){
double total, final_bill;
total = a+b+c;
final_bill = total + total * 0.18;
System.out.println(“The final bill amount = ”+final_bill);
}
}
Variable list
Name Type Description
a Double Price of first item
b Double Price of Second item
c Double Price of third item
Total Double Stores the sum of price of 3 items
final_bill Double Stores final bill amount including GST

You might also like