Java College Notes
Java College Notes
Java College Notes
INSTALLATION IN JAVA
PROPERTIES OF CLASSES : -
COMMENTS IN JAVA
I. PRIMITIVE DATATYPES : -
LITERALS
KEYWORDS
The Java Scanner class is widely used to parse text for strings
and primitive types using a regular expression. It is the simplest
way to get input in Java. By the help of Scanner in Java, we can
get input from the user in primitive types such as int, long,
double, byte, float, short, etc.
To get the instance of Java Scanner which reads input from the
user, we need to pass the input stream (System.in) in the
constructor of Scanner class. For Example:
Example 1
1. import java.util.*;
2. public class ScannerExample {
3. public static void main(String args[]){
4. Scanner in = new Scanner(System.in);
5. System.out.print("Enter your name: ");
6. String name = in.nextLine();
7. System.out.println("Name is: " + name);
8. in.close();
9. }
10. }
Output:
Example 2
1. import java.util.*;
2. public class ScannerClassExample1 {
3. public static void main(String args[]){
4. String s = "Hello, This is JavaTpoint.";
5. //Create scanner Object and pass string in it
6. Scanner scan = new Scanner(s);
7. //Check if the scanner has a token
8. System.out.println("Boolean Result: " + scan.hasNe
xt());
9. //Print the string
10. System.out.println("String: " +scan.nextLine());
11. scan.close();
12. System.out.println("--------Enter Your Details--------
");
13. Scanner in = new Scanner(System.in);
14. System.out.print("Enter your name: ");
15. String name = in.next();
16. System.out.println("Name: " + name);
17. System.out.print("Enter your age: ");
18. int i = in.nextInt();
19. System.out.println("Age: " + i);
20. System.out.print("Enter your salary: ");
21. double d = in.nextDouble();
22. System.out.println("Salary: " + d);
23. in.close();
24. }
25. }
Output:
Example 3
1. import java.util.*;
2. public class ScannerClassExample2 {
3. public static void main(String args[]){
4. String str = "Hello/This is JavaTpoint/My name is A
bhishek.";
5. //Create scanner with the specified String Object
6. Scanner scanner = new Scanner(str);
7. System.out.println("Boolean Result: "+scanner.hasN
extBoolean());
8. //Change the delimiter of this scanner
9. scanner.useDelimiter("/");
10. //Printing the tokenized Strings
11. System.out.println("---Tokenizes String---");
12. while(scanner.hasNext()){
13. System.out.println(scanner.next());
14. }
15. //Display the new delimiter
16. System.out.println("Delimiter used: " +scanner.deli
miter());
17. scanner.close();
18. }
19. }
Output:
import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
int e = sc.nextInt();
int div = (a+b+c+d+e)/500;
int percentage = div * 100 ;
System.out.println(percentage);
}
}
PRACTICE SET 1
import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
int e = sc.nextInt();
int sum = (a+b+c+d+e);
System.out.println(sum);
}
}
WRITE A PROGRAM TO PRINT THE CGPA OF A
STUDENT
import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int cgpa = (a+b+c)/300;
System.out.println(cgpa);
}
}
import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
System.out.println("Hello " + a + " , have a good day");
}
}
WRITE A PROGRAM TO CONVERT KILOMETERS TO
MILES
import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
float kilometers = sc.nextFloat();
float miles = kilometers * (0.62f) ;
System.out.println(miles);
}
}
import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Boolean a = sc.hasNextInt();
if(a == true){
System.out.println("Integer");
}
else{
System.out.println("Decimal");
}
}
}
************END OF PRACTICE SET
1***********
a. Arithmetic Operators
b. Assignment Operators
c. Comparison Operators
d. Logical Operators
e. Bit wise Operators
ARITHMETIC OPERATORS
BINARY OPERATORS
UNARY OPERATORS
Java unary operators are the types that need only one operand to
perform any operation like increment, decrement, negation, etc.
It consists of various arithmetic, logical and other operators that
operate on a single operand. Let’s look at the various unary
operators in detail and see how they operate.
Syntax:
-(operand)
Illustration:
a = -10
Example:
// Java Program to Illustrate Unary - Operator
// Main class
class GFG {
Output
Number = 20
Result = -20
Operator 2: ‘NOT’ Operator(!)
This is used to convert true to false or vice versa. Basically, it
reverses the logical state of an operand.
Syntax:
!(operand)
Illustration:
cond = !true;
// cond < false
Example:
// Main class
class GFG {
Output
Cond is: true
Var1 = 10
Var2 = 1
Now cond is: false
!(a < b) = true
!(a > b) = false
Operator 3: Increment(++)
It is used to increment the value of an integer. It can be used in
two separate ways:
When placed after the variable name, the value of the operand is
incremented but the previous value is retained temporarily until
the execution of this statement and it gets updated before the
execution of the next statement.
Syntax:
num++
Illustration:
num = 5
num++ = 6
3.2: Pre-increment operator
Syntax:
++num
Illustration:
num = 5
++num = 6
Operator 4: Decrement ( — )
It is used to decrement the value of an integer. It can be used in
two separate ways:
When placed after the variable name, the value of the operand is
decremented but the previous values is retained temporarily
until the execution of this statement and it gets updated before
the execution of the next statement.
Syntax:
num--
Illustration:
num = 5
num-- = 4 // Value will be decremented before execution of next
statement.
4.2: Pre-decrement operator
Syntax:
--num
Illustration:
num = 5
--num = 4 //output is 5, value is decremented before execution
of next statement
Operator 5: Bitwise Complement(~)
This unary operator returns the one’s complement representation
of the input value or operand, i.e, with all bits inverted, which
means it makes every 0 to 1, and every 1 to 0.
Syntax:
~(operand)
Illustration:
a = 5 [0101 in Binary]
result = ~5
This performs a bitwise complement of 5
~0101 = 1010 = 10 (in decimal)
Then the compiler will give 2’s complement
of that number.
2’s complement of 10 will be -6.
result = -6
Example:
// Main class
class GFG {
Output
First Number = 6
Second Number = -2
6's bitwise complement = -7
-2's bitwise complement = 1
Example program in Java that implements all basic unary
operators for user input:
import java.util.Scanner;
// Initialize num
int num = 10;
// Unary plus
int result = +num;
System.out.println("The value of result after unary plus is:
" + result);
// Unary minus
result = -num;
System.out.println("The value of result after unary minus is:
" + result);
// Pre-increment
result = ++num;
System.out.println("The value of result after pre-increment
is: " + result);
// Post-increment
result = num++;
System.out.println("The value of result after post-
increment is: " + result);
// Pre-decrement
result = --num;
System.out.println("The value of result after pre-decrement
is: " + result);
// Post-decrement
result = num--;
System.out.println("The value of result after post-
decrement is: " + result);
Output
The value of result after unary plus is: 10
The value of result after unary minus is: -10
The value of result after pre-increment is: 11
The value of result after post-increment is: 11
The value of re...
Explanation:
The above program implements all basic unary operators in Java
using user input. The program uses the Scanner class from the
java.util package to read user input from the console. The
following steps describe how the program works in detail:
Import the java.util.Scanner class: The program starts by
importing the Scanner class, which is used to read input from
the console.
Create a Scanner object: Next, a Scanner object sc is created and
associated with the standard input stream System.in.
Read the number from the user: The program prompts the user
to enter a number and uses the nextInt() method of the Scanner
class to read the input. The input is stored in the num variable of
type int.
Use unary plus operator: The program uses the unary plus
operator + to perform a positive operation on num. The result of
the operation is stored in the result variable of type int.
Use unary minus operator: The program uses the unary minus
operator – to perform a negative operation on num. The result of
the operation is stored in the result variable.
Use pre-increment operator: The program uses the pre-
increment operator ++ to increment the value of num before
using it in an expression. The result of the operation is stored in
the result variable.
Use post-increment operator: The program uses the post-
increment operator ++ to increment the value of num after using
it in an expression. The result of the operation is stored in the
result variable.
Use pre-decrement operator: The program uses the pre-
decrement operator — to decrement the value of num before
using it in an expression. The result of the operation is stored in
the result variable.
Use post-decrement operator: The program uses the post-
decrement operator — to decrement the value of num after using
it in an expression. The result of the operation is stored in the
result variable.
Print the results: The program prints out the final values of
result using the println method of the System.out object after
each operation.
This program demonstrates how to use basic unary operators in
Java. The Scanner class makes it easy to read user input from
the console, and various unary operators are used to modify the
value of the num variable in the program.
Advantages
The main advantage of using unary operators in Java is that they
provide a simple and efficient way to modify the value of a
variable. Some specific advantages of using unary operators are:
Concise and Easy to Use: Unary operators are simple to use and
require only one operand. They are easy to understand and make
code more readable and concise.
Faster than Other Operators: Unary operators are faster than
other operators as they only require one operand. This makes
them ideal for operations that need to be performed quickly,
such as incrementing a counter.
Pre- and Post-Increment/Decrement: Unary operators provide
both pre- and post-increment and decrement options, which
makes them useful for a variety of use cases. For example, the
pre-increment operator can be used to increment the value of a
variable before using it in an expression, while the post-
increment operator can be used to increment the value of a
variable after using it in an expression.
Modifying Primitive Types: Unary operators can be used to
modify the value of primitive types such as int, long, float,
double, etc.
Overall, unary operators provide a simple and efficient way to
perform operations on variables in Java, and they can be used in
a variety of scenarios to make code more readable and concise.
ASSIGNMENT OPERATORS
1. (=) operator:
This is the most straightforward assignment operator, which is
used to assign the value on the right to the variable on the left.
This is the basic definition of an assignment operator and how it
functions.
Syntax:
num1 = num2;
Example:
a = 10;
ch = 'y';
// Java code to illustrate "=" operator
import java.io.*;
class Assignment {
public static void main(String[] args)
{
// Declaring variables
int num;
String name;
// Assigning values
num = 10;
name = "GeeksforGeeks";
Syntax:
num1 += num2;
Example:
a += 10
This means,
a = a + 10
// Java code to illustrate "+="
import java.io.*;
class Assignment {
public static void main(String[] args)
{
// Declaring variables
int num1 = 10, num2 = 20;
int x = 5;
If you want to add the double value 4.5 to the integer variable x
and print its value, there are two methods to achieve this:
Method 1: x = x + 4.5
Method 2: x += 4.5
As per the previous example, you might think both of them are
equal. But in reality, Method 1 will throw a runtime error stating
the “incompatible types: possible lossy conversion from double
to int“, Method 2 will run without any error and prints 9 as
output.
Method 2 will run without any error and print the value 9 as
output. The compound assignment operator += performs an
implicit type conversion, also known as an automatic narrowing
primitive conversion from double to int. It is equivalent to x =
(int) (x + 4.5), where the result of the addition is explicitly cast
to an int. The fractional part of the double value is truncated,
and the resulting int value is assigned back to x.
3. (-=) operator:
This operator is a compound of ‘-‘ and ‘=’ operators. It operates
by subtracting the variable’s value on the right from the current
value of the variable on the left and then assigning the result to
the operand on the left.
Syntax:
num1 -= num2;
Example:
a -= 10
This means,
a = a - 10
// Java code to illustrate "-="
import java.io.*;
class Assignment {
public static void main(String[] args)
{
// Declaring variables
int num1 = 10, num2 = 20;
num1 *= num2;
Example:
a *= 10
This means,
a = a * 10
// Java code to illustrate "*="
import java.io.*;
class Assignment {
public static void main(String[] args)
{
// Declaring variables
int num1 = 10, num2 = 20;
Syntax:
num1 /= num2;
Example:
a /= 10
This means,
a = a / 10
// Java code to illustrate "/="
import java.io.*;
class Assignment {
public static void main(String[] args)
{
// Declaring variables
int num1 = 20, num2 = 10;
Syntax:
num1 %= num2;
Example:
a %= 3
This means,
a=a%3
// Java code to illustrate "%="
import java.io.*;
class Assignment {
public static void main(String[] args)
{
// Declaring variables
int num1 = 5, num2 = 3;
COMPARISON OPERATORS
1. Relational Operators
2. Logical operators
3. Ternary Operators
RELATIONAL OPERATORS
Syntax:
Syntax:
var1 == var2
Illustration:
var1 = "GeeksforGeeks"
var2 = 20
var1 == var2 results in false
Example:
// Main class
class GFG {
Syntax:
var1 != var2
Illustration:
var1 = "GeeksforGeeks"
var2 = 20
// Main class
class GFG {
This checks whether the first operand is greater than the second
operand or not. The operator returns true when the operand at
the left-hand side is greater than the right-hand side.
Syntax:
var1 = 30
var2 = 20
// Main class
class GFG {
This checks whether the first operand is less than the second
operand or not. The operator returns true when the operand at
the left-hand side is less than the right-hand side. It functions
opposite to that of the greater-than operator.
Syntax:
var1 = 10
var2 = 20
// Main class
class GFG {
Syntax:
var1 = 20
var2 = 20
var3 = 10
// Main class
class GFG {
Syntax:
var1 = 10
var2 = 10
var3 = 9
// Main class
class GFG {
Advantages
There are several advantages of using relational operators in
Java, including:
Easy to understand: Relational operators are simple and easy to
understand, making it easy to write code that performs
comparisons.
Versatile: Relational operators can be used to compare values of
different data types, such as integers, floating-point numbers,
and strings.
Essential for making decisions: Relational operators are
essential for making decisions in a program, as they allow you
to control the flow of a program based on the results of
comparisons.
Efficient: Relational operators are efficient, as they perform
comparisons quickly and accurately.
Reusable code: The code that uses relational operators can be
reused in different parts of a program, making it easier to
maintain and update the code.
Improved code readability: By using relational operators, you
can make your code more readable and understandable, as the
comparisons are clearly stated in the code.
Debugging made easier: Relational operators make debugging
easier, as you can use them to check the values of variables and
to find out where a problem is occurring in your code.
LOGICAL OPERATORS
Logical operators are used to perform logical “AND”, “OR” and
“NOT” operations, i.e. the function similar to AND gate and OR
gate in digital electronics. They are used to combine two or
more conditions/constraints or to complement the evaluation of
the original condition under particular consideration. One thing
to keep in mind is, while using AND operator, the second
condition is not evaluated if the first one is false. Whereas while
using OR operator, the second condition is not evaluated if the
first one is true, i.e. the AND and OR operators have a short-
circuiting effect. Used extensively to test for several conditions
for making a decision.
AND Operator ( && ) – if( a && b ) [if true execute else don’t]
OR Operator ( || ) – if( a || b) [if one of them is true to execute
else don’t]
NOT Operator ( ! ) – !(a<b) [returns false if a is smaller than b]
Example For Logical Operator in Java
Here is an example depicting all the operators where the values
of variables a, b, and c are kept the same for all the situations.
a = 10, b = 20, c = 30
Condition 1: c > a
Condition 2: c > b
Output:
For OR Operator:
Condition 1: c > a
Condition 2: c > b
Output:
Condition 1: c > a
Condition 2: c > b
Output:
False [Because the result was true and NOT operator did it’s
opposite]
Syntax:
a = 10, b = 20, c = 20
condition1: a < b
condition2: b == c
if(condition1 && condition2)
d=a+b+c
import java.io.*;
class Logical {
public static void main(String[] args)
{
// initializing variables
int a = 10, b = 20, c = 20, d = 0;
// Displaying a, b, c
System.out.println("Var1 = " + a);
System.out.println("Var2 = " + b);
System.out.println("Var3 = " + c);
Output
Var1 = 10
Var2 = 20
Var3 = 20
The sum is: 50
Example:
import java.io.*;
class shortCircuiting {
public static void main(String[] args)
{
// initializing variables
int a = 10, b = 20, c = 15;
// displaying b
System.out.println("Value of b : " + b);
// displaying b
System.out.println("Value of b : " + b);
}
}
Output:
Syntax:
condition1 || condition2
Example:
a = 10, b = 20, c = 20
condition1: a < b
condition2: b > c
if(condition1 || condition2)
d=a+b+c
d = 50.
Illustration:
import java.io.*;
class Logical {
public static void main(String[] args)
{
// initializing variables
int a = 10, b = 1, c = 10, d = 30;
// Displaying a, b, c
System.out.println("Var1 = " + a);
System.out.println("Var2 = " + b);
System.out.println("Var3 = " + c);
System.out.println("Var4 = " + d);
Output
Var1 = 10
Var2 = 1
Var3 = 10
Var4 = 30
One or both + the conditions are true
import java.io.*;
class ShortCircuitingInOR {
public static void main (String[] args) {
// initializing variables
int a = 10, b = 20, c = 15;
// displaying b
System.out.println("Value of b: " +b);
// Using logical OR
// Short-circuiting effect as the first condition is true
// so the second condition is never reached
// and so ++b (pre-increment) doesn't take place and
// value of b remains unchanged
if((a < c) || (++b < c))
System.out.println("Inside if");
// displaying b
System.out.println("Value of b: " +b);
}
}
Output
Value of b: 20
Inside if
Value of b: 20
Syntax:
!(condition)
Example:
a = 10, b = 20
Illustartion:
class Logical {
public static void main(String[] args)
{
// initializing variables
int a = 10, b = 1;
// Displaying a, b, c
System.out.println("Var1 = " + a);
System.out.println("Var2 = " + b);
Output
a: true
b: false
a && b: false
a || b: true
!a: false
!b: true
Explanation:
The code above is a Java program that implements all logical
operators with default values. The program defines a class
LogicalOperators with a main method.
In the main method, two boolean variables a and b are defined
and assigned default values true and false, respectively.
The program then prints the values of a and b to the console
using the System.out.println method. This allows us to verify the
values assigned to a and b.
Next, the program calculates the result of the logical operators
&& (and), || (or), and ! (not) applied to a and b. The results of
these operations are also printed to the console using the
System.out.println method.
The && operator returns true if both operands are true;
otherwise, it returns false. In this case, the result of a && b is
false.
The || operator returns true if either operand is true; otherwise, it
returns false. In this case, the result of a || b is true.
The ! operator negates the value of its operand. If the operand is
true, the result is false, and if the operand is false, the result is
true. In this case, the results of !a and !b are false and true,
respectively.
The output of the program shows the truth table for all logical
operators. This table provides a visual representation of how
these operators behave for all possible combinations of true and
false inputs.
Advantages of logical operators:
Short-circuit evaluation: One of the main advantages of logical
operators is that they support short-circuit evaluation. This
means that if the value of an expression can be determined
based on the left operand alone, the right operand is not
evaluated at all. While this can be useful for optimizing code
and preventing unnecessary computations, it can also lead to
subtle bugs if the right operand has side effects that are expected
to be executed.
Readability: Logical operators make code more readable by
providing a clear and concise way to express complex
conditions. They are easily recognizable and make it easier for
others to understand the code.
Flexibility: Logical operators can be combined in various ways
to form complex conditions, making the code more flexible.
This allows developers to write code that can handle different
scenarios and respond dynamically to changes in the program’s
inputs.
Reusability: By using logical operators, developers can write
code that can be reused in different parts of the program. This
reduces the amount of code that needs to be written and
maintained, making the development process more efficient.
Debugging: Logical operators can help to simplify the
debugging process. If a condition does not behave as expected,
it is easier to trace the problem by examining the results of each
logical operator rather than having to navigate through a
complex code structure.
Disadvantages of logical operators:
Limited expressiveness: Logical operators have a limited
expressive power compared to more complex logical constructs
like if-else statements and switch-case statements. This can
make it difficult to write complex conditionals that require more
advanced logic, such as evaluating multiple conditions in a
specific order.
Potential for confusion: In some cases, the use of logical
operators can lead to confusion or ambiguity in the code. For
example, consider the expression a or b and c. Depending on the
intended order of operations, this expression can have different
interpretations. To avoid this kind of confusion, it is often
recommended to use parentheses to explicitly specify the order
of evaluation.
Boolean coercion: Logical operators can sometimes lead to
unexpected behavior when used with non-Boolean values. For
example, when using the or operator, the expression a or b will
evaluate to a if a is truthy, and b otherwise. This can lead to
unexpected results if a or b are not actually Boolean values, but
instead have a truthy or false interpretation that does not align
with the programmer’s intentions.
Overall, logical operators are an important tool for developers
and play a crucial role in the implementation of complex
conditions in a program. They help to improve the readability,
flexibility, reusability, and debuggability of the code.
TERNARY OPERATORS
Syntax:
if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}
Example:
num1 = 10;
num2 = 20;
res=(num1>num2) ? (num1+num2):(num1-num2)
Since num1<num2,
the second operation is performed
res = num1-num2 = -10
import java.io.*;
class Ternary {
public static void main(String[] args)
{
// variable declaration
int n1 = 5, n2 = 10, max;
Output
First num: 5
Second num: 10
Maximum is = 10
Example 2:
Below is the implementation of the above method:
import java.io.*;
class Ternary {
public static void main(String[] args)
{
// variable declaration
int n1 = 5, n2 = 10, res;
Output
First num: 5
Second num: 10
Result = -5
Example 3:
Implementing ternary operator on Boolean values:
// Driver Class
public class TernaryOperatorExample {
// main function
public static void main(String[] args)
{
boolean condition = true;
String result = (condition) ? "True" : "False";
System.out.println(result);
}
}
Output
True
BITWISE OPERATORS
1. Bitwise OR (|)
This operator is a binary operator, denoted by ‘|’. It returns bit
by bit OR of input values, i.e., if either of the bits is 1, it gives 1,
else it shows 0.
Example:
Example:
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Example:
~ 0101
________
1010 = 10 (In decimal)
Note: Compiler will give 2’s complement of that number, i.e.,
2’s complement of 10 will be -6.
// bitwise and
// 0101 & 0111=0101 = 5
System.out.println("a&b = " + (a & b));
// bitwise or
// 0101 | 0111=0111 = 7
System.out.println("a|b = " + (a | b));
// bitwise xor
// 0101 ^ 0111=0010 = 2
System.out.println("a^b = " + (a ^ b));
// bitwise not
// ~00000000 00000000 00000000 00000101=11111111
11111111 11111111 11111010
// will give 2's complement (32 bit) of 5 = -6
System.out.println("~a = " + ~a);
Output
a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5
Auxiliary space:O(1)
Time complexity:O(1)
class GFG {
public static void main (String[] args) {
String binary[]={
"0000","0001","0010","0011","0100","0101",
"0110","0111","1000","1001","1010",
"1011","1100","1101","1110","1111"
};
// bitwise or
int c= a | b;
// bitwise and
int d= a & b;
// bitwise xor
int e= a ^ b;
// bitwise not
int f= (~a & b)|(a &~b);
int g= ~a & 0x0f;
System.out.println(" a= "+binary[a]);
System.out.println(" b= "+binary[b]);
System.out.println(" a|b= "+binary[c]);
System.out.println(" a&b= "+binary[d]);
System.out.println(" a^b= "+binary[e]);
System.out.println("~a & b|a&~b= "+binary[f]);
System.out.println("~a= "+binary[g]);
}
}
Output
a= 0011
b= 0110
a|b= 0111
a&b= 0010
a^b= 0101
~a & b|a&~b= 0101
~a= 1100
Bit-Shift Operators (Shift Operators)
Shift 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.
Syntax:
input.close();
}
}
Input
Bitwise AND: 0
Bitwise OR: 12
Bitwise XOR: 12
Bitwise NOT: -5
Bitwise Left Shift: 16
Bitwise Right Shift: 1
Bitwise Unsigned Right Shift: 1
Explanation
This program prompts the user to enter two numbers, num1
and num2. It then performs the following bitwise operations
using the &, |, ^, ~, <<, >>, and >>> operators:
Bitwise AND
Bitwise OR
Bitwise XOR
Bitwise NOT
Bitwise Left Shift
Bitwise Right Shift
Bitwise Zero Fill Right Shift
Advantages
The advantages of using Bitwise Operators in Java are:
Sign Description
Signed Left Shift << The left shift operator moves all bits
by a given number of bits to the left.
Signed Right Shift >> The right shift operator moves all
bits by a given number of bits to the right.
Unsigned Right Shift >>> It is the same as the signed right
shift, but the vacant leftmost position is filled with 0 instead of
the sign bit.
1. Signed Left Shift Operator in Java
This operator is represented by a symbol <<, read as double less
than.
Syntax:
class GFG {
public static void main(String[] args)
{
byte a = 64, b;
int i;
i = a << 2;
b = (byte)(a << 2);
System.out.println("Original value of a: " + a);
System.out.println("i and b: " + i + " " + b);
}
}
Calculating the value of number<<2 if number=2. When the
value of a number is shifted to the left two places, the leftmost
two bits are lost. The number has a value of two. 0010 is the
binary representation of the number 2. In the following example,
the method for doing a left shift is explained:
Example:
// Main class
class GFG {
System.out.println(Ans);
}
}
Output
8
2. Signed Right Shift Operator in Java
The Right Shift Operator moves the bits of a number in a given
number of places to the right. The >> sign represents the right
shift operator, which is understood as double greater than. When
you type x>>n, you tell the computer to move the bits x to the
right n places.
Syntax:
Example:
System.out.println(Ans);
}
}
}
class GFG {
public static void main (String[] args) {
char hex[]={
'0','1','2','3','4','5',
'6','7','8','9','a','b','c',
'd','e','f'
};
class GFG
{
public static void main (String[] args)
{
byte num1 = 8;
byte num2 = -8;
ASSOCIATIVITY OF OPERATORS
= += -= *= /= %=
assignment &= ^= |= right to left
<<= >>= >>>=
OUTPUT :
4.0
import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int grade = sc.nextInt();
int newgrade = grade + 8;
System.out.println(grade);
}
}
import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = 10;
int b = sc.nextInt();
if(a>b){
System.out.println("Smaller");
}
else{
System.out.println("Bigger");
}
}
}
import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = 7*49/7+35/7 ;
System.out.println(a);
}
}
****************END OF PRACTICE SET
2******************
STRINGS IN JAVA
Strings are the type of objects that can store the character of
values and in Java, every character is stored in 16 bits i,e using
UTF 16-bit encoding. A string acts the same as an array of
characters in Java.
Example:
String name = "Geeks";
String Example in Java
String Example in Java
// Main Function
public static void main(String args[])
{
String str = new String("example");
// creating Java string by new keyword
// this statement create two object i.e
// first the object is created in heap
// memory area and second the object is
// created in String constant pool.
System.out.println(str);
}
}
Output
example
Ways of Creating a String
There are two ways to create a string in Java:
String Literal
Using new Keyword
Syntax:
Example:
CharSequence Interface
CharSequence Interface is used for representing the sequence of
Characters in Java.
Classes that are implemented using the CharSequence interface
are mentioned below and these provides much of functionality
like substring, lastoccurence, first occurence, concatenate ,
toupper, tolower etc.
String
StringBuffer
StringBuilder
1. String
String is an immutable class which means a constant and cannot
be changed once created and if wish to change , we need to
create an new object and even the functionality it provides like
toupper, tolower, etc all these return a new object , its not
modify the original object. It is automatically thread safe.
Syntax
Syntax:
Syntax:
Example:
String Tokenizer in Java
A StringTokenizer object internally maintains a current position
within the string to be tokenized. Some operations advance this
current position past the characters processed. A token is
returned by taking a substring of the string that was used to
create the StringTokenizer object.
Syntax:
Here the JVM checks the String Constant Pool. If the string does
not exist, then a new string instance is created and placed in a
pool. If the string exists, then it will not create a new object.
Rather, it will return the reference to the same instance. The
cache that stores these string instances is known as the String
Constant pool or String Pool. In earlier versions of Java up to
JDK 6 String pool was located inside PermGen(Permanent
Generation) space. But in JDK 7 it is moved to the main heap
area.
class GFG {
public static void main(String[] args)
{
String s = "Sachin";
Output
Sachin
Here Sachin is not changed but a new object is created with
“Sachin Tendulkar”. That is why a string is known as immutable.
As you can see in the given figure that two objects are created
but s reference variable still refers to “Sachin” and not to
“Sachin Tendulkar”. But if we explicitly assign it to the
reference variable, it will refer to the “Sachin Tendulkar” object.
For Example:
class GFG {
public static void main(String[] args)
{
String name = "Sachin";
name = name.concat(" Tendulkar");
System.out.println(name);
}
}
Output
Sachin Tendulkar
Memory Allotment of String
Whenever a String Object is created as a literal, the object will
be created in the String constant pool. This allows JVM to
optimize the initialization of String literal.
Example:
Example:
Example:
class Test {
public static void main(String[] args)
{
// Declare String without using new operator
String name = "GeeksforGeeks";
Output
String name = GeeksforGeeks
String newString = GeeksforGeeks
Why did the String pool move from PermGen to the normal
heap area?
PermGen space is limited, the default size is just 64 MB. it was
a problem with creating and storing too many string objects in
PermGen space. That’s why the String pool was moved to a
larger heap area. To make Java more memory efficient, the
concept of string literal is used. By the use of the ‘new’ keyword,
The JVM will create a new string object in the normal heap area
even if the same string object is present in the string pool.
For example:
Example 1:
// Driver Class
class GFG {
// main function
public static void main(String args[])
{
byte ascii[] = { 71, 70, 71 };
Output
GFG
FG
Example 2:
// Construct one string from another
class GFG {
public static void main(String args[])
{
System.out.println(firstString);
System.out.println(secondString);
}
}
Output
Gfg
Gfg
STRING METHODS
Control Sequence:
A control sequence is nothing however the backslash(\) glued
with a character (the character which has to be escaped) is called
a control sequence.
Example:
Java
public class Test {
public static void main(String[] args)
{
System.out.println("Hi geek, welcome to
\"GeeksforGeeks\".");
}
}
Output: Hi geek, welcome to "GeeksforGeeks".
Some Coding Examples of Java Escape Characters
Output:
Good Morning Geeks!
Java code for the escape sequence \b :
Java
// The escape sequence \b is a backspace character
// It moves the cursor one character back with
// or without deleting the character(depending upon compiler)
Output:
Good Morning Geeks!
How are you all?
Output:
Good Morning 'Geeks!' How are you all?
Java code for the escape sequence \”
Java
// This \" escape sequence is for printing a double quotation
mark on the text string
Output:
Good Morning "Geeks!" How are you all?
Java code for the escape sequence \\
Java
// This \\ escape sequence is for printing a backslash on the text
string
Output:
\- this is a backslash.
Explanation:It contains two backslashes, this means after
reading the first \ the compiler read the next \ as a new character
STRINGS PRACTICE SET
import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
System.out.println(a.toLowerCase());
}
}
import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
System.out.println(a.replace(" ", "_"));
}
}
import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
String letter = "Dear Yash Thanks a Lot";
System.out.println(letter.replace("Yash", a));
}
}
import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
String b = a.replace(" ", "--");
String c = a.replace(" ", "---");
System.out.println(b);
System.out.println(c);
}
}
import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
String letter = "Dear Harry , This java course is nice .
Thanks ! ";
}
}
************END OF PRACTICE SET ON
STRINGS***********
CONDITIONALS
1) If - Else Statements.
IF - ELSE STATEMENTS
If-Else in Java
If- else together represents the set of Conditional statements in
Java that are executed according to the condition which is true.
class IfElseDemo {
public static void main(String args[])
{
int i = 20;
if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
Output
i is greater than 15
Outside if-else block
Nested if statement in Java
In Java, we can use nested if statements to create more complex
conditional logic. Nested if statements are if statements inside
other if statements.
Syntax:
if (condition1) {
// code block 1
if (condition2) {
// code block 2
}
}
Below is the implementation of Nested if statements:
// Driver Class
public class AgeWeightExample {
// main function
public static void main(String[] args) {
int age = 25;
double weight = 65.5;
Output
You are eligible to donate blood.
Note: The first print statement is in a block of “if” so the second
statement is not in the block of “if”. The third print statement is
in else but that else doesn’t have any corresponding “if”. That
means an “else” statement cannot exist without an “if” statement.
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}
You could also display the name of the month with if-then-
else statements:
int month = 8;
if (month == 1) {
System.out.println("January");
} else if (month == 2) {
System.out.println("February");
}
... // and so on
int month = 8;
switch (month) {
case 1: futureMonths.add("January");
case 2: futureMonths.add("February");
case 3: futureMonths.add("March");
case 4: futureMonths.add("April");
case 5: futureMonths.add("May");
case 6: futureMonths.add("June");
case 7: futureMonths.add("July");
case 8: futureMonths.add("August");
case 9: futureMonths.add("September");
case 10: futureMonths.add("October");
case 11: futureMonths.add("November");
case 12: futureMonths.add("December");
break;
default: break;
}
if (futureMonths.isEmpty()) {
System.out.println("Invalid month number");
} else {
for (String monthName : futureMonths) {
System.out.println(monthName);
}
}
}
}
August
September
October
November
December
class SwitchDemo2 {
public static void main(String[] args) {
int month = 2;
int year = 2000;
int numDays = 0;
switch (month) {
case 1: case 3: case 5:
case 7: case 8: case 10:
case 12:
numDays = 31;
break;
case 4: case 6:
case 9: case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = "
+ numDays);
}
}
This is the output from the code:
Number of Days = 29
int monthNumber = 0;
if (month == null) {
return monthNumber;
}
switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
case "february":
monthNumber = 2;
break;
case "march":
monthNumber = 3;
break;
case "april":
monthNumber = 4;
break;
case "may":
monthNumber = 5;
break;
case "june":
monthNumber = 6;
break;
case "july":
monthNumber = 7;
break;
case "august":
monthNumber = 8;
break;
case "september":
monthNumber = 9;
break;
case "october":
monthNumber = 10;
break;
case "november":
monthNumber = 11;
break;
case "december":
monthNumber = 12;
break;
default:
monthNumber = 0;
break;
}
return monthNumber;
}
int returnedMonthNumber =
StringSwitchDemo.getMonthNumber(month);
if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
}
}
}
OUTPUT :
I am 11
DETERMINE IF A STUDENT IS PASS OR FAIL
import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int percentage = ((a+b+c)/300) * 100;
if(a>33 && b>33 && c>33 && percentage > 40){
System.out.println("Pass");
}
else{
System.out.println("Fail");
}
}
}
import java.util.Scanner;
class Income
{
public static void main(String args[])
{
double tax=0,it;
Scanner sc=new Scanner(System.in);
System.out.println("Enter income ");
it=sc.nextDouble();
if(it<=200000)
tax=0;
else if(it<=300000)
tax=0.1*(it-200000);
else if(it<=500000)
tax=(0.2*(it-300000))+(0.1*100000);
else if(it<=1000000)
tax=(0.3*(it-500000))+(0.2*200000)+(0.1*100000);
else
tax=(0.4*(it-
1000000))+(0.3*500000)+(0.2*200000)+(0.1*100000);
System.out.println("Income tax amount is "+tax);
}
}
import java.util.Scanner;
public class Exercise5 {
import java.util.*;
public class RockPaperScissor {
while(true) {
//input
String userMove;
if(userMove.equals(computerMove)) {
System.out.println("Its a tie!");
}
else if(userMove.equals("Rock")) {
if(computerMove.equals("Paper"))
{
System.out.println("Computer won!");
System.out.println("Better
luck next time!");
}
else
if(computerMove.equals("Scissors")) {
System.out.println("You
won!");
System.out.println("Congratulations!");
}
}
else if(userMove.equals("Paper")) {
if(computerMove.equals("Rock"))
{
System.out.println("You
won!");
System.out.println("Congratulations!");
}
else
if(computerMove.equals("Scissors")) {
System.out.println("Computer won!");
System.out.println("Better
luck next time!");
}
}
else if(userMove.equals("Scissors")) {
if(computerMove.equals("Paper"))
{
System.out.println("You
won!");
System.out.println("Congratulations!");
}
else
if(computerMove.equals("Rock")) {
System.out.println("Computer won!");
System.out.println("Better
luck next time!");
}
}
System.out.println();
String playAgain;
System.out.println("Do you want to play
again? ");
if(playAgain.equals("yes") ||
playAgain.equals("Yes") || playAgain.equals("no") ||
playAgain.equals("No")) {
System.out.println();
System.out.println("*****************************
************************************************");
System.out.println();
break;
}
System.out.println();
System.out.println("Invalid Input");
System.out.println();
}
if(playAgain.equals("no") ||
playAgain.equals("No")) {
break;
}
}
}}
LOOPS IN JAVA
1. For Loops
2. While Loops
3. Do - While Loops
FOR LOOPS
Loops in Java come into use when we need to repeatedly
execute a block of statements. Java for loop provides a concise
way of writing the loop structure. The for statement consumes
the initialization, condition, and increment/decrement in one line
thereby providing a shorter, easy-to-debug structure of looping.
Let us understand Java for loop with Examples.
Syntax:
Initialization Expression
Test Expression
Update Expression
1. Initialization Expression
In this expression, we have to initialize the loop counter to some
value.
Example:
int i=1;
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.
Example:
i <= 10
3. Update Expression:
After executing the loop body, this expression
increments/decrements the loop variable by some value.
Example:
i++;
class GFG {
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}
Output
1
2
3
4
5
6
7
8
9
10
Dry-Running Example 1
The program will execute in the following manner.
Program starts.
i is initialized with value 1.
Condition is checked. 1 <= 5 yields true.
“Hello World” gets printed 1st time.
Updation is done. Now i = 2.
Condition is checked. 2 <= 5 yields true.
“Hello World” gets printed 2nd time.
Updation is done. Now i = 3.
Condition is checked. 3 <= 5 yields true.
“Hello World” gets printed 3rd time
Updation is done. Now i = 4.
Condition is checked. 4 <= 5 yields true.
“Hello World” gets printed 4th time
Updation is done. Now i = 5.
Condition is checked. 5 <= 5 yields true.
“Hello World” gets printed 5th time
Updation is done. Now i = 6.
Condition is checked. 6 <= 5 yields false.
Flow goes outside the loop. Program terminates.
Example 3: (The Program prints the sum of x ranging from 1 to
20)
Java
Java
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Printing a 1 to 5 (5 times)
// first loop
for (int i = 1; i <= 5; i++) {
// second loop
for (int j = 1; j <= 5; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output
12345
12345
12345
12345
12345
Syntax:
Java
// Main Function
public static void main(String args[])
{
// String array
String array[] = { "Ron", "Harry", "Hermoine" };
Example:
Java
// Java infinite loop
class GFG {
public static void main(String args[])
{
for (int i = 1; i >= 1; i++) {
System.out.println("Infinite Loop " + i);
}
}
}
Output
Infinite Loop 1
Infinite Loop 2
...
Syntax:
for(;;){
//code to be executed
}
Example:
Java
public class GFG {
public static void main(String[] args)
{
for (;;) {
System.out.println("infinitive loop");
}
}
}
Output
infinite loop
infinite loop
....
WHILE LOOP
Syntax:
while (test_expression)
{
// statements
update_expression;
}
Note: If we do not provide the curly braces ‘{‘ and ‘}’ after
while( condition ) then by default while statement will consider
the immediate one statement to be inside its block.
while (test_expression)
// single statement in while only
Example:
i <= 10
2. Update Expression: After executing the loop body, this
expression increments/decrements the loop variable by some
value.
Example:
i++;
How Does a While loop execute?
Control falls into the while loop.
The flow jumps to Condition
Condition is tested.
If Condition yields true, the flow goes into the Body.
If Condition yields false, the flow goes outside the loop
The statements inside the body of the loop get executed.
Updation takes place.
Control flows back to Step 2.
The while loop has ended and the flow has gone outside.
Flowchart For while loop (Control Flow):
Flow chart while loop (for Control Flow
class whileLoopDemo {
public static void main(String args[])
{
// initialization expression
int i = 1;
// test expression
while (i < 6) {
System.out.println("Hello World");
// update expression
i++;
}
}
}
Output
Hello World
Hello World
Hello World
Hello World
Hello World
1. Program starts.
2. i is initialized with value 1.
3. Condition is checked. 1 < 6 yields true.
3.a) "Hello World" gets printed 1st time.
3.b) Updation is done. Now i = 2.
4. Condition is checked. 2 < 6 yields true.
4.a) "Hello World" gets printed 2nd time.
4.b) Updation is done. Now i = 3.
5. Condition is checked. 3 < 6 yields true.
5.a) "Hello World" gets printed 3rd time
5.b) Updation is done. Now i = 4.
6. Condition is checked. 4 < 6 yields true.
6.a) "Hello World" gets printed 4th time
6.b) Updation is done. Now i = 5.
7. Condition is checked. 5 < 6 yields true.
7.a) "Hello World" gets printed 5th time
7.b) Updation is done. Now i = 6.
8. Condition is checked. 6 < 6 yields false.
9. Flow goes outside the loop. Program terminates.
class whileLoopDemo {
public static void main(String args[])
{
int x = 1, sum = 0;
DO - WHILE LOOPS
Syntax:
do
{
// Loop Body
Update_expression
}
// Condition check
while (test_expression);
Note: The test_expression for the do-while loop must return a
boolean value , else we would get compile-time error.
Application of do-while : Its example application is showing
some kind of menu to the users.
For example:
Illustration:
// Class
class GFG {
do {
i <= 10
B. Update Expression: After executing the loop body, this
expression increments/decrements the loop variable by some
value. For example:
i++;
Execution of do-While loop
Control falls into the do-while loop.
The statements inside the body of the loop get executed.
Updation takes place.
The flow jumps to Condition
Condition is tested.
If Condition yields true, go to Step 6.
If Condition yields false, the flow goes outside the loop
The flow goes back to Step 2.
Flowchart do-while loop:
Implementation:
// Class
class GFG {
// Do-while loop
do {
// Update expression
i++;
}
// Test expression
while (i < 6);
}
}
Output:
Hello World
Hello World
Hello World
Hello World
Hello World
Output explanation:
Program starts.
i is initialized with value 1.
Execution enters the loop
“Hello World” gets printed 1st time.
Updation is done. Now i = 2.
Condition is checked. 2 < 6 yields true.
Execution enters the loop.
“Hello World” gets printed 2nd time.
Updation is done. Now i = 3.
Condition is checked. 3 < 6 yields true.
Execution enters the loop
“Hello World” gets printed 3rd time
Updation is done. Now i = 4.
Condition is checked. 4 < 6 yields true.
Execution enters the loop
“Hello World” gets printed 4th time
Updation is done. Now i = 5.
Condition is checked. 5 < 6 yields true.
Execution enters the loop
“Hello World” gets printed 5th time
Updation is done. Now i = 6.
Condition is checked. 6 < 6 yields false.
The flow goes outside the loop.
Example 2
// Java Program to Illustrate Do-while Loop
// Class
class GFG {
// Do-while loop
do {
// Summing up
System.out.println("Summation: " + sum);
}
}
Output:
Summation: 176
import java.io.*;
class GFG {
public static void main (String[] args) {
int i=1;
do
// only single statement in do block
System.out.println("Hello GFG!");
// this condition is false so only do block will execute
while(i>=3);
}
}
Output
Hello GFG!
The break and continue statements are the jump statements that
are used to skip some statements inside the loop or terminate the
loop immediately without checking the test expression. These
statements can be used inside any loops such as for, while, do-
while loop.
break;
In Java, a break statement is majorly used for:
To exit a loop.
Used as a “civilized” form of goto.
Terminate a sequence in a switch statement.
Using break to exit a loop
Example:
Java
// Java program to demonstrate using
// break to exit a loop
class GFG {
public static void main(String[] args)
{
// Initially loop is set to run from 0-9
for (int i = 0; i < 10; i++) {
// Terminate the loop when i is 5
if (i == 5)
break;
System.out.println("i: " + i);
}
System.out.println("Out of Loop");
}
}
Output
i: 0
i: 1
i: 2
i: 3
i: 4
Out of Loop
Using break as a Form of Goto
Syntax:
label:
{
statement1;
statement2;
statement3;
.
.
}
Now, the break statements can be used to jump out of the target
block. We cannot break to any label which is not defined for an
enclosing block.
Syntax:
break label;
Example:
Java
// Java program to demonstrates using break with goto
class GFG {
public static void main(String args[])
{
// First label
first:
for (int i = 0; i < 3; i++) {
// Second label
second:
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Example:
Java
// Java program to demonstrate using break to terminate a
// sequence in a switch statement.
class GFG {
public static void main(String args[])
{
int i = 2;
switch (i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
default:
System.out.println("Invalid number");
}
}
}
Output
i is two.
Continue:
Syntax:
continue;
Using continue to continue a loop
Example:
Java
// Java program to demonstrates the continue
// statement to continue a loop
class GFG {
public static void main(String args[])
{
for (int i = 0; i < 10; i++) {
// If the number is 2
// skip and continue
if (i == 2)
continue;
Example:
Java
// Java program to demonstrates labeled continue statement
class GFG {
public static void main(String args[])
{
// First label
first:
for (int i = 0; i < 3; i++) {
// Second label
second:
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {
We can use a break with the switch We can not use a continue with the
statement. switch statement.
The break statement terminates the The continue statement brings the next
whole loop early. iteration early.
PATTERN PRINTING
// required sum
return sum;
}
// driver function
public static void main(String argc[])
{
int n = 20;
System.out.println("Sum of first " + n +
" Even numbers is: " +
evenSum(n));
}
import java.io.*;
class Easy
// array declaration
Output
10 50 60 80 90
The above syntax is equivalent to:
Output
For-each loops are not appropriate when you want to modify the
array:
import java.io.*;
import java.util.*;
class GFG {
public static void main (String[] args) {
List<Integer> list = new ArrayList<>();
long startTime;
long endTime;
for (int i = 0; i < 1000000; i++) {
list.add(i);
}
// Type 1
startTime = Calendar.getInstance().getTimeInMillis();
for (int i : list) {
int a = i;
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("For each loop :: " + (endTime -
startTime) + " ms");
// Type 2
startTime = Calendar.getInstance().getTimeInMillis();
for (int j = 0; j < list.size(); j++) {
int a = list.get(j);
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("Using collection.size() :: " + (endTime
- startTime) + " ms");
// Type 3
startTime = Calendar.getInstance().getTimeInMillis();
int size = list.size();
for (int j = 0; j < size; j++) {
int a = list.get(j);
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("By calculating collection.size() first :: "
+ (endTime - startTime) + " ms");
// Type 4
startTime = Calendar.getInstance().getTimeInMillis();
for(int j = list.size()-1; j >= 0; j--) {
int a = list.get(j);
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("Using [int j = list.size(); j > size ; j--] ::
" + (endTime - startTime) + " ms");
}
}
ARRAYS IN JAVA
Arrays in Java
In Java, all arrays are dynamically allocated. (discussed below)
Arrays may be stored in contiguous memory [consecutive
memory locations].
Since arrays are objects in Java, we can find their length using
the object property length. This is different from C/C++, where
we find length using size of.
A Java array variable can also be declared like other variables
with [] after the data type.
The variables in the array are ordered, and each has an index
beginning with 0.
Java array can also be used as a static field, a local variable, or a
method parameter.
An array can contain primitives (int, char, etc.) and object (or
non-primitive) references of a class, depending on the definition
of the array. In the case of primitive data types, the actual values
might be stored in contiguous memory locations (JVM does not
guarantee this behavior). In the case of class objects, the actual
objects are stored in a heap segment. To learn more about Java
Array, go through Java programming course here.
Java Arrays
Note: This storage of arrays helps us randomly access the
elements of an array [Support Random Access].
-- type var-name[];
-- type[] var-name;
An array declaration has two components: the type and the name.
type declares the element type of the array. The element type
determines the data type of each element that comprises the
array. Like an array of integers, we can also create an array of
other primitive data types like char, float, double, etc., or user-
defined data types (objects of a class). Thus, the element type
for the array determines what type of data the array will hold.
Example:
Example:
//declaring array
int intArray[];
// allocating memory to array
intArray = new int[20];
// combining both statements in one
int[] intArray = new int[20];
Note: The elements in the array allocated by new will
automatically be initialized to zero (for numeric types), false
(for boolean), or null (for reference types). Do refer to default
array values in Java.
class GFG {
public static void main(String[] args)
{
// declares an Array of integers.
int[] arr;
// so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Output
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
Complexity of the above method:
Time Complexity: O(n)
Auxiliary Space: O(1)
You can also access java arrays using for each loops.
Arrays-in-Java
import java.io.*;
class GFG {
public static void main (String[] args) {
System.out.println("Array Size:"+arr.length);
}
}
Output
Array Size:4
The Student Array contains five memory spaces each of the size
of Student class in which the address of five Student objects can
be stored. The Student objects have to be instantiated using the
constructor of the Student class, and their references should be
assigned to the array elements in the following way.
Example 2:
Below is the implementation of the above mentioned topic:
class Student {
public int roll_no;
public String name;
Student(int roll_no, String name)
{
this.roll_no = roll_no;
this.name = name;
}
}
// so on...
arr[2] = new Student(3, "shikar");
arr[3] = new Student(4, "dharmesh");
arr[4] = new Student(5, "mohit");
Output
Element at 0 : 1 aman
Element at 1 : 2 vaibhav
Element at 2 : 3 shikar
Element at 3 : 4 dharmesh
Element at 4 : 5 mohit
Complexity of the above method:
Time Complexity: O(n)
Auxiliary Space : O(1)
Example 3
An array of objects is also created like :
class Student
{
Output
Dharma
sanvi
Rupa
Ajay
What happens if we try to access elements outside the array size?
JVM throws ArrayIndexOutOfBoundsException to indicate that
the array has been accessed with an illegal index. The index is
either negative or greater than or equal to the size of an array.
System.out.println(
"Trying to access element outside the size of array");
System.out.println(arr[5]);
}
}
Output
Output
10
20
Complexity of the above method:
Time Complexity: O(n),here n is size of array.
Auxiliary Space: O(1), since no extra space required.
// Driver class
class GFG {
public static void main(String[] args)
{
// Syntax
int[][] arr = new int[3][3];
// 3 row and 3 column
// Number of Rows
System.out.println("Number of Rows:"+
arr.length);
// Number of Columns
System.out.println("Number of Columns:"+
arr[0].length);
}
}
Output
Number of Rows:3
Number of Columns:3
MultiDimensional-Array
// Driver Class
public class multiDimensional {
// main function
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][]
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };
// printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}
Output
279
361
742
Passing Arrays to Methods
Like variables, we can also pass arrays to methods. For example,
the below program passes the array to method sum to calculate
the sum of the array’s values.
Output
sum of array values : 15
Complexity of the above method:
Time Complexity: O(n)
Auxiliary Space : O(1)
class Test {
// Driver method
public static void main(String args[])
{
int arr[] = m1();
Output
123
Complexity of the above method:
Time Complexity: O(n)
Auxiliary Space : O(1)
// array of Strings
String[] strArray = new String[3];
System.out.println(intArray.getClass());
System.out.println(
intArray.getClass().getSuperclass());
System.out.println(byteArray.getClass());
System.out.println(shortsArray.getClass());
System.out.println(strArray.getClass());
}
}
Output
class [I
class java.lang.Object
class [B
class [S
class [Ljava.lang.String;
Explanation of the above method:
The string “[I” is the run-time type signature for the class object
“array with component type int.”
The only direct superclass of an array type is java.lang.Object.
The string “[B” is the run-time type signature for the class
object “array with component type byte.”
The string “[S” is the run-time type signature for the class object
“array with component type short.”
The string “[L” is the run-time type signature for the class object
“array with component type of a Class.” The Class name is then
followed.
Java Array Members
Now, as you know that arrays are objects of a class, and a direct
superclass of arrays is a class Object. The members of an array
type are all of the following:
class Test {
public static void main(String args[])
{
int intArray[] = { 1, 2, 3 };
int cloneArray[] = intArray.clone();
Output
false
123
Explanation of the above Program:
In this example, intArray and cloneArray are not the same
object (intArray == cloneArray is false), but they share the same
contents because primitive values are deeply copied.
For arrays containing objects, the references are copied, so the
objects themselves are not duplicated.
Clone-of-Array
class Test {
public static void main(String args[])
{
int intArray[][] = { { 1, 2, 3 }, { 4, 5 } };
int cloneArray[][] = intArray.clone();
Output
false
true
True
PRACTICE SET ON ARRAYS
import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int arr[][] = new int[3][3] ;
int arr1[][] = new int[3][3] ;
int sum[][] = new int [3][3];
//INPUT OF ARRAY 1
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
arr[i][j] = sc.nextInt();
}
}
//INPUT OF ARRAY 2
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
arr1[i][j] = sc.nextInt();
}
}
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
sum[i][j] = arr[i][j] + arr1[i][j] ;
}
}
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(sum[i][j] + " ");
}
System.out.println();
}
}
}
REVERSE AN ARRAY
import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int arr[] = {3,4,5};
for (int i =0;i<arr.length/2 ; i++) {
int temp = arr[i] ;
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
}
// Driver Class
class Test
{
// array declared
static int arr[] = {10, 324, 45, 90, 9808};
return max;
}
// Driver method
public static void main(String[] args)
{
System.out.println("Largest in given array is " + largest());
}
}
import java.util.*;
class Array {
public static void main(String[] args) {
int a[]={1,423,6,46,34,23,13,53,4};
SORTING AN ARRAY
import java.util.Arrays;
class GFG {
public static void main(String args[])
{
int[] arr = { 5, -2, 23, 7, 87, -42, 509 };
System.out.println("The original array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
Arrays.sort(arr);
System.out.println("\nThe sorted array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}