[Go to site: main page, start]

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

Java Programming Basics and Concepts

Uploaded by

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

Java Programming Basics and Concepts

Uploaded by

Rishav Roy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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[])
{
[Link]("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";

[Link](-128+7.8); // -120.2
[Link](23.5+7.8); // 31.3
[Link]('g'+7.8); // 103 + 7.8= 110.8
[Link]("Hello World !"+ 7.8); //Hello World7.8
[Link](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;
[Link](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;
[Link]("GST to be paid:"+ GST);
[Link]("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;
[Link]("Value of a is:"+ a);
[Link]("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;
[Link](name);
}
}
5 public class B 20
{
public static void Main()
{
int age = 17;
age += 1;
age++;
++age;
[Link](age);
}
}
6 public class C6 false
{ true
public static void Main()
{
int a = 5;
int b = 5;
[Link](a > b);
[Link] (a == b);
}
}
7 public class C7 12
{ 14
public static void Main()
{
int a = 5;
int b = 6;
[Link](a++ + ++a);
[Link] (++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;
[Link]("The value of c
is:"+c);
}
}
2 public class program Int a = 10;
{
public static void Main()
{
int a == 10;
[Link](a);
}
}
3 public class D3 }
{
public static void Main()
{
int a = 5;
String name = "Chirag";
[Link](a+name);
}
}|
4 public class D4
{ [Link]("Welcome");
public static void Main()
{
[Link]("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 = [Link](t);
[Link]("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;
[Link]("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;
[Link](“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

Common questions

Powered by AI

Type conversion in Java is the process through which a variable of one type is automatically converted to another type with a larger capacity, known as implicit casting or widening conversion, avoiding data loss. For example, assigning an int to a long. Type casting, however, requires explicitly converting a larger capacity type to a smaller one, called narrowing conversion, potentially leading to data loss unless handled carefully. This explicit conversion is done using type cast operators, ensuring programmers are conscious of conversion implications. Both processes are crucial for handling different data requirements and ensuring that variables fit the necessary data contexts in expressions or operations .

In Java, classes and objects are used to model real-world entities by encapsulating data and behavior within defined structures. A class in Java serves as a blueprint or template describing the possible states (attributes) and behaviors (methods) that its objects can exhibit. Real-world entities, such as a car or dog, can be represented with classes wherein attributes like 'color' and 'speed' or 'name' and 'breed' constitute their state, and methods like 'running' or 'barking' reflect their behaviors. Thus, the structure of classes and objects mirrors real-world objects by aligning with the concepts of state and behavior inherent in actual entities, enabling a seamless transition from conceptual models to software representations .

Procedural-Oriented Programming (POP) and Object-Oriented Programming (OOP) differ primarily in their approach to code organization and execution. POP follows a top-down approach, focusing on breaking tasks into sequential procedures or subroutines, without support for access modifiers. This structure often results in faster execution but less modularity and security. Examples include languages like C and BASIC. In contrast, OOP employs a bottom-up approach, centering around objects that combine data and behavior, along with the use of classes as blueprints for objects. OOP supports access modifiers, which enhance security and data encapsulation, but it generally runs slower than POP. Popular OOP languages include Java and C++ .

Unary operators in Java are operators that operate on a single operand to perform various operations, primarily for incrementing, decrementing, or negating values. The increment operator (++) increases the value of a variable by one, whereas the decrement operator (--) decreases it by one. For instance, using a++ increments the value of 'a' after its current value is used in an expression, while ++a increments 'a' before use. Unary operators simplify operations that increment, decrement, or negate variable values, playing a crucial role in loops and conditional logic statements .

Logical operators in Java, such as && (AND), || (OR), and ! (NOT), are used to evaluate Boolean expressions and make decisions based on multiple conditions. They enable the combination of two or more conditions, allowing for complex decision-making within control structures like if statements and loops. For example, the && operator returns true if both operands are true, the || operator returns true if at least one operand is true, and the ! operator inverts the Boolean value. These operators are vital for implementing logic that governs the flow of a program, determining which code blocks execute under specified conditions .

Integrated Development Environments (IDEs) significantly enhance Java programming by providing a comprehensive suite of tools that streamline code development, testing, and debugging. IDEs like Eclipse, NetBeans, and BlueJ offer features such as code editors with syntax highlighting, debugging tools, and compilation capabilities, which help reduce coding errors and improve productivity. Specifically, BlueJ is tailored for beginners, providing an inbuilt editor, debugger, and viewer, making it particularly beneficial for learning Java. By integrating various development activities into a single application, IDEs facilitate a more efficient Java development process .

Variables and data types in Java play a critical role in storing and manipulating data during program execution. Variables act as named storage locations for data, each assigned a specific data type that constraints the form and size of data it can hold. Primitive data types, like int and char, facilitate memory-efficient operations with fundamental data, whereas non-primitive data types, such as arrays and classes, allow the representation of more complex data structures. By clearly defining variable types, Java ensures proper data handling and encourages effective resource management, contributing to robust and error-free programming .

Java's high-level abstraction provides significant advantages over low-level programming languages by offering a more user-friendly syntax resembling human language, which makes programming more accessible and easier to understand. Unlike low-level languages tied closely to hardware instructions, Java abstracts complex machine-level operations, enabling developers to focus on logic and functionality rather than hardware-specific details. Additionally, Java features like garbage collection, strong memory management, and robust error handling safeguard against common programming pitfalls, resulting in safer and more maintainable code. These advantages facilitate developing complex applications efficiently across multiple platforms .

Java is considered platform-independent due to its bytecode, which can be executed on any device with a Java Virtual Machine (JVM), adhering to the Write Once Run Anywhere (WORA) principle. This allows developers to run Java applications on different platforms without modification. Additionally, Java's built-in security features, such as the absence of explicit pointer manipulation and the provision of a security manager, which allows developers to specify access rights for applications, contribute to its robustness and safety. These features, combined with its object-oriented nature, make Java a versatile and reliable choice for developing internet-based applications and enterprise-level software .

Java tokens are the smallest elements of a Java program that have meaning to the compiler, serving as fundamental building blocks of code syntax. They include keywords, identifiers, literals, operators, and separators. Keywords are predefined reserved words with special meanings, identifiers name entities like variables and classes, and literals represent constant values. Operators perform specific actions on operands, while separators delineate code structure. These tokens collectively define the syntactic structure of Java programs, facilitating the translation of code into executable actions. Mastery of tokens is crucial for writing syntactically correct and interpretable programs .

You might also like