0% found this document useful (0 votes)
19 views11 pages

Java Essentials

The document discusses basic Java concepts including classes, objects, methods, and data types. It explains that a class acts as a blueprint for objects and defines their properties through fields and behaviors through methods. The document also covers primitive data types like int and double that store values directly, as well as reference data types like String that store object references. Finally, it discusses operators for performing operations.

Uploaded by

Mohan Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
19 views11 pages

Java Essentials

The document discusses basic Java concepts including classes, objects, methods, and data types. It explains that a class acts as a blueprint for objects and defines their properties through fields and behaviors through methods. The document also covers primitive data types like int and double that store values directly, as well as reference data types like String that store object references. Finally, it discusses operators for performing operations.

Uploaded by

Mohan Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 11

Example PDF

Author

2017-02-20

Basic Syntax and Data Types:

In Java, a program is made up of one or more classes. A class is a blueprint for


creating objects, which are instances of the class. The basic syntax for creating
a class in Java is as follows:
public class MyClass {
// Fields (also known as instance variables)
// Methods
// Constructors
}
The public keyword indicates that the class is accessible from anywhere. The
class keyword is used to declare a class. MyClass is the name of the class, and
it should match the filename (e.g., MyClass.java). The body of the class is
enclosed in curly braces {}.
Inside a class, we can declare fields, which are variables that hold data. Fields
represent the state of an object. For example:
public class MyClass {
int myNumber; // Field declaration
}
In this example, myNumber is a field of the MyClass class, and its type is int.
Fields can have different data types, such as int, double, String, etc.
Methods are blocks of code that perform a specific task. They define the behavior
of an object. Here’s an example of a method:
public class MyClass {
int myNumber;

public void printNumber() { // Method declaration


System.out.println(myNumber);

1
Variables and constants This
BASICis fancy
SYNTAX AND DATA TYPES:

}
}
In this case, printNumber is a method that prints the value of the myNumber
field.
Constructors are special methods used for initializing objects. They are called
when we create a new instance of a class. Here’s an example of a constructor:
public class MyClass {
int myNumber;

public MyClass(int number) { // Constructor declaration


myNumber = number;
}
}
This constructor takes an int parameter number and assigns it to the myNumber
field.
Java has various built-in data types, including, but not limited to:
• int - represents integer values
• double - represents floating-point values with decimal places
• boolean - represents true or false values
• String - represents sequences of characters
For example, we can declare variables of these types as follows:
int myInt = 10;
double myDouble = 3.14;
boolean isTrue = true;
String myString = "Hello, world!";
These are some of the basic syntax and data types in Java. By using these
concepts, you can start writing simple programs in Java.

Variables and constants


In Java, a variable is a named storage location that holds a value. It can be of
different types such as int, float, double, boolean, char, etc. Variables can be
assigned values and their values can be changed during the program execution.
Here’s an example of declaring and initializing a variable in Java:
int myVariable; // declaring a variable of type int
myVariable = 10; // assigning a value to the variable

System.out.println(myVariable); // prints the value of the variable

So is this 2
Variables and constants This
BASICis fancy
SYNTAX AND DATA TYPES:

In this example, myVariable is declared as an integer variable and as-


signed a value of 10. Later, the value of myVariable is printed using the
System.out.println() method.
A constant, on the other hand, is a value that cannot be changed. In Java,
constants are declared using the final keyword. Once a constant value is
assigned, it cannot be modified during the program execution.
Here’s an example of declaring a constant in Java:
final int MY_CONSTANT = 20; // declaring a constant variable of type int

System.out.println(MY_CONSTANT); // prints the value of the constant


In this example, MY_CONSTANT is declared as a constant integer variable with a
value of 20. The value of the constant cannot be modified, and its value can be
accessed throughout the program.
Variables and constants are fundamental concepts in Java programming that
allow us to store and manipulate data within our programs. They provide
flexibility and control over the data used in the program.

Primitive data types (int, double, char, etc.)


In Java, primitive data types are the most basic data types provided by the
language. These data types represent the most fundamental elements of data
that can be stored and manipulated in a program.
Some examples of primitive data types in Java are:
1. int: Used to hold integer numbers. For example, int num = 5;
2. double: Used to hold floating-point numbers (decimals). For example,
double num = 3.14;
3. char: Used to hold single characters. It is enclosed in single quotes. For
example, char letter = 'A';
4. boolean: Used to hold boolean values (true or false). For example,
boolean flag = true;
5. byte: Used to hold small integer numbers. For example, byte num = 10;
6. short: Used to hold larger integer numbers. For example, short num =
1000;
7. long: Used to hold very large integer numbers. It is represented by adding
the ‘L’ suffix at the end. For example, long num = 10000000000L;
These primitive data types are built-in and have a fixed size in memory, which
allows for efficient storage and manipulation of data. They are used to declare
variables that can store values of these specific types. For example, int num
declares a variable named ‘num’ that can hold integer values.

So is this 3
Variables and constants This
BASICis fancy
SYNTAX AND DATA TYPES:

Reference data types (objects)


