0% found this document useful (0 votes)
4 views46 pages

Java Basics: Input and Output Methods

Java is a class-based, object-oriented programming language that allows developers to write code once and run it anywhere, thanks to its platform independence. Key features include robustness, security, multithreading, and support for distributed applications. The document also covers Java's data types, operators, variable types, and the structure of a basic Java program.

Uploaded by

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

Java Basics: Input and Output Methods

Java is a class-based, object-oriented programming language that allows developers to write code once and run it anywhere, thanks to its platform independence. Key features include robustness, security, multithreading, and support for distributed applications. The document also covers Java's data types, operators, variable types, and the structure of a basic Java program.

Uploaded by

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

Introduction to Java:

 Java is a class-based, object-oriented programming language that is


designed to have as few implementation dependencies as possible.
 It is intended to let application developers write once, and run
anywhere (WORA), meaning that compiled Java code can run on all
platforms that support Java without the need for recompilation.
 Java was developed by James Gosling at Sun Microsystems Inc in May 1995
and later acquired by Oracle Corporation.
Key Features of Java:
 Platform Independent
Compiler converts source code to byte code and then the JVM executes the
bytecode generated by the compiler. This byte code can run on any platform be it
Windows, Linux, or macOS
 Object-Oriented Programming
Java is an object-oriented language , promoting the use of objects and classes.
The four main concepts of Object-Oriented programming are:
 Abstraction
 Encapsulation
 Inheritance
 Polymorphism

 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

Byte Code Machine Code

Byte Code consisting of binary,


hexadecimal, macro instructions like (new, Machine code consisting of
add, swap, etc) and it is not directly binary instructions that are
understandable by the CPU. It is designed directly understandable by the
for efficient execution by software such as CPU.
a virtual [Link]-level
Byte code is considered as the Machine Code is considered as
intermediate-level code. the low-level code.

Byte code is a non-runnable code Machine code is a set of


generated after compilation of source instructions in machine language
code and it relies on an interpreter to get or in binary format and it is
executed. directly executed by CPU.

Machine code is not executed by


Byte code is executed by the virtual
a virtual machine it is directly
machine then the Central Processing Unit.
executed by CPU.

Machine code is more specific


Byte code is less specific towards
towards machine than the byte
machine than the machine code.
code.

It is not platform independent


because the object code of one
It is platform-independent as it is platform can not be run on the
dependent on the virtual machine and the different Operating System.
system having a virtual machine can be Object varies depending upon
executed irrespective of the platform. system architecture and native
instructions associated with the
machine.

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.

A Basic JAVA program:


public class HelloWorld {
public static void main(String[] args) //main method
{
[Link]("Hello, World!");
}
}

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.

2. **static**: The `main` method is declared `static` so that it can be called


without creating an instance of the class. Java starts the program by calling the
`main` method, and since no objects exist at the start, the method must be static
to allow the runtime to invoke it directly.
3. **void**: This indicates that the `main` method doesn't return any value. It
simply starts the execution of the program and doesn't return anything to the
calling environment (i.e., the Java runtime).

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.

5. **String[] args**: This parameter allows the program to accept command-line


arguments. `args` is an array of strings that stores the arguments passed when the
program is run. If no arguments are passed, the array will be empty but not null.

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.

Data types in JAVA:


Why is the Size of char 2 bytes in Java?
So, other languages like C/C++ use only ASCII characters, and to represent all ASCII
characters 8 bits is enough. But Java uses the Unicode system not the ASCII code
System and to represent the Unicode system 8 bits is not enough to represent all
characters so Java uses 2 bytes for characters. Unicode defines a fully international
character set that can represent most of the world’s written languages. It is a
unification of dozens of character sets, such as Latin, Greek, Cyrillic, Katakana,
Arabic, and many more.

Data type Size in bytes Range Example Default

boolean 1 bit true or false boolean x= true; false

char 2 byte (8 bits) 0-65535 char a= ‘A’ \u0000

byte 1 byte -27 to 27 -1 byte a = 100 0

short 2 byte -215 to 215-1 short a= 1000 0

int 4 byte -231 to 231-1 int a= 10000 0


long 8 byte -263 to 263-1 long a=10000000 0

float 4 byte -3.4*1038 to 3.4*1038 float f=3.14f 0.0

