0% found this document useful (0 votes)
1 views45 pages

Java Module1

Java is a widely-used programming language created in 1995, owned by Oracle, and runs on over 3 billion devices. It is utilized for various applications, including mobile, desktop, web, and games, and requires the Java Development Kit (JDK) for program execution. The document also covers the structure of a simple Java program, error handling, data types, literals, variables, and operators in Java.

Uploaded by

Prerna Janavekar
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)
1 views45 pages

Java Module1

Java is a widely-used programming language created in 1995, owned by Oracle, and runs on over 3 billion devices. It is utilized for various applications, including mobile, desktop, web, and games, and requires the Java Development Kit (JDK) for program execution. The document also covers the structure of a simple Java program, error handling, data types, literals, variables, and operators in Java.

Uploaded by

Prerna Janavekar
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
You are on page 1/ 45

What is Java?

Java is a popular programming language, created in 1995.


It is owned by Oracle, and more than 3 billion devices run
Java.
It is used for:
 Mobile applications (specially Android apps)
 Desktop applications
 Web applications
 Web servers and application servers
 Games
 Database connection

To create a simple Java program, you need to create a class that contains
the main method. Let's understand the requirement first.

The requirement for Java Hello World Example


For executing any Java program, the following software or application
must be properly installed.

o Install the JDK if you don't have installed it, download the JDK and install it.
o Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-
path-in-java
o Create the Java program
o Compile and run the Java program

Creating Hello World Example


Let's create the hello java program:

1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }
Save the above file as Simple.java

To
compile: javac Simple.java

To
java Simple
execute:

Output:

Hello Java

Compilation Flow:

When we compile Java program using javac tool, the Java compiler
converts the source code into byte code.

Parameters used in First Java Program


Let's see what is the meaning of class, public, static, void,
main, String[], System.out.println().

o class keyword is used to declare a class in Java.


o public keyword is an access modifier that represents visibility. It
means it is visible to all.
o static is a keyword. If we declare any method as static, it is known
as the static method. The core advantage of the static method is
that there is no need to create an object to invoke the static
method. The main() method is executed by the JVM, so it doesn't
require creating an object to invoke the main() method. So, it saves
memory.
o void is the return type of the method. It means it doesn't return any
value.
o main represents the starting point of the program.
o String[] args or String args[] is used for command line argument.
We will discuss it in coming section.
o System.out.println() is used to print statement. Here, System is a
class, out is an object of the PrintStream class, println() is a method
of the PrintStream class. We will discuss the internal working
of System.out.println() statement in the coming section.

Handling Syntax Errors

Error is an illegal operation performed by the user


which results in the abnormal working of the program.
Programming errors often remain undetected until the
program is compiled or executed. Some of the errors
inhibit the program from getting compiled or executed.
Thus errors should be removed before compiling and
executing.
The most common errors can be broadly classified as
follows:
1. Run Time Error:
Run Time errors occur or we can say, are detected
during the execution of the program. Sometimes these
are discovered when the user enters an invalid data or
data which is not relevant. Runtime errors occur when
a program does not contain any syntax errors
For example: if the user inputs a data of string format
when the computer is expecting an integer, there will
be a runtime error.
Example : Runtime Error caused by dividing by zero
2. Compile Time Error:
Compile Time Errors are those errors which prevent
the code from running because of an incorrect syntax
such as a missing semicolon at the end of a statement
or a missing bracket, class not found, etc.
Example : Misspelled variable name or method
names
Logical Error: A logic error is when your program
compiles and executes, but does the wrong thing or
returns an incorrect result or no output when it should
be returning an output. These errors are detected
neither by the compiler nor by JVM
Example: Accidentally using an incorrect operator on
the variables to perform an operation
3. Logical Error: A logic error is when your program compiles
and executes, but does the wrong thing or returns an incorrect
result or no output when it should be returning an output.
These errors are detected neither by the compiler nor by JVM

Syntax Error:
Syntax and Logical errors are faced by Programmers.

Data Types in Java


Data types specify the different sizes and values that can be stored in the
variable. There are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char,
byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.

There are 8 types of primitive data types:

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type
Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Boolean Data Type


The Boolean data type is used to store only two possible values: true and
false. This data type is used for simple flags that track true/false
conditions.

The Boolean data type specifies one bit of information, but its "size" can't
be defined precisely.

Example:

1. Boolean one = false

Byte Data Type