In Java, reference data types, also known as objects, are variables that store the
memory address or reference of an object rather than the actual data. These
reference variables do not hold the actual data itself but rather point to the
location in memory where the object is stored.
To declare a reference variable in Java, you need to specify the object’s class
followed by the variable name. For example, to declare a reference variable of
type String, you would write:
String myString;
To create an object and assign it to the reference variable, you can use the new
keyword along with the class’s constructor. For example:
myString = new String("Hello");
In the above code, a new String object with the value “Hello” is created and the
reference to this object is assigned to the myString variable.
You can access the methods and fields of an object using the dot operator (.).
For instance, to get the length of a String object, you can use the length()
method:
int length = myString.length();
Note that when you assign one reference variable to another, they both point
to the same memory address. Therefore, if you modify one object, it will also
affect the other object that references the same memory location.
String firstName = "John";
String lastName = firstName; // Both firstName and lastName point to the same memory address

lastName = "Doe"; // Only modifies the value that lastName points to

System.out.println(firstName); // Output: John (firstName remains unchanged)


System.out.println(lastName); // Output: Doe (lastName points to a different value)
It’s important to note that Java’s primitive data types (int, char, double, etc.)
are not reference types, but rather value types. They store the actual data value
instead of a reference to it.

Operators (+, -, , /, %, etc.)*


In Java, operators are special symbols that perform certain operations on variables
or values.
1. Arithmetic Operators:
• Addition (+): Adds two operands.
• Subtraction (-): Subtracts the second operand from the first operand.
• Multiplication (*): Multiplies two operands.

So is this 4
Variables and constants This
BASICis fancy
SYNTAX AND DATA TYPES:

• Division (/): Divides the first operand by the second operand.


• Modulus (%): Returns the remainder of the division between two
operands.
• Increment (++) and Decrement (–): Increases or decreases the value
of an operand by 1.
• Unary Minus and Plus (-, +): Changes the sign of an operand.
2. Assignment Operators:
• Assignment (=): Assigns a value to a variable.
• Compound Assignment (+=, -=, *=, /=, %=): Performs a specific
operation and assigns the result to the variable.
3. Comparison Operators:
• Equal to (==): Checks if the values of two operands are equal.
• Not equal to (!=): Checks if the values of two operands are not equal.
• Greater than (>), Less than (<), Greater than or equal to (>=), Less
than or equal to (<=): Compare the values of two operands.
4. Logical Operators:
• Logical AND (&&): Returns true if both operands are true.
• Logical OR (||): Returns true if either operand is true.
• Logical NOT (!): Returns the opposite boolean value.
5. Bitwise Operators:
• Bitwise AND (&): Performs a bitwise AND on the operands.
• Bitwise OR (|): Performs a bitwise OR on the operands.
• Bitwise XOR (ˆ): Performs a bitwise XOR on the operands.
• Bitwise Complement (~): Inverts the bits of an operand.
• Left Shift («): Shifts the bits of the left operand to the left by the
number of positions specified by the right operand.
• Right Shift (»): Shifts the bits of the left operand to the right by the
number of positions specified by the right operand.
• Unsigned Right Shift (»>): Shifts the bits of the left operand to the
right by the number of positions specified by the right operand, filling
the new positions with zero.
These operators are used to perform various operations in Java, allowing you to
manipulate variables and values in different ways. # Control Flow: Control
flow in Java refers to the order in which statements are executed in a program.
It determines how a program will progress based on conditions and loops. There
are several constructs in Java that help control the flow of execution.
1. Decision-making statements:
• if-else statement: It tests a condition and executes a block of
statements if the condition evaluates to true, and another block if it
evaluates to false.
• switch statement: It evaluates a given expression and executes a
block of code based on matching cases.
2. Looping statements:
• for loop: It repeatedly executes a block of statements a fixed number
of times.

So is this 5
This
BASICis fancy
Conditional statements (if, else, switch) SYNTAX AND DATA TYPES:

• while loop: It repeatedly executes a block of statements as long as


a condition is true.
• do-while loop: It repeatedly executes a block of statements at least
once, and then continues as long as a condition is true.
3. Branching statements:
• break statement: It terminates the innermost loop or switch state-
ment, and transfers control to the next statement after the loop or
switch.
• continue statement: It skips the remaining statements in a loop
and continues with the next iteration.
• return statement: It terminates the execution of a method and
returns a value to the caller.
Control flow statements allow us to make decisions, repeat the execution of code,
and control the order of statements in a program. By using these constructs
effectively, we can create flexible and efficient algorithms in Java programs.

Conditional statements (if, else, switch)


