Unit 1:
Evolution of High Level Language
High-level programming languages have evolved significantly from early machine-level code
to modern, user-friendly languages.
1st Generation (1940s–1950s): Machine & Assembly Language
⚫ Machine Language (1GL): Binary code (0s and 1s), hardware-specific, difficult to read/write.
⚫ Assembly Language (2GL): Uses mnemonics (e.g., MOV, ADD) for instructions, still hardware-
specific.
2nd Generation (1950s–1960s): Early High-Level Languages (3GLs)
⚫ FORTRAN (1957): First high-level language, designed for scientific computing.
⚫ COBOL (1959): Business-oriented with English-like syntax.
⚫ LISP (1958): Functional language used in AI.
⚫ ALGOL (1958): Introduced structured programming, influenced many future languages.
3rd Generation (1970s–1980s): Structured Programming
⚫ C (1972): Powerful and portable, used in system programming.
⚫ Pascal (1970): Popular for teaching structured programming.
⚫ BASIC (1964): Easy to learn, educational use.
4th Generation (1980s–1990s): Productivity-Oriented Languages
⚫ SQL: Query language for managing databases.
⚫ MATLAB: Math-focused with built-in matrix handling.
5th Generation (1990s–Present): Object-Oriented & Modern Languages
⚫ C++: Object-oriented extension of C.
⚫ Java: Platform independence via JVM.
⚫ Python: Simple, readable syntax, powerful libraries.
⚫ Ruby: Web development with Rails.
⚫ PHP: Server-side scripting for web apps.
Recent Trends (2000s–Present): Modern Paradigms
⚫ JavaScript: Essential for web applications.
⚫ Kotlin: Modern alternative to Java for Android.
⚫ Swift: Apple’s language for iOS/macOS.
⚫ Go (Golang): Fast and concurrent, developed by Google.
⚫ Rust: Memory safety and performance.
⚫ Scala, Haskell: Functional programming.
Generation Period Language Features
Examples
1st Gen 1940s Machine Binary,
Code hardware-
specific
2nd Gen 1950s Assembly Mnemonics,
slightly
readable
3rd Gen 1960s–80s FORTRAN, High-level,
C, BASIC structured
4th Gen 1980s SQL, Task-specific,
MATLAB declarative
5th Gen 1990s Java, Python, Object-
C++ oriented,
1
portable
Modern 2000s–Now JavaScript, Web,
Go, Kotlin, concurrent,
Rust safe
What is Software Complexity?
Software complexity means how hard or easy it is to understand, build, test, and change a
software program.
- The bigger and more features a software has, the more complex it becomes.
- Complex software is harder to fix, improve, and understand.
Types of Software Complexity
1. Structural Complexity
- Related to how parts of the program (functions, classes) are connected.
- If everything is linked too much, it becomes messy and hard to manage.
Example: A big program where changing one part breaks others.
2. Cyclomatic Complexity
- Counts how many different paths or decisions exist in the program.
- More paths = more tests needed = more complex.
Example: A program with many if-else conditions is harder to test.
3. Structural Complexity
Describes how different parts (modules/functions) of a program are connected.
More connections between modules = harder to understand, maintain, and test.
Example: A program where every function depends on many other functions is difficult to
change without causing errors elsewhere.
4. Essential Complexity
It means the problem itself is hard to understand, even if the code is simple.
Example: Dividing a number by zero is not allowed in maths. Even if the code is short, you
still need to understand this rule.
Here are some attributes of software complexity
• Size – How big the program is (number of lines, functions, modules, etc.).
More code means more complexity.
• Control Flow – How the program moves from one step to another (if, loops, etc.).
More branches and conditions make it harder to follow.
• Data Flow – How data moves and changes in the program.
Tracking data through many variables increases complexity.
• Modularity – How well the program is divided into separate parts (modules).
Good modularity reduces complexity.
• Coupling – How much different parts of the program depend on each other.
More dependency means more complexity.
• Cohesion – How closely related the functions in a module are.
High cohesion (all parts doing one task) makes it simpler.
2
Object-Oriented Programming
Object-oriented programming (OOP) is a programming paradigm based on the concept
of “objects”, which may contain data in the form of fields, often known as attributes
and code in the form of procedures, often known as methods.
Object-Oriented Programming (OOP) in Java is a fundamental concept that helps in
designing and organizing software.
The OOP concepts:
1. Object
2. Class
3. Abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism
Objects:
The Object is the real-time entity having some state and behaviour. In Java,
Object is an instance of the class having the instance variables like the state of
the object and the methods as the behaviour of the object. The object of a class
can be created by using the new keyword in Java Programming language.
Key points about object
1. An object is a real-world entity.
2. An object is a runtime entity.
3. The object is an entity which has state and behaviour.
4. The object is an instance of a class.
example
Car is a object which has state (name, color, model, number) and behaviour (speed, etc).
Creating the Object
Using the new keyword is the most popular way to create an object or
instance of the class. When we create an instance of the class by using the
new keyword, it allocates memory for the newly created object and also
returns the reference of that object to that memory.
The syntax for creating an object is:
3
ClassName objectname= new ClassName();
Example: Student S1 = new Student();
Class
It is a template/Blueprint from which objects are created. There are two types of class
Pre-defined class
Some of the predefined classes in java are
• Object Class: Object class is the root of Java class hierarchy.
• Math Class: Math class is present in java.
• String Class: String class is present in java.
• System Class: System class is present in java.
• Scanner Class: Scanner class is present in java
User defined class
A class which is created by java programmer is called user defined class. Some of the user-
defined classes are used in java i.e., car, furniture, student.
Example
Class Student
{
--------------------------- // data or fields or variables
// methods
}
Data Abstraction
Data abstraction is the process of hiding certain details and showing only
essential information to the user. Abstraction can be achieved with either
abstract classes or interfaces.
Data Encapsulation
Encapsulation in Java is a mechanism of wrapping the data (variables) and
code acting on the data (methods) together as a single unit is called as
data encapsulation. In encapsulation, the variables of a class will be hidden
4
from other classes, and can be accessed only through the methods
of their current class.
Inheritance
Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object is called as inheritance. It is an
important part of OOPs (Object Oriented programming system). The idea
behind inheritance in Java is that you can create new classes that are built upon
existing classes.
Polymorphism
The term "polymorphism" means "many forms". In object-oriented
programming, polymorphism is useful when you want to create multiple
forms with the same name of a single entity. To implement polymorphism in
Java, we use two concepts method overloading and method overriding.
The method overloading is performed in the same class where we have
multiple methods with the same name but different parameters,
whereas,method overriding requires the same method name and parameters in
5
both the parent and child classes. However, the child class can modify the
method's behavior.
Advantages of OOP
•Modularity: Classes are encouraged for better modular design since a large system can be
divided into smaller, manageable components. This makes code easier to write, understand,
maintain, and debug.
• Code Reusability: OOP supports inheritance, allowing the reuse of existing source code.
Once a class is written and tested, it can be extended to create new classes with added
functionality without rewriting the source code.
•Maintainability: OOP states that programs follow principles like encapsulation, abstraction,
and modularity to be less up-to-date. In a program, you can often change one part of the system
without impacting the other parts.
• Data Security: The data is hidden through private or protected access sources. OOP ensures
sensitive data is not directly accessible from outside the class. It protects the integrity of the
data and prevents accidental or unauthorized modification.
• Scalability: OOP allows large and complex programs to scale easily. The ability to structure
a system into classes and objects ensures it can be expanded
Disadvantages of OOP Language
• The length of the programmes developed using OOP language is much larger than the
procedural approach.
• We can not apply OOP everywhere as it is not a universal language. It is applied only when it
is required. It is not suitable for all types of problems.
• Programmers need good design and coding skills for using OOP effectively.
• Proper planning is important as OOP can be a bit tricky.
• OOP takes time and practice to understand well.
OOP Languages:
Python, Java, C++, JavaScript, C#, Ruby, PHP, TypeScript, Kotlin, and R are programming
languages that support Object-Oriented Programming (OOP). These languages allow the use of
concepts like classes, objects, inheritance, encapsulation, and polymorphism to build structured
and reusable code.
Applications of OOP
OOP is used in developing real-time systems like flight simulators and traffic control systems.
It is widely applied in building GUI-based applications such as desktop software.
6
OOP helps in creating mobile apps using languages like Java, Kotlin, and Swift.
It is useful in game development for managing game objects and behaviors.
OOP is used in designing web applications with frameworks that support object-oriented code.
What is Java?
o Java is a high-level, object-oriented, and platform-independent
programming language.
o Java was developed by Sun Microsystems in the year 1995. James
Gosling is known as the father of Java.
o Before Java, its name was Oak. Since Oak was already a
registered company, so James Gosling and his team changed the name from
Oak to Java.
Features of Java
Simple: Java is designed to be easy to learn. If you understand the basic concept of
OOP.
Secure:
Java program cannot harm other system thus making it secure.
Java provides a secure means of creating Internet applications.
Java provides secure way to access web applications.
Portable:
Java programs can execute in any environment for which there is a Java run-time
system.
Java programs can run on any platform (Linux, Window, Mac OS)
Java programs can be transferred over world wide web (e.g: applets).
Object-oriented:
Java programming is object-oriented programming language.
Like C++, java provides most of the object oriented features.
Java is pure OOP Language. (while C++ is semi object oriented)
Robust:
Java encourages error-free programming by being strictly typed and performing run-
7
time checks.
Multithreaded:
Java provides integrated support for multithreaded programming.
Interpreted :
Java supports cross-platform code through the use of Java bytecode.
Bytecode can be interpreted on any platform by JVM (Java Virtual Machine).
High performance:
Bytecodes are highly optimized.
JVM can execute bytecodes much faster.
Distributed:
Java is designed with the distributed environment.
Java can be transmitted over internet.
Platform Independent
Platform Independent
A platform is the hardware or software environment in which a program
runs.
Java code can be run on multiple platforms.
Structure of Java Program
8
1. Documentation Section
The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program. The information includes the
author's name, date of creation, version, program name, company name, and
description of the program. It improves the readability of the program
Ex: //First Java Program
2. Package Declaration
The package declaration is optional. It is placed just after the documentation section. In
this section, we declare the package name in which the class is placed. Note that there
can be only one package statement in a Java program. It must be defined before any
class and interface declaration.
Example: package javatpoint; //where javatpoint is the package name
3. Import Statements
import keyword is used to import built-in and user-defined packages into java source
file. So that the class can refer to a class that is in another package by directly using its
name.
The keyword is import. The general syntax is
import package1 [.package2].[classname].*;
Example
import [Link]; //it imports the Scanner class only import
[Link].*; //it imports all the class of the [Link] package
4. Interface Section
It is an optional section. We can create an interface in this section if required. We
use the interface keyword to create an interface. An interface is a slightly different
from the class. It contains only constants and method declarations.
Example:
interface car
{
void start();
9
void stop();
}
5. Class Definition
In this section, we define the class. Without the class, we cannot create any Java
program. A Java program may conation more than one class definition. We use the
class keyword to define the class. It contains information about user-defined methods,
variables, and constants. Every Java program has at least one class that contains the
main() method.
Example:
class Student //class definition
{
}
6. Main Method Class
In this section, we define the main() method. It is essential for all Java programs.
Because the execution of all Java programs starts from the main() method. In other
words, it is an entry point of the class. It must be inside the class. Inside the main
method, we create objects and call the methods.
Example:
public static void main(String args[])
{
}
Example:
10
Components of Java:
The programming environment of Java consists of 3 components mainly
⚫ JDK
⚫ JRE
⚫ JVM
JDK(Java Development Kit)
⚫ JDK is an acronym for Java Development Kit. The Java
Development Kit (JDK) is a software development environment which is
used to develop Java applications.
⚫ It physically exists. It contains JRE + development tools.
⚫ The JDK contains a private Java Virtual Machine (JVM) and a few other
resources such as an interpreter/loader (java), a compiler (javac), an archiver
(jar), a documentation generator (Javadoc), etc. to complete the development
of a Java Application.
11
What is JRE(Java Runtime Environment)? JRE
JRE is an acronym for Java Runtime Environment.
It is a software package that provides Java class libraries, JVM and components
required to run Java applications.
It contains a set of libraries + other files that JVM uses at runtime.
What is JVM?
JVM(Java Virtual Machine) is an abstract machine that enables you computer
to run Java program
When you run Java program, Java compiler first compilers your Java code to
bytecode. Then, the JVM translates byte code into machine code.
Bytecode:
Bytecode is the intermediate representation of a Java program, allowing a JVM
to translate a program into machine-level assembly instructions. When a Java
program is compiled, bytecode is generated in the form of a(.class) file. This (.class)
file contains non-runnable instructions and relies on a JVM to be interpreted.
Java tokens
Each individual characters or units used in a java program are termed as tokens. Java
program are written using these tokens and the syntax of the language. The java has
various types of tokens as follows as
12
Identifier
Keywords
Separators
Punctuators
Constants
Variables
Operators
Java Identifiers:
All Java components require names. Names used for classes, variables and methods are
called identifiers. In Java, there are several points to remember about identifiers.
They are as follows:
All identifiers should begin with a letter (A to Z or a to z), or an underscore (_). After
the first character, identifiers can have any combination of characters. A keyword
cannot be used as an identifier.
“Most importantly identifiers are case sensitive”.
Rules for identifiers
• First letter must be an alphabet followed by letters or digits.
• Special characters are not allowed except underscore( _ ) and $ sign.
• It cannot be keywords.
• They can be of any length
• Uppercase and lowercase letters are distint.
Keywords
13
Constants
Any fixed value that does not change during the execution of a program is known as
constant.
The general syntax is
final datatype identifier_name=value;
Example: final int PI=3.14;
where final is a keyword, int is a datatype, PI is variable name, 3.14 is value.
⚫ Integer Constant: Fixed whole numbers like 25 (e.g., int age = 25;).
14
⚫ Real Constant: Fixed decimal numbers like 3.14 (e.g., double pi = 3.14;).
⚫ Character Constant: Single characters like 'A' (e.g., char grade = 'A';).
⚫ String Constant: Text in double quotes like "Hello" (e.g., String message = "Hello";).
Data types
In Java, each type of data (such as integer, character, etc. ) is predefined as part of the
programming language and all constants or variables defined within a given program
must be described with one of the data types.
Data types represent the different values to be stored in the variable. In java, there are
two categories of data types:
a) Primitive data types
b) Non-primitive data types
1. Primitive data types: The primitive data types include boolean, char, byte,
short, int, long, float and double.
There are 8 types of primitive data types:
Type Default Size
boolean false 1 byte
char '\u0000' 2 byte
15
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0 8 byte
float 0.0 4 byte
double 0.0 8 byte
⚫ Boolean - This group includes boolean. It can have only one of two possible values, true or
false.
⚫ Characters- This group includes char, which represents symbols in a character set,
like letters and numbers. char is a 16-bit type.
⚫ Integers - This group includes byte, short, int, and long. All of these are signed,
positive and negative values.
⚫ Floating-point numbers– They are also known as real numbers. This group
includes float and double, which represent single and double precision numbers,
respectively.
Non-Primitive data types
The non-primitive data types include Strings, Arrays etc
String:
A string represents a sequence of characters for example "Javatpoint", "Hello world",
etc. String is the class of Java.
One of the ways to create a string and store a value in it is shown below:
Example: String str = "You're the best";
Variables
A variable is the holder that can hold the value while the java program is executed. A
variable is assigned with a data type. It is name of reserved area allocated in memory. In
other words, it is a name of memory location. There are three types of variables in java:
local, instance and static.
The general syntax of variable declaration
Datatype variable=value;
16
Example
int a, b, c; // Declaration of variables a, b, and c. int a
= 20, b = 30; // initialization
byte B = 22; // Declaration initializes a byte type variable B.
17
Implementing a java program
Implementation of a java application program involves a series of steps. They include:
➢ Creating the program
➢ Compiling the program
➢ Running the program
Creating the program
We can create a program using any text editor. Assume that we have entered the
following program:
class firstprogram
{
public static void main(String[] args)
{
[Link]("Computer Application");
}
}
We must save this program in a file called [Link] ensuring that the file
name contains the class name properly. This file is called the source file.
Note that all Java source files will have the extension java.
Compiling the program
To compile the program, we must run the Java Compiler javac, with the name of the
source file on the command line as shown below:
If everything is OK, the javac compiler creates a file called [Link]
containing the bytecodes of the program. Note that the compiler automatically names
the bytecode file as <classname>.class.
Syntax: to compile: javac [Link]
Example: javac [Link]
18
Running the program
To run the program, we must run the Java interpreter java, with the name of the class
file on the command line.
To run we have to use
java filename
Example:
java firstprogram
Operators
Operators in Java can be classified into 6 types:
• Arithmetic Operators.
• Assignment Operators.
• Relational Operators.
• Logical Operators.
• Unary Operators.
• Bitwise Operators
1. Arithmetic Operators in Java
Arithmetic Operators are used to perform mathematical operations like addition, subtraction,
etc. Assume that A = 10 and B = 20 for the below table.
19
2. Assignment Operators in Java
An Assignment Operator is an operator used to assign a new value to a variable. Ex: A = 10
and B = 20
Compound assignment operator:
In Java, compound assignment operators let you perform an operation and
assign the result back to the variable in a single step.
3. Relational Operators in Java
These operators compare the values on either side of them and decide the relation
among them. Assume A = 10 and B = 20.
20
4. Logical Operators in Java
The following are the Logical operators present in Java:
Oper Description Example
ator
&& True if both the operands is true a<10 && a<20
(and)
|| (or) True if either of the operands is true a<10 || a<20
True if an operand is false (complements the operand)
! !(x<10 && a<20)
(not)
21
5. Unary Operator in Java
Unary operators are the one that needs a single operand and are used to increment a
value, decrement a value.
Ope Description Example
rato
r
increments the value by 1. There is post-increment and
++ a++ and
pre-increment operators ++a
decrements the value by 1. There is post decrement and
-- a- - or - -a
pre decrement operators
6. Bitwise Operator in Java
Bitwise operations directly manipulate bits. In all computers, numbers are represented
with bits, a series of zeros and ones.
Operator Description Example
& (AND) returns bit by bit AND of input a&b
| (OR) returns OR of input values a|b
^ (XOR) returns XOR of input values a^b
~
returns the one’s complement. (all bits reversed) ~a
(Complem
ent)
7. Ternary Operators in Java
The ternary operator is a conditional operator that decreases the length of code while
performing comparisons and conditionals. This method is an alternative for using if-
else and nested if-else statements. The order of execution for this operator is from left
to right.
Syntax:
(Condition1) ? (Statement1) : (Statement2);
22
• Condition1: It is the expression to be evaluated which returns a boolean
value.
• Statement 1: It is the statement to be executed if the condition results in a
true state.
• Statement 2: It is the statement to be executed if the condition results in a
false state.
Control Structures
Java Control statements control the flow of execution in a java program, based on data
values and conditional logic used.
There are two main categories of control flow statements;
Selection statements:
a) if statement
b) if-else statement
c) Switch statement.
Loop statements:
a) while loop
b) do-while loop
c) for loop.
Selection statements:
The selection statements checks the condition only once for the program execution.
a) If Statement:
The if statement executes a block of code only if the specified expression is true. If the
value is false, then the if block is skipped and execution continues with the rest of the
program.
The simple if statement has the following syntax
if (Condition)
{
statement(s);
}
23
Example
public class programif
{
public static void main(String[] args)
{
int a = 10, b = 20; if (a > b)
[Link](“a > b”);
if (a < b) [Link](“b <
a”);
}
}
b) If-else Statement
The if-else statement is an extension of the if statement. If the condition in the if
statement fails, the statements in the else block are executed.
The if-else statement has the following syntax: if
(booleanExpression)
{
statement1;
}
else
{
statement2;
}
Example:
public class ProgramIfElse
{
public static void main(String[] args)
{
int a = 10, b = 20; if
(a > b)
{
[Link](“a > b”);
24
}
else
{
[Link](“b < a”);
}
}
}
c) Switch statement
The Java switch statement executes one statement from multiple conditions. It is like if-
else-if ladder statement.
• The case value must be of switch expression type only. The case value
must be literal or constant. It doesn't allow variables.
• The case values must be unique. In case of duplicate value, it renders
compile-time error.
• Each case statement can have a break statement which is optional. When
control reaches to the break statement, it jumps the control after the switch expression.
If a break statement is not found, it executes the next case.
• The case value can have a default label which is optional.
The general Syntax is
switch(expression)
{
case value1:
statement
break;
case value2:
//code to be executed;
break;
.......
……….
default:
code to be executed if all cases are not matched;
}
25
Example
public class SwitchExample
{
public static void main(String[] args)
{
int number=20;
switch(number)
{
case 10: [Link]("10"); break;
case 20: [Link]("20"); break;
case 30: [Link]("30"); break;
//Default case statement
default:
[Link]("Not in 10, 20 or 30");
}
}
}
Break and Continue Statement
The break and continue statements are the jump statements that are used to skip some
statements inside the loop or terminate the loop immediately without checking the test
expression. These statements can be used inside any loops such as for, while, do-while
loop.
Break: It is used to exit from a switch statement or a loop. However break statement
cannot exit from nested loops, since it can exit only from the loop containing it.
Syntax :
break;
26
Example:
Class examplebreak
{
public static void main(String args[])
{
int i; for(i=1;i<=10;i++)
{
[Link](i); if(i==5)
break;
}
}
}
Output:
1
2
3
4
5
Continue: It is used to skip the rest of the statements in the body of the loop and execution
continues until the condition is satisfied.
Syntax:
continue;
Example:
Class examplebreak
{
public static void main(String args[])
{
int i; for(i=1;i<=10;i++)
{
[Link](i); if(i==5)
continue;
}
}
}
27
Output:
1
2
3
4
5
6
7
8
9
10
Difference between break and continue statement
Break continue
➢ It is used to transfer ➢ It cannot be used in
control outside a switch switch statement
statement
➢ It is used to exit from a ➢ It is used to skip the rest of
loop the statements of loop
body
➢ Only break cannot exit ➢ In nested loops continue
from nested loops. cannot proceed to the
next iteration of the outer loop.
➢ The general form is break ➢ The general form is
continue.
d) Nested if statement
A nested if statement is an if statement placed inside another if statement. Nested if
statements are often used when you must test a combination of conditions before
deciding on the proper action.
The general syntax is
if(Condition1)
{
// Executes when the condition 1 is true
if(Condition2)
{
// Executes when the Boolean expression 2 is true
}
}
28
Example:
public class Test
{
public static void main(String args[])
{
int x = 30;
int y = 10;
if( x == 30 )
if( y == 10 )
[Link]("X = 30 and Y = 10");
}
}
}
}
Looping Structures
Looping in programming languages is a feature which facilitates the execution of a set
of instructions/functions repeatedly while some condition evaluates to true.
a) while loop: A while loop is a control flow statement that allows code to be
executed repeatedly based on a given Boolean condition. While loop starts with the
checking of condition. If it evaluated to true, then the loop body statements are
executed otherwise first statement following the loop is executed. For this reason it
is also called Entry control loop
Once the condition is evaluated to true, the statements in the loop body are executed.
Normally the statements contain an update value for the variable being processed for
the next [Link] the condition becomes false, the loop terminates which
marks the end of its life cycle.
29
Syntax :
while (condition)
{
loop statements...
}
Example:
public class ProgramWhile
{
public static void main(String[] args)
{
int count = 1;
[Link](“Printing Numbers from 1 to 10”);
while (count <= 10)
{
[Link](count++);
}
}
}
b) DO-While loop
The do-while loop is similar to the while loop, except that the test condition is
performed at the end of the loop instead of at the beginning. The do—while loop
executes at least once without checking the condition. It begins with the keyword do,
followed by the statements that making up the body of the loop.
Finally, the keyword while and the test expression completes the do-while loop. When
the loop condition becomes false, the loop is terminated and execution continues with
the statement immediately following the loop.
The general Syntax is
do
{
statements..
}
30
while (condition);
Example
public class dowhileloop
{
public static void main(String[] args)
{
int count = 1;
[Link](“Printing Numbers from 1 to 10”);
do
{
[Link](count++);
}
while (count <= 10);
}
}
C) For loop
For loop provides a concise way of writing the loop structure. Unlike a while loop, a for
statement consumes the initialization, condition and increment/decrement in one line
thereby providing a shorter, easy to debug structure of looping.
The general Syntax is
for (initialization; testing condition; increment/decrement)
{
statement(s)
}
Example
public class ProgramFor
{
public static void main(String[] args)
{
[Link](“Printing Numbers from 1 to 10”); for
(int count = 1; count <= 10; count++)
{
31
[Link](count);
}}
}
Console Input and output statements in Java:
Java Input Statement
The Scanner class is used to get user input, and it is found in the [Link] [Link] use
the Scanner class, create an object of the class and use any of the available methods found in
the Scanner class documentation.
Methods of Scanner Class in Java
Below is a table listing the commonly used methods of the Scanner class in Java and their
descriptions.
Method Description
nextBoolean() Reads a boolean value from the user.
nextByte() Reads a byte value from the user.
nextDouble() Reads a double value from the user.
nextFloat() Reads a float value from the user.
nextInt() Reads an integer value from the user.
nextLine() Reads a String value from the user.
nextLong() Reads a long value from the user.
nextShort() Reads a short value from the user.
Java output statements
The [Link] stream, is used together with different methods to output values or print text
to the console:
Methods for Printing in Java
Below is a table listing the commonly used methods for printing in Java and their descriptions.
Method Description
print() Prints text or values to the console.
println() Prints text or values to the console,
followed by a new line.
Type Casting in Java
Type casting in Java is the process of converting a value from one data type to another. It is used
when you want to store a value of one type in a variable of another type.
Implicit Casting (Widening):
Widening conversion takes place when two data types are automatically converted. This happens
when:
32
⚫ The two data types are compatible.
⚫ When we assign a value of a smaller data type to a bigger data type.
Example:
int num = 10;
double result = num; // int to double (widening) [Link](result); // Output: 10.0
Explicit casting(Narrowing):
Explicit casting is required when larger data types are converted to smaller data types, which may
result in data loss or loss of [Link] is useful for incompatible data types where automatic
conversion cannot be done.
Example
double num = 10.5;
int result = (int) num; // double to int (narrowing) [Link](result); // Output: 10
Labeled Loops in Java
Definition
A labeled loop in Java is a loop that has a name (label) before it. It is mainly used when you
have nested loops and want to break or continue a specific outer loop from the inner loop.
Syntax
labelName:
for (...) {
for (...) {
break labelName; // or continue labelName;
}
}
Example with break
public class LabeledBreakExample {
public static void main(String[] args) {
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break outer;
}
[Link](i + " " + j);
}
}
}
}
Output
11
33
12
13
21
Example with continue
public class LabeledContinueExample {
public static void main(String[] args) {
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
continue outer;
}
[Link](i + " " + j);
}
}
}
}
Output
11
21
31
Types of Errors in Java
The problems in a Java program that prevent it from running normally are called Java errors.
Some prevent the code from compiling, while others cause failure at runtime. Identifying and
understanding different types of errors helps developers write more robust and reliable code.
In Java, errors can be categorized into three main types: Compiletime Errors, Runtime Errors,
and Logical Errors.
1. Compile time error
Compile Time Errors are those errors which prevent the code from running because of an
incorrect syntax such as a missing semicolon at the end of a statement or a missing bracket,
class not found, etc. These errors are detected by the java compiler and an error message is
displayed on the screen while compiling. Compile Time Errors are sometimes also referred to
as Syntax errors.
Example:
public class SyntaxErrorExample {
public static void main(String[] args) {
[Link]("Hello World") // missing semicolon
}
}
Output: ';' expected (Compile-time error)
2. Runtime Error
Runtime errors are detected during the execution of the program. Sometimes these are
discovered when the user enters an invalid data or data which is not relevant. Runtime errors
occur when a program does not contain any syntax errors but asks the computer to do
something that the computer is unable to reliably do.
During compilation, the compiler has no technique to detect these kinds of errors. It is the JVM
(Java Virtual Machine) that detects it while the program is running. To handle the error during
34
the run time we can put our error code inside the try block and catch the error inside the catch
block.
For example: if the user inputs a data of string format when the computer is expecting an
integer, there will be a runtime error.
Example:
public class RuntimeErrorExample {
public static void main(String[] args) {
int a = 10;
int b = 0;
int result = a / b; // ArithmeticException
[Link]("Result: " + result);
}
}
Output: Exception in thread "main" [Link]: / by zero
3. Logical Error
A logic error is when your program compiles and executes, but does the wrong thing or returns
an incorrect result or no output when it should be returning an output. These errors are detected
neither by the compiler nor by JVM. The Java system has no idea what your program is
supposed to do, so it provides no additional information to help you find the error. Logical
errors are also called Semantic Errors.
These errors are caused due to an incorrect idea or concept used by a programmer while
coding. Syntax errors are grammatical errors whereas, logical errors are errors arising out of an
incorrect meaning. For example, if a programmer accidentally adds two variables when he or
she meant to divide them, the program will give no error and will execute successfully but with
an incorrect result.
Example:
public class LogicalErrorExample {
public static void main(String[] args) {
int radius = 5;
double area = 2 * 3.14 * radius; // Wrong formula for area
[Link]("Area of circle: " + area);
}
}
Output: Area of circle: 31.400000000000002 (Incorrect result)
35