double 8 byte -1.7*10308 to 1.7*10308 double a= 3.14d 0.0

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.

Reserved Words in Java


Any programming language reserves some words to represent functionalities
defined by that language. These words are called reserved words.
They can be briefly categorized into two parts: keywords(50) and literals(3).
Keywords are the reserved words in Java having certain meanings. These words
are not allowed to use as variable names or object names.

abstract continue for protected transient

Assert Default Goto public Try

Boolean Do If Static throws

break double implements strictfp Package

byte else import super Private

case enum Interface Short switch

Catch Extends instanceof return void

Char Final Int synchronized volatile

class finally long throw Date


const float Native This while

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.

What are the Java Operators?


Operators in Java are the symbols used for performing specific operations in Java.
Types of Operators in Java
There are multiple types of operators in Java all are mentioned below:

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);

// Unary decrement (--)


// Decrement 'b' by 1 before using its value
[Link]("Unary Decrement: " + --b);
// 'b' has been decremented
[Link]("b after decrement: " + b);
// Unary plus (+)
int c = -5;
// The unary plus doesn't change the value of 'c'
[Link]("Unary Plus: " + (+c));

// Unary minus (-)


// The unary minus negates the value of 'c'
[Link]("Unary Minus: " + (-c));
// Unary logical NOT (!)
boolean d = false;
// Logical NOT of false is true
[Link]("Unary Logical NOT: " + !d);
// Unary bitwise NOT (~)
int e = 1;
// Bitwise NOT of 1 is -2
[Link]("Unary Bitwise NOT: " + ~e);
}
}
Unary Increment: 11
a after increment: 11
Unary Decrement: 4
b after decrement: 4
Unary Plus: -5
Unary Minus: 5
Unary Logical NOT: true
Unary Bitwise NOT: -2

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

Bitwise left shift


<< Bitwise right shift
6. >> with sign extension Left to right
>>> Bitwise right shift
with zero extension

Relational less than


Relational less than
< or equal
<= Relational greater
7. > than Left to right
Methods to Take Input in Java
There are two ways by which we can take Java input from the user or from a file
 BufferedReader Class
 Scanner Class
Scanner Class in Java
In Java, Scanner is a class in [Link] package used for obtaining the input of the
primitive types like int, double, etc. and strings.

Method Description

nextBoolean() Used for reading Boolean value

nextByte() Used for reading Byte value

nextDouble() Used for reading Double value

nextFloat() Used for reading Float value

nextInt() Used for reading Int value

nextLong() Used for reading Long value

nextShort() Used for reading Short value

next() Used for reading a word

nextLine() Used for reading Line value


Method Description

To read only one character or one


next().charAt(0)
letter from the word

// Java program to read data of various types using Scanner class.