Conditional statements in Java are used to control the flow of the program based
on certain conditions. There are mainly two types of conditional statements:
if-else statements and switch statements.
1. If-else statements: The if-else statement is used to execute a block of code
if a certain condition is true, and another block of code if the condition is
false. The basic syntax is as follows:
if(condition){
// code to be executed if the condition is true
} else{
// code to be executed if the condition is false
}
Example:
int score = 80;
if(score >= 60){
System.out.println("You passed the exam.");
} else{
System.out.println("You failed the exam.");
}
2. Switch statement: The switch statement is used to select one of many code
blocks to be executed. It evaluates an expression and then matches the
expression’s value with case labels. The basic syntax is as follows:
switch(expression){
case value1:
// code to be executed if the expression matches value1

So is this 6
This
BASICis fancy
Conditional statements (if, else, switch) SYNTAX AND DATA TYPES:

break;
case value2:
// code to be executed if the expression matches value2
break;
...
default:
// code to be executed if none of the cases match the expression
}
Example:
int day = 2;
switch(day){
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
...
default:
System.out.println("Invalid day");
}
In the above example, if the value of day is 2, it will print “Tuesday”. If the
value is not matched with any of the cases, it will execute the code inside the
default block.
These conditional statements are essential in writing programs that require
decision making based on different conditions. They provide the flexibility
to control the flow of execution and produce different outputs based on the
conditions.

Looping constructs (for, while, do-while)


Looping constructs in Java are used to repeat a block of code multiple times
until a certain condition is met. There are three types of looping constructs in
Java: for, while, and do-while.
1. for loop: The for loop is used when the number of iterations is known
in advance. It consists of three parts: initialization, condition, and incre-
ment/decrement.
Syntax:
for (initialization; condition; increment/decrement) {
// code to be executed
}
Example:

So is this 7
This
BASICis fancy
Conditional statements (if, else, switch) SYNTAX AND DATA TYPES:

for (int i = 0; i < 5; i++) {


System.out.println(i);
}
This will print the numbers from 0 to 4.
2. while loop: The while loop is used when the number of iterations is not
known in advance, but the condition is evaluated before each iteration.
Syntax:
while (condition) {
// code to be executed
}
Example:
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
This will print the numbers from 0 to 4.
3. do-while loop: The do-while loop is similar to the while loop, but the
condition is evaluated after each iteration. This means that the loop will
execute at least once, even if the condition is initially false.
Syntax:
do {
// code to be executed
} while (condition);
Example:
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
This will also print the numbers from 0 to 4.
All three types of loops can be used to execute a block of code repeatedly until a
certain condition is met. The choice of loop depends on the specific requirements
of the program.

Break and continue statements


The break and continue statements are control flow statements in Java that are
used to modify the behavior of loops.

So is this 8
This
BASICis fancy
Conditional statements (if, else, switch) SYNTAX AND DATA TYPES:

The break statement is used to exit a loop prematurely. It can be used with for,
while, and do-while loops. When the break statement is encountered within a
loop, the loop is immediately terminated, and the program execution continues
with the next statement following the loop.
Here’s an example that demonstrates the use of the break statement:
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // the loop will terminate when i becomes 5
}
System.out.println(i);
}
In the code above, the loop will print the numbers from 1 to 4, and when
i becomes 5, the break statement is executed, causing the loop to terminate.
Therefore, the output will be:
1
2
3
4
The continue statement is used to skip the remaining code within a loop
iteration and move to the next iteration. It can be used with for, while, and
do-while loops. When the continue statement is encountered within a loop, the
current iteration is immediately skipped, and the program execution continues
with the next iteration.
Here’s an example that demonstrates the use of the continue statement:
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // the loop will skip even numbers
}
System.out.println(i);
}
In the code above, the loop will print the odd numbers from 1 to 10. When i
is an even number, the continue statement is executed, causing the remaining
code within the loop to be skipped. Therefore, the output will be:
1
3
5
7
9
Both the break and continue statements provide control flow within loops,
allowing you to modify the loop’s behavior based on certain conditions.

So is this 9
This
BASICis fancy
Conditional statements (if, else, switch) SYNTAX AND DATA TYPES:

Certainly, here’s a table summarizing the basic syntax and some commonly used
data types in Java:

Concept Syntax Example


Comments // Single-line comment // This is a
comment
/* Multi-linecomment */ /* This is
amulti-line
comment */
Data Types int (integer) int age = 25;
double (floating-point double salary =
number) 55000.50;
boolean (true/false) boolean isJavaFun
= true;
char (single character) char grade = 'A';
String (text) String name =
"John";
Variables <DataType> int x;
<variableName>;
Variable <variableName> = <value>; x = 10;
Assignment
Initialization <DataType> <variableName> int y = 20;
= <value>;
Operators + (addition) int sum = x + y;
- (subtraction) int difference =
x - y;
* (multiplication) int product = x *
y;
/ (division) double quotient =
x / y;
Conditional if (condition) {// code} if (x > y) {//
Statements code}
else {// code} else {// code}
Loops for (initialization; for (int i = 0; i
condition; update) {// < 5; i++) {//
code} code}
while (condition) {// while (x > 0) {//
code} code}
Methods returnType int add(int a,
methodName(parameters) int b) {return a
{// code} + b;}
void (no return value) void
printMessage()
{System.out.println("Hello");}

So is this 10
This
BASICis fancy
Conditional statements (if, else, switch) SYNTAX AND DATA TYPES:

Concept Syntax Example


Class Definition public class ClassName public class
{// code} MyClass {// code}
Main Method public static void public static
main(String[] args) {// void
code} main(String[]
args) {// code}

Please note that Java is a case-sensitive language, so the capitalization of


keywords, data types, variable names, and method names is important. . . .

So is this 11

You might also like