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

Week3 Lecture Notes-Input and Output

Uploaded by

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

Week3 Lecture Notes-Input and Output

Uploaded by

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

Java Input

Java provides different ways to get input from the user. However, in this
tutorial, you will learn to get input from user using the object of Scanner class.

In order to use the object of Scanner, we need to import [Link]


package.

import [Link];
To learn more about importing packages in Java, visit Java Import Packages.

Then, we need to create an object of the Scanner class. We can use the object
to take input from the user.

// create an object of Scanner


Scanner input = new Scanner([Link]);

// take input from the user


int number = [Link]();
Example: Get Integer Input From the User
import [Link];

class Input {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter an integer: ");
int number = [Link]();
[Link]("You entered " + number);
// closing the scanner object
[Link]();
Run Code
Output:

Enter an integer: 23
You entered 23

In the above example, we have created an object named input of the Scanner
class. We then call the nextInt() method of the Scanner class to get an integer
input from the user.

Similarly, we can use nextLong(), nextFloat(), nextDouble(), and next()


methods to get long, float, double, and string input respectively from the user.

Note: We have used the close() method to close the object. It is


recommended to close the scanner object once the input is taken.

Example: Get float, double and String Input


import [Link];

class Input {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
// Getting float input
[Link]("Enter float: ");
float myFloat = [Link]();
[Link]("Float entered =" + myFloat);
// Getting double input
[Link]("Enter double: ");
double myDouble = [Link]();
[Link]("Double entered =" + myDouble);
// Getting String input
[Link]("Enter text: ");
String myString = [Link]();
[Link]("Text entered =" + myString);
Run Code
Output:

Enter float: 2.343


Float entered = 2.343
Enter double: -23.4
Double entered =-23.4
Enter text: Hey!
Text entered = Hey!

Java Output
In Java, you can simply use

[Link](); or
[Link](); or
[Link]();

to send output to standard output (screen).


Here,

System is a class
out is a public static field: it accepts output data.
Don't worry if you don't understand it. We will discuss class, public, and static
in later weeks.

Let's take an example to output a line.

class AssignmentOperator {
public static void main(String[] args) {
[Link]("Java programming is interesting.");
}
}

Run Code
Output:
Java programming is interesting.
Here, we have used the printin() method to display the string.
Difference between printin(), print() and printf()
print() - It prints string inside the quotes.
printin() - It prints string inside the quotes similar like print() method. Then
the cursor moves to the beginning of the next line.
printf() - It provides string formatting (similar to printf in C/C++ programming).
Example: print() and printin()

class Output {
public static void main(String[] args) {
[Link]("1. printin ");
[Link]("2. printin ");
[Link]("1. print ");
[Link]("2. print");
}
}
Run Code
Output:

1. println
2. println
1. print 2. print

In the above example, we have shown the working of the print() and printin()
methods. To learn about the printf() method, visit Java printf().

Example: Printing Variables and Literals


class Variables {
public static void main(String[] args) {
Double number = -10.6;
[Link](5);
[Link](number);
}
}
Run Code
When you run the program, the output will be:
5
-10.6
Here, you can see that we have not used the quotation marks. It is because to
display integers, variables and so on, we don't use quotation marks.

Example: Print Concatenated Strings


class PrintVariables {
public static void main(String[] args) {
Double number = -10.6;
[Link]("l am " + "awesome.");
[Link]("Number =" + number);
}
}
Run Code
Output:

| am awesome.
Number =-10.6
In the above example, notice the line,

[Link]("l am " + "awesome.");


Here, we have used the + operator to concatenate (join) the two strings: "I am
"and "awesome.".

And also, the line,

[Link]("Number =" + number);


Here, first the value of variable number is evaluated. Then, the value is
concatenated to the string: "Number =".

Java Variables
A variable is a location in memory (storage area) to hold data.

To indicate the storage area, each variable should be given a unique name
(identifier). Learn more about Java identifiers.

Create Variables in Java


Here's how we create a variable in Java,

int speedLimit = 80;


Here, speedLimit is a variable of int data type and we have assigned value 80
to it.

The int data type suggests that the variable can only hold integers. To learn
more, visit Java data types.

In the example, we have assigned value to the variable during declaration.


However, it's not mandatory.

You can declare variables and assign variables separately. For example,

int speedLimit;
speedLimit = 80;
Note: Java is a statically-typed language. It means that all variables must be
declared before they can be used.

Change values of variables


The value of a variable can be changed in the program, hence the name
variable. For example,

int speedLimit = 80;

speedLimit = 90;
Here, initially, the value of speedLimit is 80. Later, we changed it to 90.

However, we cannot change the data type of a variable in Java within the
same scope.

What is the variable scope?

Don't worry about it for now. Just remember that we can't do something like
this:
int speedLimit = 80;

float speedLimit;
To learn more, visit: Can | change declaration type for a variable in Java?

Rules for Naming Variables in Java


Java programming language has its own set of rules and conventions for
naming variables. Here's what you need to know:

Java is case sensitive. Hence, age and AGE are two different variables. For
example,

int age = 24;


int AGE = 25;

[Link](age); // prints 24
[Link](AGE); // prints 25
Variables must start with either a letter or an underscore, _ or a dollar, $ sign.
For example,

int age; // valid name and good practice


int _age; // valid but bad practice
int Sage; // valid but bad practice
Variable names cannot start with numbers. For example,

int 1age; // invalid variables


Variable names can't use whitespace. For example,

int my age; // invalid variables

Here, is we need to use variable names having more than one word, use all
lowercase letters for the first word and capitalize the first letter of each
subsequent word. For example, myAge.
When creating variables, choose a name that makes sense. For example,
score, number, level makes more sense than variable names such as s, n, and
l.
If you choose one-word variable names, use all lowercase letters. For
example, it's better to use speed rather than SPEED, or sPEED.
There are 4 types of variables in Java programming language:
Instance Variables (Non-Static Fields)
Class Variables (Static Fields)
Local Variables
Parameters

If you are interested to learn more about it now, visit Java Variable Types.

Java literals
Literals are data used for representing fixed values. They can be used directly
in the code. For example,

inta=1;
float b = 2.5;
charc="F';
Here, 1, 2.5, and 'F' are literals.

Here are different types of literals in Java.

1. Boolean Literals
In Java, boolean literals are used to initialize boolean data types. They can
store two values: true and false. For example,

boolean flagl = false;


boolean flag2 = true;
Here, false and true are two boolean literals.

2. Integer Literals
An integer literal is a numeric value(associated with numbers) without any
fractional or exponential part. There are 4 types of integer literals in Java:

binary (base 2)
decimal (base 10)
octal (base 8)
hexadecimal (base 16)
For example:
// binary
int binaryNumber = 0b10010;
// octal
int octalNumber = 027;

// decimal
int decNumber = 34;

// hexadecimal
int hexNumber = 0x2F; // Ox represents hexadecimal
// binary
int binNumber = 0b10010; // Ob represents binary
In Java, binary starts with Ob, octal starts with 0, and hexadecimal starts with
Ox.

Note: Integer literals are used to initialize variables of integer types like byte,
short, int, and long.

3. Floating-point Literals
A floating-point literal is a numeric literal that has either a fractional form or
an exponential form. For example,

class Main {
public static void main(String[] args) {

double myDouble = 3.4;


float myFloat = 3.4F;

// 3.445%10"2
double myDoubleScientific = 3.445e2;

[Link](myDouble); // prints 3.4


[Link](myFloat); // prints 3.4
[Link](myDoubleScientific); // prints 344.5
Run Code
Note: The floating-point literals are used to initialize float and double type
variables.

4. Character Literals
Character literals are unicode character enclosed inside single quotes. For
example,

char letter ='a’;


Here, a is the character literal.

We can also use escape sequences as character literals. For example, \b


(backspace), \t (tab), \n (new line), etc.

5. String literals
A string literal is a sequence of characters enclosed inside double-quotes. For
example,

String strl = "Java Programming";


String str2 = "Programiz";
Here, Java Programming and Programiz are two string literals.

Java keywords are also known as reserved words. Keywords are particular
words that act as a key to a code. These are predefined words by Java so they
cannot be used as a variable or object name or class name.

A list of Java keywords or reserved words are given below:

abstract: Java abstract keyword is used to declare an abstract class. An


abstract class can provide the implementation of the interface. It can have
abstract and non-abstract methods.

boolean: Java boolean keyword is used to declare a variable as a boolean


type. It can hold True and False values only.
10
break: Java break keyword is used to break the loop or switch statement. It
breaks the current flow of the program at specified conditions.

byte: Java byte keyword is used to declare a variable that can hold 8-bit data
values.

case: Java case keyword is used with the switch statements to mark blocks of
text.

catch: Java catch keyword is used to catch the exceptions generated by try
statements. It must be used after the try block only.

char: Java char keyword is used to declare a variable that can hold unsigned
16-bit Unicode characters

class: Java class keyword is used to declare a class.

continue: Java continue keyword is used to continue the loop. It continues the
current flow of the program and skips the remaining code at the specified
condition.

default: Java default keyword is used to specify the default block of code in a
switch statement.

do: Java do keyword is used in the control statement to declare a loop. It can
iterate a part of the program several times.

double: Java double keyword is used to declare a variable that can hold 64-bit
floating-point number.

else: Java else keyword is used to indicate the alternative branches in an if


statement.

enum: Java enum keyword is used to define a fixed set of constants. Enum
constructors are always private or default.

11
extends: Java extends keyword is used to indicate that a class is derived from
another class or interface.

final: Java final keyword is used to indicate that a variable holds a constant
value. It is used with a variable. It is used to restrict the user from updating
the value of the variable.

finally: Java finally keyword indicates a block of code in a try-catch structure.


This block is always executed whether an exception is handled or not.

float: Java float keyword is used to declare a variable that can hold a 32-bit
floating-point number.

for: Java for keyword is used to start a for loop. It is used to execute a set of
instructions/functions repeatedly when some condition becomes true. If the
number of iteration is fixed, it is recommended to use for loop.

if: Java if keyword tests the condition. It executes the if block if the condition
is true.

implements: Java implements keyword is used to implement an interface.

import: Java import keyword makes classes and interfaces available and
accessible to the current source code.

instanceof: Java instanceof keyword is used to test whether the object is an


instance of the specified class or implements an interface.

int: Java int keyword is used to declare a variable that can hold a 32-bit signed
integer.

interface: Java interface keyword is used to declare an interface. It can have


only abstract methods.

long: Java long keyword is used to declare a variable that can hold a 64-bit
integer.

12
native: Java native keyword is used to specify that a method is implemented
in native code using JNI (Java Native Interface).

new: Java new keyword is used to create new objects.

null: Java null keyword is used to indicate that a reference does not refer to
anything. It removes the garbage value.

package: Java package keyword is used to declare a Java package that includes
the classes.

private: Java private keyword is an access modifier. It is used to indicate that a


method or variable may be accessed only in the class in which it is declared.

protected: Java protected keyword is an access modifier. It can be accessible


within the package and outside the package but through inheritance only. It
can't be applied with the class.

public: Java public keyword is an access modifier. It is used to indicate that an


item is accessible anywhere. It has the widest scope among all other
modifiers.

return: Java return keyword is used to return from a method when its
execution is complete.

short: Java short keyword is used to declare a variable that can hold a 16-bit
integer.

static: Java static keyword is used to indicate that a variable or method is a


class method. The static keyword in Java is mainly used for memory
management.

strictfp: Java strictfp is used to restrict the floating-point calculations to


ensure portability.

super: Java super keyword is a reference variable that is used to refer to


parent class objects. It can be used to invoke the immediate parent class
method.
13
switch: The Java switch keyword contains a switch statement that executes
code based on test value. The switch statement tests the equality of a variable
against multiple values.

synchronized: Java synchronized keyword is used to specify the critical


sections or methods in multithreaded code.

this: Java this keyword can be used to refer the current object in a method or
constructor.

throw: The Java throw keyword is used to explicitly throw an exception. The
throw keyword is mainly used to throw custom exceptions. It is followed by an
instance.

throws: The Java throws keyword is used to declare an exception. Checked


exceptions can be propagated with throws.

transient: Java transient keyword is used in serialization. If you define any


data member as transient, it will not be serialized.

try: Java try keyword is used to start a block of code that will be tested for
exceptions. The try block must be followed by either catch or finally block.

void: Java void keyword is used to specify that a method does not have a
return value.

volatile: Java volatile keyword is used to indicate that a variable may change
asynchronously.

while: Java while keyword is used to start a while loop. This loop iterates a
part of the program several times. If the number of iteration is not fixed, it is
recommended to use the while loop.

14
Identifiers are the name given to variables, classes, methods, etc. Consider
the above code;

int score;

Here, score is a variable (an identifier). You cannot use keywords as variable
names. It's because keywords have predefined meanings. For example,

int float;

The above code is wrong. It's because float is a keyword and cannot be used
as a variable name.

Identifiers cannot be a keyword.


Identifiers are case-sensitive.
It can have a sequence of letters and digits. However, it must begin with a
letter, S or _. The first letter of an identifier cannot be a digit.
It's a convention to start an identifier with a letter rather and S or _.
Whitespaces are not allowed.

Similarly, you cannot use symbols such as @, #, and so on.

score
level
highestScore
numberl
convertToString

class
float
lnumber
highest Score
@pple
15
Java Data Types
As the name suggests, data types specify the type of data that can be stored
inside variables in Java.

Java is a statically-typed language. This means that all variables must be


declared before they can be used.

int speed;
Here, speed is a variable, and the data type of the variable is int.

The int data type determines that the speed variable can only contain
integers.

There are 8 data types predefined in Java, known as primitive data types.

Note: In addition to primitive data types, there are also referenced types
(object type).

1. boolean type
The boolean data type has two possible values, either true or false.
Default value: false.
They are usually used for true/false conditions.
Example 1: Java boolean data type
class Main {
public static void main(String[] args) {

boolean flag = true;


[Link](flag); // prints true
}
}

2. int type
The int data type can have values from -231 to 231-1 (32-bit signed two's
complement integer).
If you are using Java 8 or later, you can use an unsigned 32-bit integer. This
will have a minimum value of 0 and a maximum value of 232-1. To learn more,
visit How to use the unsigned integer in java 8?
Default value: 0
Example 4: Java int data type
class Main {
public static void main(String[] args) {

int range =-4250000;


[Link](range); // print -4250000
}
}

3. double type
The double data type is a double-precision 64-bit floating-point.
It should never be used for precise values such as currency.
Default value: 0.0 (0.0d)
Example 6: Java double data type
class Main {
public static void main(String[] args) {

double number =-42.3;


[Link](number); // prints -42.3
}
}

4. float type
The float data type is a single-precision 32-bit floating-point. Learn more
about single-precision and double-precision floating-point if you are
interested.
It should never be used for precise values such as currency.
Default value: 0.0 (0.0f)
Example 7: Java float data type
class Main {
public static void main(String[] args) {

float number = -42.3f;


[Link](number); // prints -42.3
17
}
}
Run Code
Notice that we have used -42.3f instead of -42.3in the above program. It's
because -42.3 is a double literal.

To tell the compiler to treat -42.3 as float rather than double, you need to use
for F.

If you want to know about single-precision and double-precision, visit Java


single-precision and double-precision floating-point.

5. char type
It's a 16-bit Unicode character.
The minimum value of the char data type is '\u0000Q' (0) and the maximum
value of the is "\uffff".
Default value: '\u0000'
Example 8: Java char data type
class Main {
public static void main(String[] args) {
char letter = '\u0051";
[Link](letter); // prints Q
}
}
Run Code
Here, the Unicode value of Q is \u0O051. Hence, we get Q as the output.

Here is another example:

class Main {
public static void main(String[] args) {
char letterl ='9';
[Link](letterl); // prints 9
char letter2 = 65;
[Link](letter2); // prints A
}
}
Run Code
18
Here, we have assigned 9 as a character (specified by single quotes) to the
letterl variable. However, the letter2 variable is assigned 65 as an integer
number (no single quotes).

Hence, A is printed to the output. It is because Java treats characters as an


integer and the ASCII value of A is 65. To learn more about ASCII, visit What is
ASCII Code?.

String type
Java also provides support for character strings via [Link] class.
Strings in Java are not primitive types. Instead, they are objects. For example,

String myString = "Java Programming";


Here, myString is an object of the String class.

Operators are symbols that perform operations on variables and values. For
example, + is an operator used for addition, while * is also an operator used
for multiplication.

Operators in Java can be classified into 5 types:

Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators
Unary Operators
Bitwise Operators

1. Java Arithmetic Operators


Arithmetic operators are used to perform arithmetic operations on variables
and data. For example,

a+b;
Here, the + operator is used to add two variables a and b. Similarly, there are
various other arithmetic operators in Java.

19
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Operation (Remainder after division)

Example 1: Arithmetic Operators


class Main {
public static void main(String[] args) {

// declare variables
inta=12,b =5;

// addition operator
[Link]("a+b =" + (a + b));

// subtraction operator
[Link]("a-b =" + (a - b));

// multiplication operator
[Link]("a*b =" + (a * b));

// division operator
[Link]("a /b="+ (a / b));

// modulo operator
[Link]("a % b =" + (a % b));
}
}
Run Code
Output
at+b=17
a-b=7
a*b=60
a/b=2
a%b=2
20
In the above example, we have used +, -, and * operators to compute
addition, subtraction, and multiplication operations.

/ Division Operator

Note the operation, a / b in our program. The / operator is the division


operator.

If we use the division operator with two integers, then the resulting quotient
will also be an integer. And, if one of the operands is a floating-point number,
we will get the result will also be in floating-point.

In Java,

(9/2)is4
(9.0/2)is 4.5
(9/2.0)is 4.5
(9.0/2.0) is 4.5
% Modulo Operator

The modulo operator % computes the remainder. When a = 7 is divided by b =


4, the remainder is 3.

Note: The % operator is mainly used with integers.

2. Java Assignment Operators


Assignment operators are used in Java to assign values to variables. For
example,

int age;
age =5;
Here, = is the assignment operator. It assigns the value on its right to the
variable on its left. That is, 5 is assigned to the variable age.

Let's see some more assignment operators available in Java.

21
Operator Example Equivalentto
= a=bja=b;
+= a+=b;, a=a+bh;
= a-=b; a=a-b;
f= at=b; a=a*b;
a/=b; a=a/b;
/=

%= a%=b;, a=a%b;
Example 2: Assignment Operators
class Main {
public static void main(String[] args) {

// create variables
inta=4;
int var;

// assign value using =


var = a;
[Link]("var using =: " + var);

// assign value using =+


var += a,

[Link]("var using +=: " + var);

// assign value using =*


var *= ga;
[Link]("var using *=:" + var);
}
}
Run Code
Output

var using =: 4
var using +=: 8
var using *=: 32

22
3. Java Relational Operators
Relational operators are used to check the relationship between two
operands. For example,

// check if a is less than b


a<b;

Here, < operator is the relational operator. It checks if a is less than b or not.

It returns either true or false.

Operator Description Example


== Is Equal To 3 ==5 returns false
I= NotEqualTo 3 !=5returnstrue
> Greater Than 3 > 5 returns false
< Less Than 3 <5 returns true
>= Greater Than or Equal To 3 >=5 returns false
<= Less Than or Equal To 3 <=5 returns true

Example 3: Relational Operators


class Main {
public static void main(String[] args) {

// create variables
inta=7,b=11;

// value of aand b
[Link]("ais"+a+ "and bis" +b);

// == operator
[Link](a == b); // false

// |= operator
[Link](a I= b); // true

// > operator
[Link](a > b); // false
23
// < operator
[Link](a < b); // true

// >= operator
[Link](a >= b); // false

// <= operator
[Link](a <= b); // true
}
}
Run Code
Note: Relational operators are used in decision making and loops.

4. Java Logical Operators


Logical operators are used to check whether an expression is true or false.
They are used in decision making.

Operator Example Meaning


&& (Logical AND) expressionl && expression2 true only if both
expression and expression? are true
| | (Logical OR) expressionl || expression2 true if either expressionl or
expression? is true
I (Logical NOT) lexpression true if expression is false and vice versa
Example 4: Logical Operators
class Main {
public static void main(String[] args) {

// && operator
[Link]((5 > 3) && (8 > 5)); // true
[Link]((5 > 3) && (8 < 5)); // false

// | | operator
[Link]((5< 3) || (8 >5)); // true
[Link]((5 > 3) || (8 <5)); // true
[Link]((5< 3) || (8 <5)); // false

24
// | operator
[Link](!(5 == 3)); // true
[Link](!(5 > 3)); // false
}
}
Run Code
Working of Program

(5>3) && (8 > 5) returns true because both (5 > 3) and (8 > 5) are true.
(5> 3) && (8 < 5) returns false because the expression (8 < 5) is false.
(5<3) || (8 >5) returns true because the expression (8 > 5) is true.
(5>3) || (8 <5) returns true because the expression (5 > 3) is true.
(5<3) || (8 <5) returns false because both (5 < 3) and (8 < 5) are false.
I(5 == 3) returns true because 5 == 3 is false.
I(5 > 3) returns false because 5 > 3 is true.
5. Java Unary Operators
Unary operators are used with only one operand. For example, ++ is a unary
operator that increases the value of a variable by 1. That is, ++5 will return 6.

Operator Meaning
+ Unary plus: not necessary to use since numbers are positive without
using it
- Unary minus: inverts the sign of an expression
++ Increment operator: increments value by 1
-- Decrement operator: decrements value by 1
l Logical complement operator: inverts the value of a boolean
Increment and Decrement Operators
Java also provides increment and decrement operators: ++ and -- respectively.
++ increases the value of the operand by 1, while -- decrease it by 1. For
example,

int num =5;

// increase num by 1
++num;
25
Here, the value of num gets increased to 6 from its initial value of 5.

Example 5: Increment and Decrement Operators


class Main {
public static void main(String[] args) {

// declare variables
inta=12,b=12;
int resultl, result;

// original value
[Link]("Value of a: " + a);

// increment operator
resultl = ++a;
[Link]("After increment: " + resultl);

[Link]("Value of b: " + b);

// decrement operator
result2 = --b;
[Link]("After decrement: " + result2);
}
}
Run Code
Output

Value of a: 12
After increment: 13
Value of b: 12
After decrement: 11
In the above program, we have used the ++ and -- operator as prefixes (++a, --
b). We can also use these operators as postfix (a++, b++).

There is a slight difference when these operators are used as prefix versus
when they are used as a postfix.

26
To learn more about these operators, visit increment and decrement
operators.

Other operators
Besides these operators, there are other additional operators in Java.

Java instanceof Operator

The instanceof operator checks whether an object is an instanceof a particular


class. For example,

class Main {
public static void main(String[] args) {
String str = "Programiz";
boolean result;
// checks if str is an instance of
// the String class
result = str instanceof String;
[Link]("Is str an object of String? " + result);
}
}
Run Code
Output

Is str an object of String? true


Here, str is an instance of the String class. Hence, the instanceof operator
returns true. To learn more, visit Java instanceof.

Java Ternary Operator


The ternary operator (conditional operator) is shorthand for the if-then-else
statement. For example,

variable = Expression ? expressionl : expression2


Here's how it works.

If the Expression is true, expressionl is assigned to the variable.


If the Expression is false, expression2 is assigned to the variable.
Let's see an example of a ternary operator.
27
class Java {
public static void main(String[] args) {
int februaryDays = 29;
String result;
// ternary operator
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
[Link](result);
}
}
Run Code
Output

Leap year
In the above example, we have used the ternary operator to check if the year
is a leap year or not.

Differentiate between BODMAS and BEDMAS.

In computer programming, comments are a portion of the program that are


completely ignored by Java compilers. They are mainly used to help
programmers to understand the code. For example,

// declare and initialize two variables


inta=1;
intb=3;

// print the output


[Link]("This is output");
Here, we have used the following comments,

declare and initialize two variables


print the output
Types of Comments in Java

28
In Java, there are two types of comments:

single-line comment
multi-line comment
Single-line Comment
A single-line comment starts and ends in the same line. To write a single-line
comment, we can use the // symbol. For example,

// "Hello, World!" program example

class Main {
public static void main(String[] args) {
// prints "Hello, World!"
[Link]("Hello, World!");
}
}
Run Code
Output:

Hello, World!
Here, we have used two single-line comments:

"Hello, World!" program example


prints "Hello World!"

The Java compiler ignores everything from // to the end of line. Hence, it is
also known as End of Line comment.

Multi-line Comment

When we want to write comments in multiple lines, we can use the multi-line
comment. To write multi-line comments, we can use the /*....*/ symbol. For
example,

29
/* This is an example of multi-line comment.
* The program prints "Hello, World!" to the standard output.
*/

class HelloWorld {
public static void main(String[] args) {

[Link]("Hello, World!");
}
}
Run Code
Output:

Hello, World!
Here, we have used the multi-line comment:

/* This is an example of multi-line comment.


* The program prints "Hello, World!" to the standard output.
*/
This type of comment is also known as Traditional Comment. In this type of
comment, the Java compiler ignores everything from /* to */.

Use Comments the Right Way


One thing you should always consider that comments shouldn't be the
substitute for a way to explain poorly written code in English. You should
always write well structured and self explaining code. And, then use
comments.

A method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known as
functions.
Why use methods? To reuse code: define the code once, and use it many
times.

A Function in Java is a block of statements that is defined to perform a specific


task. A function is also called a reusable code because once it is created, it can
be used again and again.

Built-in functions (System defined functions) and User defined functions.

Built-in Functions : These functions are predefined, and we can use them any
time we want in our Java program. For example pow(), sqrt(), min(), etc.
User Defined Functions : These functions are defined or created by the
programmer for performing a specific task in a program.

User-Defined Functions are the functions which are created by user as per his
own requirements. System define Functions are Predefined functions. In User
Defined Functions, name of function can be changed any time.

// Exam of User Defined Functions:

int addNumbers() { //user defined method


// code
}

// calls the method


addNumbers();

System Defined functions:


[Link](), [Link](), [Link](), abs(), charAt(), length(), replace(),

31
[Link];
public class ArithmeticOperators {
static void main(String[] args) {
SC = new ([Link]);
[Link]("Enter the first number: ");
double ium = sc RexiDoUBIe();
[Link]("Enter the second number: ");
double = [Link]();

int num3 =

=numl+ num?2;
= numl - num2;

[Link]. + sum);
[Link]("The difference of the two numbers is: " + difference);
[Link]("The product of the two numbers is: " + product);
[Link]("The division of the two numbers is: " + division);
[Link]("The squareroot of the number three is: " + squareroot);
If (num1 < num2) {[Link](“First number smaller the second
number”);
else {[Link](First number equals or bigger than the second
number.”};
Increment = ++num3;
[Link]("After increment: " + Increment);

32
Input
Enter the first number: 20
Enter the second number: 10

Output
The sum of the two numbers is: 30.0
The difference of the two numbers is: 10.0
The product of the two numbers is: 200.0
The division of the two numbers is: 2.0
The squareroot of number three is: 3
First number equals or bigger than the second number.
After increment: 10

33

You might also like