Week3 Lecture Notes-Input and Output
Week3 Lecture Notes-Input and Output
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.
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.
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.
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:
Java Output
In Java, you can simply use
[Link](); or
[Link](); or
[Link]();
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.
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().
| am awesome.
Number =-10.6
In the above example, notice the line,
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.
The int data type suggests that the variable can only hold integers. To learn
more, visit Java data types.
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.
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.
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?
Java is case sensitive. Hence, age and AGE are two different variables. For
example,
[Link](age); // prints 24
[Link](AGE); // prints 25
Variables must start with either a letter or an underscore, _ or a dollar, $ sign.
For example,
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.
1. Boolean Literals
In Java, boolean literals are used to initialize boolean data types. They can
store two values: true and false. For example,
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) {
// 3.445%10"2
double myDoubleScientific = 3.445e2;
4. Character Literals
Character literals are unicode character enclosed inside single quotes. For
example,
5. String literals
A string literal is a sequence of characters enclosed inside double-quotes. For
example,
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.
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
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.
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.
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.
import: Java import keyword makes classes and interfaces available and
accessible to the current source code.
int: Java int keyword is used to declare a variable that can hold a 32-bit signed
integer.
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).
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.
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.
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.
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.
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.
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) {
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) {
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) {
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) {
To tell the compiler to treat -42.3 as float rather than double, you need to use
for F.
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.
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).
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,
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.
Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators
Unary Operators
Bitwise Operators
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)
// 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
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
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.
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;
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,
Here, < operator is the relational operator. It checks if a is less than b or not.
// 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.
// && 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,
// increase num by 1
++num;
25
Here, the value of num gets increased to 6 from its initial value of 5.
// declare variables
inta=12,b=12;
int resultl, result;
// original value
[Link]("Value of a: " + a);
// increment operator
resultl = ++a;
[Link]("After increment: " + resultl);
// 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.
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
Leap year
In the above example, we have used the ternary operator to check if the year
is a leap year or not.
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,
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:
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:
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.
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.
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