The byte data type is an example of primitive data type. It isan 8-bit
signed two's complement integer. Its value-range lies between -128 to
127 (inclusive). Its minimum value is -128 and maximum value is 127. Its
default value is 0.

The byte data type is used to save memory in large arrays where the
memory savings is most required. It saves space because a byte is 4
times smaller than an integer. It can also be used in place of "int" data
type.

Example:

1. byte a = 10, byte b = -20

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-
range lies between -32,768 to 32,767 (inclusive). Its minimum value is -
32,768 and maximum value is 32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data
type. A short data type is 2 times smaller than an integer.

Example:

1. short s = 10000, short r = -5000

Int Data Type


The int data type is a 32-bit signed two's complement integer. Its value-
range lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1)
(inclusive). Its minimum value is - 2,147,483,648and maximum value is
2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral
values unless if there is no problem about memory.

Example:

1. int a = 100000, int b = -200000

Long Data Type


The long data type is a 64-bit two's complement integer. Its value-range
lies between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is -
9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is
used when you need a range of values more than those provided by int.

Example:

1. long a = 100000L, long b = -200000L

Float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating point.Its
value range is unlimited. It is recommended to use a float (instead of
double) if you need to save memory in large arrays of floating point
numbers. The float data type should never be used for precise values,
such as currency. Its default value is 0.0F.

Example:

1. float f1 = 234.5f

Literals in Java
In Java, literal is a notation that represents a fixed value in the source
code. In lexical analysis, literals of a given type are generally known
as tokens. In this section, we will discuss the term literals in Java.

Literals
In Java, literals are the constant values that appear directly in the
program. It can be assigned directly to a variable. Java has various types
of literals. The following figure represents a literal.
Types of Literals in Java
There are the majorly four types of literals in Java:

1. Integer Literal
2. Character Literal
3. Boolean Literal
4. String Literal

Integer Literals
Integer literals are sequences of digits. There are three types of integer
literals:

o Decimal Integer: These are the set of numbers that consist of digits from
0 to 9. It may have a positive (+) or negative (-) Note that between
numbers commas and non-digit characters are not permitted. For
example, 5678, +657, -89, etc.

1. int decVal = 26;


o Octal Integer: It is a combination of number have digits from 0 to 7 with
a leading 0. For example, 045, 026,
1. int octVal = 067;
o Hexa-Decimal: The sequence of digits preceded by 0x or 0X is
considered as hexadecimal integers. It may also include a character
from a to f or A to F that represents numbers from 10 to 15, respectively.
For example, 0xd, 0xf,

1. int hexVal = 0x1a;


o Binary Integer: Base 2, whose digits consists of the numbers 0 and 1
(you can create binary literals in Java SE 7 and later). Prefix 0b represents
the Binary system. For example, 0b11010.

1. int binVal = 0b11010;

Backslash Literals
Java supports some special backslash character literals known as
backslash literals. They are used in formatted output. For example:

\n: It is used for a new line

\t: It is used for horizontal tab

Character Literals
A character literal is expressed as a character or an escape sequence,
enclosed in a single quote ('') mark. It is always a type of char. For
example, 'a', '%', '\u000d', etc.

String Literals
String literal is a sequence of characters that is enclosed
between double quotes ("") marks. It may be alphabet, numbers, special
characters, blank space, etc. For example, "Jack", "12345", "\n", etc.

Example:

public class Test {

public static void main(String[] args)


{
// decimal-form literal
int a = 101;
// octal-form literal
int b = 0100;
// Hexa-decimal form literal
int c = 0xFace;
// Binary literal
int d = 0b1111;

System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}

Output
101
64
64206
15

A Closer Look at Variables

public class MyFirstJavaProgram {


/* This is my first java program. *
This will print 'Hello World' as the output */
public static void main(String []args) {
System.out.println("Hello World"); // prints Hello World
}
}

Let's look at how to save the file, compile, and run the program. Please
follow the subsequent steps –
Open notepad and add the code as above.

Save the file as: MyFirstJavaProgram.java.


Open a command prompt window and go to the directory where
you saved the class. Assume it's C:\.
Type 'javac MyFirstJavaProgram.java' and press enter to compile
your code. If there are no errors in your code, the command
prompt will take you to the next line (Assumption : The path
variable is set).
Now, type ' java MyFirstJavaProgram ' to run your program.
You will be able to see ' Hello World ' printed on the window.

Output
C:\> javac MyFirstJavaProgram.java
C:\> java MyFirstJavaProgram
Hello World

Scope of Variables in Java


In programming, scope of variable defines how a specific variable is
accessible within the program or across classes. In this section, we will
discuss the scope of variables in Java.

Scope of a Variable
In programming, a variable can be declared and defined inside a class,
method, or block. It defines the scope of the variable i.e. the visibility or
accessibility of a variable. Variable declared inside a block or method are
not visible to outside. If we try to do so, we will get a compilation error.
Note that the scope of a variable can be nested.

o We can declare variables anywhere in the program but it has limited


scope.
o A variable can be a parameter of a method or constructor.
o A variable can be defined and declared inside the body of a method and
constructor.
o It can also be defined inside blocks and loops.
o Variable declared inside main() function cannot be accessed outside the
main() function
Demo.java

1. public class Demo


2. {
3. //instance variable
4. String name = "Andrew";
5. //class and static variable
6. static double height= 5.9;
7. public static void main(String args[])
8. {
9. //local variable
10.int marks = 72;
11. }
12.}

In Java, there are three types of variables based on their scope:

1. Member Variables (Class Level Scope)


2. Local Variables (Method Level Scope)

Member Variables (Class Level Scope)


These are the variables that are declared inside the class but outside any
function have class-level scope. We can access these variables anywhere
inside the class. Note that the access specifier of a member variable does
not affect the scope within the class. Java allows us to access member
variables outside the class with the following rules:
Access Modifier Package Subclass Word

public Yes Yes Yes

protected Yes Yes No

private No No No

default Yes No No

Syntax:

1. public class DemoClass


2. {
3. //variables declared inside the class have class level scope
4. int age;
5. private String name;
6. void displayName()
7. {
8. //statements
9. }
10.int dispalyAge()
11. {
12.//statements
13. }
14.char c;
15. }

Let's see an example.

There is another variable named an instance variable. These are


declared inside a class but outside any method, constructor, or block.
When an instance variable is declared using the keyword static is known
as a static variable. Their scope is class level but visible to the method,
constructor, or block that is defined inside the class.
Operators in Java
Operator in Java is a symbol that is used to perform operations. For
example: +, -, *, / etc.

There are many types of operators in Java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

Java Operator Precedence

Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative * / %

additive + -

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^
bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Java Unary Operator


The Java unary operators require only one operand. Unary operators are
used to perform various operations i.e.:

o incrementing/decrementing a value by one


o negating an expression
o inverting the value of a boolean

Java Unary Operator Example: ++ and --


1. public class OperatorExample{
2. public static void main(String args[]){
3. int x=10;
4. System.out.println(x++);//10 (11)
5. System.out.println(++x);//12
6. System.out.println(x--);//12 (11)
7. System.out.println(--x);//10
8. }}

Output:

10
12
12
10

Java Unary Operator Example 2: ++ and --


1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=10;
5. System.out.println(a++ + ++a);//10+12=22
6. System.out.println(b++ + b++);//10+11=21
7.
8. }}

Output:

22
21

Java Arithmetic Operators


Java arithmetic operators are used to perform addition, subtraction,
multiplication, and division. They act as basic mathematical operations.

Java Arithmetic Operator Example


1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. System.out.println(a+b);//15
6. System.out.println(a-b);//5
7. System.out.println(a*b);//50
8. System.out.println(a/b);//2
9. System.out.println(a%b);//0
10.}}

Output:

15
5
50
2
0

Logical operators
Logical operators are used to performing 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.
1. AND Operator ( && ) – if( a && b ) [if true execute else don’t]
2. OR Operator ( || ) – if( a || b) [if one of them is true execute else
don’t]
3. NOT Operator ( ! ) – !(a<b) [returns false if a is smaller than b]

Logical ‘AND’ Operator (&&)


This operator returns true when both the conditions under consideration are
satisfied or are true. If even one of the two yields false, the operator results
false. In Simple terms, cond1 && cond2 returns true when both cond1
and cond2 are true (i.e. non-zero).

Example:

public class Main {

public static void main(String[] args) {

int x = 5;

System.out.println(x > 3 && x < 10);

// returns true because 5 is greater than 3 AND 5 is less than 10

}
}

Output:
true

// Java code to illustrate


// logical AND operator

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

// using logical AND to verify


// two constraints
if ((a < b) && (b == c)) {
d = a + b + c;
System.out.println("The sum is: " + d);
}
else
System.out.println("False conditions");
}
}