import [Link];
public class ScannerDemo1 {
// main function
public static void main(String[] args)
{
// Declare the object and initialize with
// predefined standard input object
Scanner sc = new Scanner([Link]);

// 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

Important Points About Java Scanner Class


 To create an object of Scanner class, we usually pass the predefined object
[Link], which represents the standard input stream. We may pass an
object of class File if we want to read input from a file.
 To read numerical values of a certain data type XYZ, the function to use is
nextXYZ(). For example, to read a value of type short, we can use
nextShort()
 To read strings, we use nextLine().
 To read a single character, we use next().charAt(0). next() function returns
the next token/word in the input as a string and charAt(0) function returns
the first character in that string.
 The Scanner class reads an entire line and divides the line into tokens.
Tokens are small elements that have some meaning to the Java compiler.
For example, Suppose there is an input string: “How are you”
In this case, the scanner object will read the entire line and divides the
string into tokens: “How”, “are” and “you”. The object then iterates over
each token and reads each token using its different methods.

Java [Link]() is used to print an argument that is passed to it.


Difference between print() and println()
println() print()

It adds new line after the


It does not add any new line.
message gets displayed.

This method only works with argument,


It can work without arguments.
otherwise it is a syntax error.

Flow control in Java:


Decision making statements:
1. if: if statement is the simplest decision-making statement. It is used
to decide whether a certain statement or block of statements will be
executed or not i.e. if a certain condition is true then a block of
statements is executed otherwise not.
if(condition)
{
// Statements to
execute if
// condition is true
}
Note: If we do not provide the
curly braces ‘{‘and ‘}’ after
if(condition ) then by default if
statement will consider the
immediate one statement to be
inside its block.

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;

5. switch-case: The switch statement is a multiway branch statement.


It gives the user a menu to choose from.
 If the choice is out of range, then the statements in the default set are
executed.
 It is not necessary for the default statement to be present in the switch-case
block.
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
 Here, the expression and the values must be of the same datatype.
 Duplicate case values are not allowed.
 Ex: case 1: statement1 ERROR
case 1: statement2
 The break statement is used inside the switch to terminate a statement
sequence.
 The break statements are necessary without the break keyword, statements in
switch blocks fall through.
 If the break keyword is omitted, execution will continue to the next case.
6. jump: Java supports three jump statements: break, continue and return. These
three statements transfer control to another part of the program.
 Break: In Java, a break is majorly used for:
 Terminate a sequence in a switch statement.
 To exit a loop.

 Continue: For early iteration of loop.


 Return: The return statement is used to explicitly return from a method.
That is, it causes program control to transfer back to the caller of the
method.

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:

1. while loop: [Entry control loop]


A while loop is a control flow statement that allows code to be executed
repeatedly based on a given Boolean condition.
Syntax:
while (boolean condition)
{
loop statements...
}
2. do…while loop:
Java do-while loop is an Exit control loop. Therefore, unlike for or while loop, a do-
while check for the condition after executing the statements of the loop body.
do{
// Loop Body
Update_expression
}
while (test_expression); // Condition check
The test_expression for the do-while loop must return a boolean value , else we
would get compile-time error.
For example:
You are implementing a game where you show some options to the user, press 1
to do this .., press 2 to do this .. etc and press ‘Q’ to quit the game. So here you
want to show the game menu to the user at least once, so you write the code for
the game menu inside the do-while loop.

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.

Nested For Loop in Java


Java Nested For Loop is a concept of using a for loop inside another for loop.
for ( initialization; condition; increment ) {
for ( initialization; condition; increment ) {
// statement of inside loop
}
// statement of outer loop
}

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

2. WAP to print the product of n natural numbers or


To print the factorial of the given number.
import [Link];
class Product
{
public static void main(String[] args)
{ int n,product=1,i;
Scanner Sc= new Scanner([Link]); // create an object of Sacnner class
n = [Link]();
for(i=1; i<=n; i++) // to multiply each number from 1 to n
product*=i; //to store the product
[Link]("Product of n natural numbers: "+ product);
}
}
INPUT: 5 OUTPUT: Product of n natural numbers: 120

3. WAP to print the following patterns


1
11
111
1111
11111
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 “1” According to
int i; the row number
for(i=1;i<=5;i++) //rows Ex: row 1 has “1”
{ Row 2 has “1 1”
for(int j=1; j<=i ;j++) //printing Row 3 has “1 1 1” …
[Link]("1 "); So we print “1” for j=1 to j=i where ‘i’ is
[Link](); the row number.
}
}
}
1
22
333
4444
55555
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 “1 time”
for(int j=1; j<=i ;j++) //printing Row 2 prints 2 “2 times”
[Link](i+ " "); Row 3 prints 3 “3 times”
[Link](); So we print “i” for j=1 to j=i where ‘i’ is
} the row number.
}
}

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

5. WAP to check if the given number is palindrome or not.


import [Link]; A palindrome number is a number
public class Reverse { which is same when read from left to
public static void main(String [] args) { right or from right to left.
int n;
Scanner Sc= new Scanner([Link]); We store n’s values in temp so we can
n=[Link](); use it later
int last_digit, reverse=0,temp; N undergoes changes in the loop and
temp=n; it’s reverse gets stored in “reverse”.
while(n>0) Check the before program.
{
last_digit= n%10; OUTPUT:
reverse= reverse*10 +last_digit; 12321
n/=10; //removing the last digit Palindrome
}
if(temp==reverse)
[Link]("Palindrome");
else
[Link]("Not Palindrome");
}
}

6. WAP to check if the given number is special or not.


import [Link]; A special number is a number whose
public class Special{ sum of the digits + product of the digit
public static void main(String [] args) =original number.
{
int n; OUTPUT:
Scanner Sc= new Scanner([Link]); 59
n=[Link](); Special
int last_digit, sum=0, product=1;
int temp=n; //original
while(n>0)
{
last_digit= n%10;
sum+=last_digit;
product*=last_digit;
n/=10; //removing the last digit
}
int xyz = sum+product;
if(temp==xyz)
[Link]("Special");
else
[Link]("Not special");
}
}

7. WAP to check if the given number is automorphic or not.


import [Link]; 5 - 1 digit
public class Automorphic{ temp=10^1=10 //10 to the power digit
public static void main(String [] args)
{ 5*5=25 // square of n
int n;
Scanner Sc= new Scanner([Link]); 25%10 =5 //square% temp =ans
n=[Link](); ans==n
int last_digit, square, pow=0; Yes
square= n*n; else
int temp=n; //original NO
while(n>0) //counting digits of the
original number An automorphic number is a number
{ whose square ends up with the given
last_digit= n%10; number itself.
n/=10; For example: 25 and 76
pow++; 25*25=625
} 76*76=5776
int ans= square %
(int)[Link](10,pow); [Link](base, power);
if(temp==ans) It return the answer in double so we
[Link]("YES"); are converting it to int by using “(int)”
else before the formula
[Link]("NO");
}
}
8. WAP to check if the given number is neon or not.
import [Link]; Ex: 11
public class Neon{ Step1: square the number
public static void main(String [] args) 11*11=121
{ Step2: get the sum of the digits of its
int n; square 1+2+1=5
Scanner Sc= new Scanner([Link]); Step3: Compare the answer and
n=[Link](); original
int last_digit, square, sum=0; 5!=11 so not a neon number.
square= n*n;
while(square>0) //we need the sum of Ex2: 9
digits of the squared one so. 1. 9*9=81
{ 2. 8+1=9
last_digit= square%10; 3. 9==9
sum+=last_digit; So it is a neon number.
square/=10;
}
if(n==sum)
[Link]("Neon");
else
[Link]("Not neon");
}
}

8. WAP to print the sum of positive numbers. Stop when 0 is encountered.


import [Link];  We use do…while loop here so
public class Positive{ that we can take the input and
public static void main(String[] args) { then check the condition.
int n,sum=0;  We use the condition while(n!
Scanner Sc= new Scanner([Link]); =0) because we need to stop
do only when 0 is encountered
{  We use continue so that we can
n=[Link](); skip the number if it is negative.
if(n<0)  We add the number to sum only
continue; when it is positive.
else 5
sum+=n; 4
}while(n!=0); -1
[Link]("Sum:"+sum); } 8
} 0
Sum:17

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")

Java String class methods:

Method Description Example

int length(); Return the length of String S = “Hello”


[Link](); the String int l= [Link](); //5

char charAt(index); It returns char value String S = “Hello”


[Link](index); for the particular char z= [Link](2) // ‘l’
index

substring(int beginIndex) Returns a substring String str = "Hello, World!";


from the specified String sub1 =
index. [Link](7); // Output:
"World"

substring(int beginIndex, int Returns a substring String str = "Hello, World!";


endIndex) from the starting String sub1 =
index to the ending [Link](0,5); //
index Output: “Hello”

indexOf(String str) / Returns the index of String str = "mississippi";


indexOf(char ch) the first occurrence of int index = [Link]('s');
the specified string or // Output: 2
character.

lastIndexOf(String str) / Returns the index of String str = "mississippi";


lastIndexOf(char ch) the last occurrence of int index = str. lastIndexOf
the specified string or ('s'); // Output: 6
character.

contains(CharSequence s) Checks whether the String str = "Hello World";


string contains the boolean result =
specified sequence of [Link]("World"); //
characters. Output: true

[Link](S2); Compares the content String str1 = "Geeks";


of two strings for String str2 = "Geeks";
equality. boolean s=
[Link](str2); // true

[Link](str2); Compares two strings, String str1 = "Geeks";


ignoring case String str2 = "geeks";
considerations. boolean s=
[Link](str2)
; // true

toLowerCase() Converts all String str = "Geeks";


characters in the String lower =
string to lowercase. [Link](); //
Output: "geeks"

toUpperCase() Converts all String str = "Geeks";


characters in the String upper =
string to uppercase. [Link](); //
Output: "GEEKS"

trim() Removes leading and String str =


trailing whitespace " Hello World ";
from the string. String trimmed = [Link]();
// Output: "Hello World"

replace(char1, char2) Replaces all String str=”mississippi”;


replace(Sequence1, occurrences of the old String str= [Link](‘s’,
Sequence2) character or substring ‘z’);
with the new one. // mizzizzippi

** replaceAll(String regex, Replaces all substrings String str = "123abc456";


String replacement) ** that match the regex String replaced =
with the specified [Link]("\\d", "*");
replacement. // Output: "***abc***"

** 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"]

startsWith(String prefix) Checks if the string String str = "mississippi";


starts with the boolean result =
specified prefix. [Link]("mis"); //
Output: true

endsWith(String suffix) Checks if the string String str = "mississippi";


ends with the boolean result =
specified suffix. [Link]("ppi"); //
Output: true

isEmpty() Checks if the string is String str = "";


empty (i.e., its length boolean isEmpty =
is 0). [Link](); // true

valueOf() Converts other data int num = 100;


[Link](variable_of_O types (like int, float, String str =
therDatatype); etc.) to a string. [Link](num); //
Output: "100"

[Link](str2); Compares two strings String s= “can”


lexicographically. String P= “cam”
If lengths are int a=[Link](P);
different, it will c-c
compare the a-a
characters with the n-m
least length. 111-110 = 1
If both are same, it Can comes after cam
will take out the In dictionary
difference of the Ex:
lengths. The one with “Rahul”.compareTo(“Ra”);
smaller length comes R-R, a-a;
first. 5-2 = 3 //ans

[Link](str2); Concatenates the String str1 = "Hello"; String


specified string to the str2 = "World";
end of the current String str=
string. //no space [Link](str2);
//HelloWorld

** matches(String regex) ** Checks whether the String str = "12345";


string matches the boolean isMatch =
specified regular [Link]("\\d+"); //
expression. Output: true

** intern() ** Ensures that the String str1 = new


string is in the string String("Geeks");
pool and returns the String str2 = [Link]();
reference from the // Returns the string from
pool. the pool

Wrapper Classes in JAVA:


In Java, wrapper classes are used to convert primitive data types into objects.
 int → Integer
 char → Character
 byte → Byte
 short → Short
 long → Long
 float → Float
 double → Double
 boolean → Boolean
Why Use Wrapper Classes?
1. Object-Oriented Nature: Since Java is an object-oriented language, there
are situations where an object is required, but primitive types are not
objects. Wrapper classes allow the use of primitive types in these scenarios.
2. Collections Framework: Java collections, like ArrayList, only store objects,
not primitives. Wrapper classes are used to store primitive values in
collections.
3. Autoboxing/Unboxing: Java automatically converts primitives to their
corresponding wrapper class objects when needed (autoboxing) and vice
versa (unboxing). This reduces manual conversion.

Integer wrappedNum = num; // Autoboxing


int unwrappedNum = wrappedNum; // Unboxing

// 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);
}
}

2. WAP to initialize a string “c:\\users\\[Link]” and print its path, filename


and extension.

public class Occurrence path:c:\users\


{ file name:flower
extension:jpg
public static void main(String[] args)
{ path name starts from the first character and
String s="c:\\users\\[Link]"; ends at “\\”.
int l=[Link](); So we need to find the last occurrence of “\\”
int a=[Link]("\\"); Since in the formula
int b=[Link]("."); [Link](start,end);
Start is inclusive and end is exclusive we write
a+1;
[Link]("path:"+
[Link](0,a+1)); Filename starts AFTER “\\” so we write a+1.
[Link]("file name:"+ And ends at “.” We only write b.
[Link](a+1,b)); And we find the “.” Last occurrence because,
[Link]("extension:"+ extension is present at the last.
For example: .ppt
[Link](b+1,l));
} Extension starts from . and ends till the last
} So we write b+1(to not include “.”) to l(length
of the string).

3. WAP to accept a string a print its reverse.


import [Link]; Since we want the reverse of the string, we
public class Reverse start printing each character of the string
{ from the back.
public static void main(String[] args) So we start from l-1.
{ Ex:
String s; Apple - elppA
Scanner sc=new Scanner([Link]); 01234 - 43210
s=[Link](); [Link](i); is used to take the character at
int l=[Link](); the i th position.
for(int i=l-1 ; i >= 0; i--) i iterates from l-1 to 0.
{
[Link]([Link](i));
}
}
}

You might also like