Java Basics: Input and Output Methods
Java Basics: Input and Output Methods
Simplicity
Robustness
Java language is robust which means reliable.
The main features of java that make it robust are garbage collection, exception
handling, and memory allocation.
Security
Distributed
We can create distributed applications using the java programming language.
Remote Method Invocation and Enterprise Java Beans are used for creating
distributed applications in java.
Multithreading
Java supports multithreading, enabling the concurrent execution of multiple parts
of a program.
Portability
All the source code need not be All the source code must be
converted into Machine code(or Object converted into machine code
Code) for execution by CPU. Some source before it is executed by the CPU.
code written by any specific high-level
language is converted into byte code then
byte code to object code for execution by
CPU.
In Java, the `main` method is always declared as `public static void main(String[]
args)` because of the following reasons:
1. **public**: This keyword means the method is accessible from anywhere. The
`main` method needs to be accessible by the Java runtime environment to start
the execution of the program, which is outside of the program itself. Without
`public`, the Java runtime wouldn't be able to call this method.
4. **main**: This is the name of the method that serves as the entry point for the
program. The Java runtime specifically looks for a method with this name to begin
execution.
This specific structure is required for the Java Virtual Machine (JVM) to correctly
identify and execute the entry point of any Java program.
Basics of JAVA:
Class: The class is a blueprint (plan) of the instance of a class (object). It can be
defined as a logical template that share common properties and methods.
Object : The object is an instance of a class. It is an entity that has behavior and
state.
Method : The behavior of an object is the method.
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating and initializing custom character
char a = 'G';
// Integer data type is generally used for numeric values
int i = 89;
// use byte and short if memory is a constraint
byte b = 4;
// this will give error as number is larger than byte range
// byte b1 = 7888888955;
short s = 56;
// this will give error as number is larger than short range
// short s1 = 87878787878;
// by default fraction value is double in java
double d = 4.355453532;
// for float use 'f' as suffix as standard
float f = 4.7333434f;
// need to hold big range of numbers then we need this data type
long l = 12121;
[Link]("char: " + a);
[Link]("integer: " + i);
[Link]("byte: " + b);
[Link]("short: " + s);
[Link]("float: " + f);
[Link]("double: " + d);
[Link]("long: " + l);
}
}
Output
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121
Java Identifiers
In Java, identifiers are used for identification purposes. Java Identifiers can be a
class name, method name, variable name, or label.
Rules For Defining Java Identifiers
The only allowed characters for identifiers are all alphanumeric
characters([A-Z],[a-z],[0-9]), ‘$‘(dollar sign) and ‘_‘ (underscore).
Identifiers should not start with digits([0-9]).
are case-sensitive.
There is no limit on the length of the identifier but it is
advisable to use an optimum length of 4 – 15 letters only.
Reserved Words can’t be used as an identifier.
NOTE: The keywords const and goto are reserved, even though they are not
currently used. In place of const, the final keyword is used. Some keywords like
strictfp are included in later versions of Java.
Literal: Any constant value which can be assigned to the variable is called
literal/constant.
Note: By default, every literal is of int type, we can specify explicitly as long type
by suffixed with l or L. There is no way to specify byte and short literals explicitly.
1. Arithmetic Operators
* : Multiplication
/ : Division
% : Modulo
+ : Addition
– : Subtraction
2. Unary Operators
Unary operators need only one operand.
– : Unary minus, used for negating the values.
+ : Unary plus indicates the positive value (numbers are positive without
this, however). It performs an automatic conversion to int when the type of
its operand is the byte, char, or short. This is called unary numeric
promotion.
++ : Increment operator, used for incrementing the value by 1. There are
two varieties of increment operators.
o Post-Increment: Value is first used for computing the result and then
incremented.
o Pre-Increment: Value is incremented first, and then the result is
computed.
– – : Decrement operator, used for decrementing the value by 1. There are
two varieties of decrement operators.
o Post-decrement: Value is first used for computing the result and then
decremented.
o Pre-Decrement: The value is decremented first, and then the result is
computed.
! : Logical not operator, used for inverting a boolean value.
class Main {
public static void main(String[] args)
{
int a = 10;
int b = 5;
// Unary increment (++)
// Increment 'a' by 1 before using its value
[Link]("Unary Increment: " + (++a));
// 'a' has been incremented
[Link]("a after increment: " + a);
3. Assignment Operator
‘=’ Assignment operator is used to assign a value to any variable.
The general format of the assignment operator is:
variable = value;
Compound Statements:
The assignment operator can be combined with other operators to build a
shorter version of the statement called a Compound Statement. For example,
instead of a = a+5, we can write a += 5.
+= -=
*= /= %=
4. Relational Operators
==, Equal to returns true if the left-hand side is equal to the right-hand side.
!=, Not Equal to returns true if the left-hand side is not equal to the right-
hand side.
<, less than: returns true if the left-hand side is less than the right-hand
side.
<=, less than or equal to returns true if the left-hand side is less than or
equal to the right-hand side.
>, Greater than: returns true if the left-hand side is greater than the right-
hand side.
>=, Greater than or equal to returns true if the left-hand side is greater
than or equal to the right-hand side.
5. Logical Operators
&&, Logical AND: returns true when both conditions are true.
||, Logical OR: returns true if at least one condition is true.
!, Logical NOT: returns true when a condition is false and vice-versa
6. Ternary Operator
condition ? if true : if false
The above statement means that if the condition evaluates to
true, then execute the statements after the ‘?’ else execute the
statements after the ‘:’.
7. Bitwise Operators
These operators are used to perform the manipulation of individual bits of a
number. They can be used with any of the integer types.
&, Bitwise AND operator: returns bit by bit AND of input values.
|, Bitwise OR operator: returns bit by bit OR of input values.
^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
~, Bitwise Complement Operator: This is a unary operator which returns
the one’s complement representation of the input value, i.e., with all bits
inverted.
8. Shift Operators
These operators are used to shift the bits of a number left or
right, thereby multiplying or dividing the number by two,
respectively. They can be used when we have to multiply or
divide a number by two. General format-
number shift_op number_of_places_to_shift;
<<, Left shift operator: shifts the bits of the number to the left and fills 0 on voids
left as a result.
>>, Signed Right shift operator: shifts the bits of the number to the right and fills
0 on voids left as a result. The leftmost bit depends on the sign of the initial
number.
9. instance of operator
The instance of the operator is used for type checking. It can be
used to test if an object is an instance of a class, a subclass, or
an interface. General format-
object instance of class/subclass/interface
Variables in Java
Java variable is a name given to a memory location. It is the basic unit of storage in
a program.
The value stored in a variable can be changed during program execution.
Variables in Java are only a name given to a memory location. All the
operations done on the variable affect that memory location.
In Java, all variables must be declared before use.
Declaration: datatype variable_Name
Types of Variables in Java
1. Local Variables
A variable defined within a block or method or constructor is called a local
variable.
The Local variable is created at the time of declaration and destroyed after
exiting from the block or when the call returns from the function.
The scope of these variables exists only within the block in which the
variables are declared, i.e., we can access these variables only within that
block.
Initialization of the local variable is mandatory before using it in the defined
scope.
2. Instance Variables
Instance variables are non-static variables and are declared in a class outside of
any method, constructor, or block.
As instance variables are declared in a class, these variables are created
when an object of the class is created and destroyed when the object is
destroyed.
Unlike local variables, we may use access specifiers for instance variables. If
we do not specify any access specifier, then the default access specifier will
be used.
Instance variables can be accessed only by creating objects.
3. Static Variables
static variables are declared using the static keyword within a class outside
of any method, constructor, or block.
Static variables cannot be declared locally inside an instance method.
Java Operator Precedence:
Parenthesis
Postfix
Prefix
Multiplicative
Additive
Relational
Logical
Precedence Operator Type Associativity
() Parentheses
1. [] Array subscript Left to Right
· Member selection
Unary post-
++ increment
2. Right to left
-- Unary post-
decrement
Unary pre-
increment
++ Unary pre-
-- decrement
+ Unary plus
3. - Unary minus Right to left
! Unary logical
~ negation
(type) Unary bitwise
complement
Unary type cast
* Multiplication
4. / Division Left to right
% Modulus
+ Addition
5. Left to right
- Subtraction
Method Description
// String input
String name = [Link]();
// Character input
char gender = [Link]().charAt(0);
// Numerical data input
// byte, short and float can be read
// using similar-named functions.
int age = [Link]();
long mobileNo = [Link]();
double cgpa = [Link]();
// Print the values to check if the input was correctly obtained.
[Link]("Name: " + name);
[Link]("Gender: " + gender);
[Link]("Age: " + age);
[Link]("Mobile Number: " + mobileNo);
[Link]("CGPA: " + cgpa);
}
}
Input Output
Geek Name: Geek
F Gender: F
40 Age: 40
9876543210 Mobile Number: 9876543210
9.9 CGPA: 9.9
2. if-else:
We can use the else statement with the if statement to execute a block of code
when the condition is false.
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if condition is false
}
3. nested-if: Nested if statements mean an if statement inside an if statement.
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
4. if-else-if ladder:
The if statements are executed from the top down.
As soon as one of the conditions controlling the if is true, the statement
associated with that ‘if’ is executed, and the rest of the ladder is bypassed.
If none of the conditions is true, then the final else statement will be executed.
There can be as many as ‘else if’ blocks associated with one ‘if’ block but only one
‘else’ block is allowed with one ‘if’ block.
if (condition)
statement;
else if (condition)
statement;
.
else
statement;
Example Program:
Write a Java program to print the area of circle, rectangle or square according to
the users input.
import [Link]; // To import Scanner class so the user can give input
class Area
{
public static void main(String[] args)
{
int ch, l, b, s, r;
Scanner Sc= new Scanner([Link]); // Creating an object of scanner class
[Link]("Enter your choice");
[Link]("1. Area of Circle");
[Link]("2. Area of Square");
[Link]("3. Area of Rectangle");
ch=[Link](); // taking input from the user
switch(ch)
{
case 1:
[Link]("Enter the radius");
r=[Link]();
[Link]("Area:" + [Link]*r*r);
break; //to terminate the block of case 1
case 2: [Link]("Enter the side");
s=[Link]();
[Link]("Area:" + s*s);
break; //to terminate the block of case 2
case 3:
[Link]("Enter the length, breadth");
l=[Link]();
b=[Link]();
[Link]("Area: " + l*b);
break; //to terminate the block of case 3
default: [Link]("Invalid choice"); } } }
INPUT OUTPUT:
2 Enter your choice
5 1. Area of Circle
2. Area of Square
3. Area of Rectangle
Enter the side
Area: 25
Loops in Java:
Looping in programming languages is a feature which facilitates the execution of a
set of instructions/functions repeatedly while some condition evaluates to true.
Three types of Conditional statements:
3. For Loop:
1. Initialization Expression
In this expression, we have to initialize the loop counter to some value.
2. Test Expression: In this expression, we have to test the condition. If the
condition evaluates to true then, we will execute the body of the loop and go to
the update expression. Otherwise, we will exit from the for a loop.
3. Update Expression:
After executing the loop body, this expression increments/decrements the loop
variable by some value.
Programs:
1. WAP to print the sum of n natural numbers
import [Link];
class Sum
{
public static void main(String[] args)
{ int n,sum=0,i;
Scanner Sc= new Scanner([Link]); // create an object of Sacnner class
n = [Link]();
for(i=1;i<=n;i++) // to add numbers from 1 to n
sum+=i; //to store the sum //sum=sum+i;
[Link]("Sum of n natural numbers: "+ sum);
}}
INPUT: 5 OUTPUT: Sum of n natural numbers: 15
1
12
123
1234
12345
class Pattern LOGIC:
{ We have 5 rows so we iterate from 1 to
public static void main(String[] args) 5
{ In each row we print ‘i’ which is the
int i; row number.
for(i=1;i<=5;i++) //rows Ex:
{ Row 1 prints “1”
for(int j=1; j<=i ;j++) //printing Row 2 prints “1 2” till 2
[Link](j+ " "); Row 3 prints “1 2 3” till 3
[Link](); So we print “the value of j” for j=1 to
} j=i where ‘i’ is the row number.
}
}
11111
1111
111
11
1
class Pattern LOGIC:
{ We are printing 1 and in each line the
public static void main(String[] args) number of 1’s decrease
{ and we have 5 rows so we iterate from
int i; 5 to 1
for(i=5;i>=1;i--) //rows
{ Ex:
for(int j=i; j>=1 ;j--) //printing Row 5 prints “1 1 1 1 1 ”
[Link]("1 "); Row 4 prints “1 1 1 1 ”
[Link](); Row 3 prints “1 1 1 ”
} So we print 1 for j=i to 1
} Ex: first we print for j=5 to j=1 i.e. we
} print “1” 5 times
11111
11111
11111
11111
11111
class Pattern LOGIC:
{ We are printing 1 in each line.
public static void main(String[] args) We have 5 rows so we print “1” 5
{ times in each row
int i; “i” iterates from 1 to 5. It represents
for(i=1;i<=5;i++) //rows the row.
{ “j” iterates from 1 to 5. It represent the
for(int j=1; j<=5;j++) //printing number of times “1” is being printed.
[Link]("1 ");
[Link]();
}
}
}
11111
22222
33333
44444
55555
class Pattern LOGIC:
{ We are printing the row number in
public static void main(String[] args) each line “n” times
{ Where “n” is the total number of rows;
int i; Ex: row 1 prints “1” 5 times
for(i=1;i<=5;i++) //rows Row 2 prints “2” 5 times
{ That’s why we wrote 1 in the print
for(int j=1; j<=5;j++) //printing statement.
[Link](i+ " "); i iterates from 1 to 5
[Link](); j iterates from 1 to 5 representing the
} number of times “row number” is to
} be printed.
}
4. WAP to print the reverse of a number.
import [Link]; Ex: 123
public class Reverse { Last_digit is 3
public static void main(String [] args) 123%10=3
{ Rv= 3 // 0*10+3
int n; We are adding the number in the
Scanner Sc= new Scanner([Link]); unit’s place
n=[Link](); 123/10= 12
int last_digit, reverse=0; Last_digit= 2
while(n>0) 12%10=2
{ Rv=3*10+2 =32
last_digit= n%10; We are adding the number in the
reverse= reverse*10 +last_digit; unit’s place so 3 is in 10’s place now.
n/=10; //removing the last digit 12/10=1
} Last_Digit= 1
[Link](reverse); 1%10=1
} Rv= 32*10 +1 = 321 //answer
} 3 in 100’s place and 2 in 10’s place
1/10=0 STOP
Strings in java:
String is an object that represents a sequence of characters. The [Link]
class is used to create a string object.
How to create a string object?
There are two ways to create String object:
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes.
String s="Example";
String can contain characters, numbers, special characters and white spaces.
Each time you create a string literal, the JVM checks the "string constant pool"
first. If the string already exists in the pool, a reference to the pooled instance is
returned. If the string doesn't exist in the pool, a new string instance is created
and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome"; //It doesn't create a new instance
In other words, it does not allocate new memory space for string s2. Same
memory space is utilized for both. "string constant pool" is the name of the
memory space specially allocated for string in java.
2. By new keyword
String s=new String("Welcome")
** split(String regex) ** Splits the string into String str = "Java is fun";
an array of substrings String[] parts = [Link](" ");
based on the specified // Output: ["Java", "is",
regular expression. "fun"]
// Primitive type
int num = 5;
// Wrapper class Integer
Integer wrappedNum = [Link](num); // Autoboxing
// Unboxing
Some operations on Characters in JAVA:
Operations Description
[Link](char) checks if the character is uppercase
and returns true or false
[Link](char) checks if the character is lowercase
and returns true or false
[Link](char) checks if the character is whitespace
and returns true or false
[Link](char) checks if the character is Letter and
returns true or false
[Link](char) checks if the character is Digit and
returns true or false
[Link](char) checks if the character is letter or digit
and returns true or false
[Link](char) Converts a lowercase character to
uppercase
[Link](char) Converts an uppercase character to
lowercase.
Programs:
1. WAP to accept a string a print each character on a new line and also convert it
to uppercase.
import [Link]; B
public class String1 o
o
{
k
public static void main(String [] args)
{ f
String s; a
Scanner Sc= new Scanner([Link]); i
s=[Link](); r
BOOK FAIR
int l= [Link]();
for(int i=0; i<l; i++) [Link](i); takes the character at the ‘I’th
{ position and prints it.
char z= [Link](i);
[Link](z); [Link]() converts the string to
uppercase.
}
s=[Link]();
[Link](s);
}
}