Output
Var1 = 10
Var2 = 20
Var3 = 20
The sum is: 50

Relational operator

/ Java Program to Illustrate equal to Operator

// Importing I/O classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Initializing variables
int var1 = 5, var2 = 10, var3 = 5;

// Displaying var1, var2, var3


System.out.println("Var1 = " + var1);
System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and


// printing corresponding boolean value
System.out.println("var1 == var2: "
+ (var1 == var2));

// Comparing var1 and var3 and


// printing corresponding boolean value
System.out.println("var1 == var3: "
+ (var1 == var3));
}
}

Output
Var1 = 5
Var2 = 10
Var3 = 5
var1 == var2: false
var1 == var3: true

Shorthand Assignment Operators


In addition to the basic assignment operator, Java also defines 12
shorthand assignment operators that combine assignment with the 5
arithmetic operators (+=, -=, *=, /=, %=) and the 6 bitwise and shift
operators (&=, |=, ^=, <<=, >>=, >>>=). For example, the += operator reads the
value of the left variable, adds the value of the right operand to it, stores
the sum back into the left variable as a side effect, and returns the sum
as the value of the expression. Thus, the expression x += 2 is almost the
same x = x + 2.
The difference between these two expressions is that when we use
the += operator, the left operand is evaluated only once. This makes a
difference when that operand has a side effect. Consider the following
two expressions a[i++] += 2; and a[i++] = a[i++] + 2;, which are not
equivalent:
We use Assignment operators to assign values to variables.

int x = 10;
In the above statement, we use the assignment operator ( = ) to assign
the value 10 to x.

Shorthand Operators
Statements like this:

a = a + 10;
are used a lot in programs. Java provides shorthand operators to
combine the arithmetic and assignment operator into a single operator
and write the above statement like this:

a += 10;
Both these statements are equivalent. They add 10 to a and assign the
value back to a. The second statement uses the shorthand operator and
is a little simple and saves a bit of typing.

There are shorthand operators for all arithmetic binary operators. The
table below lists some of the shorthand operators in Java:

Operator Example Same As

+= x += 5 x=x+5

-= x -= 5 x=x-5

*= x *= 5 x=x*5

/= x /= 5 x=x/5

%= x %= 5 x=x%5

Let’s look at a Blue program to see some examples of Shorthand


operator’s usage:

public class ShorthandOp


{
public void demoShorthandOp() {

int x = 10, y = 20, z = 30;

x += 20; //Same as x = x + 20
y *= 3; //Same as y = y * 3
z -= 15; //Same as z = z - 15

System.out.println("x = " + x);


System.out.println("y = " + y);
System.out.println("z = " + z);
}
}
Here is the output of the program:

X=30
Y=60
Z=15

Type conversion in Assignments


Java provides various data types just likely any other dynamic languages
such as boolean, char, int, unsigned int, signed int, float, double, long, etc in
total providing 7 types where every datatype acquires different space while
storing in memory. When you assign a value of one data type to another, the
two types might not be compatible with each other. If the data types are
compatible, then Java will perform the conversion automatically known as
Automatic Type Conversion, and if not then they need to be cast or
converted explicitly. For example, assigning an int value to a long variable.

Datatype Bits Acquired In Memory

boolean 1

byte 8 (1 byte)

char 16 (2 bytes)

short 16(2 bytes)

int 32 (4 bytes)

long 64 (8 bytes)

float 32 (4 bytes)

double 64 (8 bytes)

Widening or Automatic Type Conversion


Widening conversion takes place when two data types are automatically
converted. This happens when:
The two data types are compatible.

When we assign a value of a smaller data type to a bigger data

type.
For Example, in java, the numeric data types are compatible with each other
but no automatic conversion is supported from numeric type to char or
boolean. Also, char and boolean are not compatible with each other.

Example:
 Java

// Java Program to Illustrate Automatic Type Conversion

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
int i = 100;

// Automatic type conversion


// Integer to long type
long l = i;

// Automatic type conversion


// long to float type
float f = l;

// Print and display commands


System.out.println("Int value " + i);
System.out.println("Long value " + l);
System.out.println("Float value " + f);
}
}

Output
Int value 100
Long value 100
Float value 100.0
Java Type Casting
Type casting is when you assign a value of one primitive data type to another
type.

In Java, there are two types of casting:

 Widening Casting (automatically) - converting a smaller type to a


larger type size
byte -> short -> char -> int -> long -> float -> double

 Narrowing Casting (manually) - converting a larger type to a smaller


size type
double -> float -> long -> int -> char -> short -> byte

Widening Casting
Widening casting is done automatically when passing a smaller size type to a
larger size type:

Example
public class Main {

public static void main(String[] args) {

int myInt = 9;

double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt); // Outputs 9

System.out.println(myDouble); // Outputs 9.0

output

9
9.0
Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses
in front of the value:

Example
public class Main {

public static void main(String[] args) {

double myDouble = 9.78d;

int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78

System.out.println(myInt); // Outputs 9

output

9.78
9

Operator Precedence
What is operator precedence?
The operator precedence represents how two expressions are bind
together. In an expression, it determines the grouping of operators with
operands and decides how an expression will evaluate.

While solving an expression two things must be kept in mind the first is
a precedence and the second is associativity.
Precedence
Precedence is the priority for grouping different types of operators with
their operands. It is meaningful only if an expression has more than one
operator with higher or lower precedence. The operators having higher
precedence are evaluated first. If we want to evaluate lower precedence
operators first, we must group operands by using parentheses and then
evaluate.

Associativity
We must follow associativity if an expression has more than two operators
of the same precedence. In such a case, an expression can be solved
either left-to-right or right-to-left, accordingly.

Java Operator Precedence Example


Let's understand the operator precedence through an example. Consider
the following expression and guess the answer.

1. 1 + 5 * 3

You might be thinking that the answer would be 18 but not so. Because
the multiplication (*) operator has higher precedence than the addition
(+) operator. Hence, the expression first evaluates 5*3 and then evaluates
the remaining expression i.e. 1+15. Therefore, the answer will be 16.

Let's see another example. Consider the following expression.

1. x + y * z / k
In the above expression, * and / operations are performed before +
because of precedence. y is multiplied by z before it is divided by k
because of associativity.

Example: Operator Precedence

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

int a = 10, b = 5, c = 1, result;


result = a-++c-++b;

System.out.println(result);
}
}

Output:

2
Expressions
An expression is a combination of operators, constants and variables. An expression
may consist of one or more operands, and zero or more operators to produce a value.

Types of Expressions:
Expressions may be of the following types:

 Constant expressions: Constant Expressions consists of only


constant values. A constant value is one that doesn’t change.
Examples:
 5, 10 + 5 / 6.0, 'x’
 Integral expressions: Integral Expressions are those which produce
integer results after implementing all the automatic and explicit type
conversions.
Examples:
x, x * y, x + int( 5.0)
where x and y are integer variables.
 Floating expressions: Float Expressions are which produce floating
point results after implementing all the automatic and explicit type
conversions.
Examples:
x + y, 10.75
where x and y are floating point variables.
 Relational expressions: Relational Expressions yield results of type bool
which takes a value true or false. When arithmetic expressions are used
on either side of a relational operator, they will be evaluated first and then
the results compared. Relational expressions are also known as Boolean
expressions.
Examples:
x <= y, x + y > 2

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

String band = "Beatles";

if (band == "Beatles") { // start of block


System.out.print("Hey ");
System.out.print("Jude!");
} // end of block
}
}
Run Code

Output:

Hey Jude!
More Data Types and Operators

Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous memory location.

Java array is an object which contains elements of a similar data type.


Additionally, The elements of an array are stored in a contiguous memory
location. It is a data structure where we store similar elements. We can store
only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the
0th index, 2nd element is stored on 1st index and so on.

Moreover, Java provides the feature of anonymous arrays which is not


available in C/C++.

Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort
the data efficiently.
o Random access: We can get any data located at an index position.

Types of Array in java


There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Single Dimensional Array in Java


Syntax to Declare an Array in Java
1. dataType[] arr; (or)
2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in Java

1. arrayRefVar=new datatype[size];

Example of Java Array


Let's see the simple example of java array, where we are going to declare,
instantiate, initialize and traverse an array.

1. //Java Program to illustrate how to declare, initialize


2. class Testarray{
3. public static void main(String args[]){
4. int a[]=new int[5];//declaration
5. a[0]=10;//initialization
6. a[1]=20;
7. a[2]=70;
8. a[3]=40;
9. a[4]=50;
10. //traversing array
11.for(int i=0;i<a.length;i++)//length is the property of array
12. System.out.println(a[i]);
13.}}

Output:

10
20
70
40
50

Alternative Array Declaration Syntax

For example, the following two declarations are equivalent:

int al[] = new int[3];


int[] a2 = new int[3];

The following declarations are also equivalent:


char twod1[][] = new char[3]
[4];
char[][] twod2 = new char[3][4];

This alternative declaration form offers convenience when declaring several


arrays at the same time:

int[] nums, nums2, nums3; // create three arrays

Assigning Array References


As with other objects, when you assign one array reference variable
to another, you are simply changing what object that variable refers
to. You are not causing a copy of the array to be made, nor are you
causing the contents of one array to be copied to the other. For
example, consider this program

The output from the program is shown here:

As the output shows, after the assignment of nums1 to nums2,


both array reference
Using the Length Member
array.length: length is a final variable applicable for arrays. With the help of
the length variable, we can obtain the size of the array.
string.length() : length() method is a final variable which is applicable for
string objects. The length() method returns the number of characters present
in the string.
Examples:
// length can be used for int[], double[], String[]
// to know the length of the arrays.

// length() can be used for String, StringBuilder, etc


// String class related Objects to know the length of the
String
3. To directly access a field member of an array we can
use .length; whereas .length() invokes a method to access a field member.
Example: // Java program to illustrate the
// concept of length

// and length()

public class Test {

public static void main(String[] args)

// Here array is the array name of int type

int[] array = new int[4];

System.out.println("The size of the array is "

+ array.length);

// Here str is a string object

String str = "GeeksforGeeks";

System.out.println("The size of the String is "

+ str.length());

Output
The size of the array is 4
The size of the String is 13

public class Test {


public static void main(String[] args)
{
// Here str is the array name of String type.
String[] str = { "GEEKS", "FOR", "GEEKS" };
System.out.println(str.length);
}
}

Output
3
Explanation: Here the str is an array of type string and that’s why str.length
is used to find its length.

The For-Each Style for Loop


Java For-each Loop | Enhanced For Loop
The Java for-each loop or enhanced for loop is introduced since J2SE 5.0. It
provides an alternative approach to traverse the array or collection in
Java. It is mainly used to traverse the array or collection elements. The
advantage of the for-each loop is that it eliminates the possibility of bugs
and makes the code more readable. It is known as the for-each loop
because it traverses each element one by one.

The drawback of the enhanced for loop is that it cannot traverse the
elements in reverse order. Here, you do not have the option to skip any
element because it does not work on an index basis. Moreover, you
cannot traverse the odd or even elements only.

But, it is recommended to use the Java for-each loop for traversing the
elements of array and collection because it makes the code readable.

Advantages
o It makes the code more readable.
o It eliminates the possibility of programming errors.

Syntax
The syntax of Java for-each loop consists of data_type with the variable
followed by a colon (:), then array or collection.

1. for(data_type variable : array | collection){


2. //body of for-each loop
3. }

How it works?
The Java for-each loop traverses the array or collection until the last
element. For each element, it stores the element in the variable and
executes the body of the for-each loop.

For-each loop Example: Traversing the array elements


1. //An example of Java for-each loop
2. class ForEachExample1{
3. public static void main(String args[]){
4. //declaring an array
5. int arr[]={12,13,14,44};
6. //traversing the array with for-each loop
7. for(int i:arr){
8. System.out.println(i);
9. }
10. }
11. }
12.

Output:

12
12
14
44

Let us see another of Java for-each loop where we are going to total the
elements.

1. class ForEachExample1{
2. public static void main(String args[]){
3. int arr[]={12,13,14,44};
4. int total=0;
5. for(int i:arr){
6. total=total+i;
7. }
8. System.out.println("Total: "+total);
9. }
10.}

Output:
Total: 83

For-each loop Example: Traversing the collection elements


1. import java.util.*;
2. class ForEachExample2{
3. public static void main(String args[]){
4. //Creating a list of elements
5. ArrayList<String> list=new ArrayList<String>();
6. list.add("vimal");
7. list.add("sonoo");
8. list.add("ratan");
9. //traversing the list of elements using for-each loop
10. for(String s:list){
11. System.out.println(s);
12. }
13.
14. }
15. }

Output:

vimal
sonoo
ratan

Strings

Java String
In Java, string is basically an object that represents sequence of char
values. An array of characters works same as Java string. For example:

1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);

is same as:

1. String s="javatpoint";
Java String class provides a lot of methods to perform operations on
strings such as compare(), concat(), equals(), split(), length(), replace(),
compareTo(), intern(), substring() etc.

The java.lang.String class


implements Serializable, Comparable and CharSequence interfaces.

CharSequence Interface
The CharSequence interface is used to represent the sequence of
characters. String, StringBuffer and StringBuilder classes implement it. It
means, we can create strings in Java by using these three classes.

The Java String is immutable which means it cannot be changed.


Whenever we change any string, a new instance is created. For mutable
strings, you can use StringBuffer and StringBuilder classes.

We will discuss immutable string later. Let's first understand what String
in Java is and how to create the String object.
What is String in Java?
Generally, String is a sequence of characters. But in Java, string is an
object that represents a sequence of characters. The java.lang.String 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. For Example:

1. String s="welcome";

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 the above example, only one object will be created. Firstly, JVM will not
find any string object with the value "Welcome" in string constant pool
that is why it will create a new object. After that it will find the string with
the value "Welcome" in the pool, it will not create a new object but will
return the reference to the same instance.

By new keyword
1. String s=new String("Welcome");//creates two objects and one refer
ence variable

In such case, JVM will create a new string object in normal (non-pool) heap
memory, and the literal "Welcome" will be placed in the string constant
pool. The variable s will refer to the object in a heap (non-pool).

Java String Example


String compare by equals()
class StringCompareequl{
public static void main(String []args){
String s1 = "tutorialspoint";
String s2 = "tutorialspoint";
String s3 = new String ("Tutorials Point");
System.out.println(s1.equals(s2));
System.out.println(s2.equals(s3));
}
}
The above code sample will produce the following result.
true
false

String compare by == operator


public class StringCompareequl{
public static void main(String []args){
String s1 = "tutorialspoint";
String s2 = "tutorialspoint";
String s3 = new String ("Tutorials Point");
System.out.println(s1 == s2);
System.out.println(s2 == s3);
}
}
The above code sample will produce the following result.
true
false

class StringReverseExample{
public static void main(String[] args) {
String string = "abcdef";
String reverse = new StringBuffer(string).reverse().toString();
System.out.println("\nString before reverse: "+string);
System.out.println("String after reverse: "+reverse);
}
}

Result
The above code sample will produce the following result.
String before reverse: abcdef
String after reverse: fedcba

StringExample.java

1. public class StringExample{


2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10.}}

Output:

java
strings
example

Bitwise Operators

Bitwise Operators

Bitwise operators are used to performing the manipulation of individual bits


of a number. They can be used with any integral type (char, short, int, etc.).
They are used when performing update and query operations of the Binary
indexed trees.
Now let’s look at each one of the bitwise operators in Java:
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:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise OR Operation of 5 and 7


0101
| 0111
________
0111 = 7 (In decimal)
2. Bitwise AND (&)
This operator is a binary operator, denoted by ‘&.’ It returns bit by bit AND of
input values, i.e., if both bits are 1, it gives 1, else it shows 0.
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise AND Operation of 5 and 7


0101
& 0111
________
0101 = 5 (In decimal)
3. Bitwise XOR (^)
This operator is a binary operator, denoted by ‘^.’ It returns bit by bit XOR of
input values, i.e., if corresponding bits are different, it gives 1, else it shows
0.
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise XOR Operation of 5 and 7


0101
^ 0111
________
0010 = 2 (In decimal)
4. Bitwise Complement (~)
This operator is a unary operator, denoted by ‘~.’ It returns the one’s
complement representation of the input value, i.e., with all bits inverted,
which means it makes every 0 to 1, and every 1 to 0.
Example:
a = 5 = 0101 (In Binary)

Bitwise Complement Operation of 5

~ 0101
________
1010 = 10 (In decimal)
AND Operator
Output
9

OR operator
Output
31

Bitwise AND Operator

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

int A = 10;
int B = 3;
int Y;
Y = A & B;
System.out.println(Y);

}
}
Output

Bitwise OR Operator

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

int A = 10;
int B = 3;
int Y;
Y = A | B;
System.out.println(Y);

}
}
Output
11

Bitwise XOR Operator

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

int A = 10;
int B = 3;
int Y;
Y = A ^ B;
System.out.println(Y);

}
}
Output

Bitwise Compliment Operator

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

int A = 10;
int Y;
Y = ~A ;
System.out.println(Y);

}
}
Output

-11

Press any key to continue . . .

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy