0% found this document useful (0 votes)
16 views24 pages

Java Basics: Syntax and Functions

Uploaded by

jagadeesh2waran
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)
16 views24 pages

Java Basics: Syntax and Functions

Uploaded by

jagadeesh2waran
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

Page 1 of 24

PSNACET

JAVA BASICS

Basics : Basic syntax and functions from the Java programming language.
Boilerplate
Class HelloWorld {
Public static void main(String args[]) {
[Link](“Hello World”);
}
}

Showing Output
It will print something to the output console.

Class HelloWorld {
Public static void main(String args[]) {
[Link](“Hello World”);
}
}

Taking Input
It will take string input from the user.

Import [Link];
Class HelloWorld {
Public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
String name = [Link]();
[Link](name);
} }
Page 2 of 24
PSNACET

It will take integer input from the user.

Import [Link];
Class HelloWorld {
Public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
Int x = [Link]();
[Link](x);
}
}

It will take float input from the user.

Import [Link];
Class HelloWorld {
Public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
Float x = [Link]();
[Link](x);
}
}

It will take double input from the user.

Import [Link];
Class HelloWorld {
Public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
Page 3 of 24
PSNACET

Double x = [Link]();
[Link](x);
}
}

Primitive Type Variables


The eight primitives defined in Java are int, byte, short, long, float, double, boolean, and char.
These aren’t considered objects and represent raw values.

Byte
Byte is a primitive data type that only takes up 8 bits of memory.

Class HelloWorld {
Public static void main(String args[]) {
Byte age = 18;
[Link](age);
}
}

Long
Long is another primitive data type related to integers. Long takes up 64 bits of memory.

Class HelloWorld {
Public static void main(String args[]) {
Long var = 900L;
[Link](var);
}
}
Page 4 of 24
PSNACET

Float
We represent basic fractional numbers in Java using the float type. This is a single-precision
decimal number, which means if we get past six decimal points, this number becomes less
precise and more of an estimate.

Class HelloWorld {
Public static void main(String args[]) {
Float price = 100.05f;
[Link](price);
}
}

Char
Char is a 16-bit integer representing a Unicode-encoded character.

Class HelloWorld {
Public static void main(String args[]) {
Char letter = ‘A’;
[Link](letter);
}
}

Int
Int holds a wide range of non-fractional number values.

Class HelloWorld {
Public static void main(String args[]) {
Int var1 = 256;
[Link](var1);
} }
Page 5 of 24
PSNACET

Short
If we want to save memory and byte is too small, we can use short.

Class HelloWorld {
Public static void main(String args[]) {
Short var2 = 5666;
[Link](var2);
}
}

Comments
A comment is the code that is not executed by the compiler, and the programmer uses it to
keep track of the code.

Single line comment


// It’s a single line comment

Multi-line comment
/* It’s a
Multi-line
Comment
*/

Constants
Constants are like a variable, except that their value never changes during program execution.

Public class Declaration {


Final double PI = 3.14;
Page 6 of 24
PSNACET

Public static void main(String[] args) {


[Link](“Value of PI: “ + PI);
}
}

Arithmetic Expressions
These are the collection of literals and arithmetic operators.

Addition
It can be used to add two numbers.

Public class HelloWorld {


Public static void main(String args[]) {
Int x = 10 + 3;
[Link](x);
}
}

Subtraction
It can be used to subtract two numbers.

Public class HelloWorld {


Public static void main(String args[]) {
Int x = 10 – 3;
[Link](x);
}
}
Page 7 of 24
PSNACET

Multiplication
It can be used to multiply two numbers.

Public class HelloWorld {


Public static void main(String args[]) {
Int x = 10 * 3;
[Link](x);
}
}

Division
It can be used to divide two numbers.

Public class HelloWorld {


Public static void main(String args[]) {
Int x = 10 / 3;
[Link](x);
}
}

Modulo Remainder
It returns the remainder of the two numbers after division.

Public class HelloWorld {


Public static void main(String args[]) {
Int x = 10 % 3;
[Link](x);
}
}
Page 8 of 24
PSNACET

Augmented Operators
Addition assignment
Public class HelloWorld {
Public static void main(String args[]) {
Int var = 1;
Var += 10;
[Link](var);
}
}

Subtraction assignment
Public class HelloWorld {
Public static void main(String args[]) {
Int var = 1;
Var -= 10;
[Link](var);
}
}

Multiplication assignment
Public class HelloWorld {
Public static void main(String args[]) {
Int var = 1;
Var *= 10;
[Link](var);
}
}
Page 9 of 24
PSNACET

Division assignment
Public class HelloWorld {
Public static void main(String args[]) {
Int var = 1;
Var /= 10;
[Link](var);
}
}

Modulus assignment
Public class HelloWorld {
Public static void main(String args[]) {
Int var = 1;
Var %= 10;
[Link](var);
}
}

Escape Sequences
It is a sequence of characters starting with a backslash, and it doesn’t represent itself when
used inside a string literal.

Tab
It gives a tab space.

Public class HelloWorld {


Public static void main(String args[]) {
[Link](“\t”);
}
}
Page 10 of 24
PSNACET

Backslash
It adds a backslash.

Public class HelloWorld {


Public static void main(String args[]) {
[Link](“\\”);
}
}

Single quote
It adds a single quotation mark.

Public class HelloWorld {


Public static void main(String args[]) {
[Link](“\’”);
}
}

Question mark
It adds a question mark.

Public class HelloWorld {


Public static void main(String args[]) {
[Link](“?”);
}
}
Page 11 of 24
PSNACET

Carriage return
Inserts a carriage return in the text at this point.

Public class HelloWorld {


Public static void main(String args[]) {
[Link](“\r”);
}
}

Double quote
It adds a double quotation mark.

Public class HelloWorld {


Public static void main(String args[]) {
[Link](“\””);
}
}

Type Casting
Type Casting is a process of converting one data type into another.

Widening Type Casting


It means converting a lower data type into a higher.

Class HelloWorld {
Public static void main(String args[]) {
Int x = 45;
Double var_name = x;
[Link](var_name);
} }
Page 12 of 24
PSNACET

Narrowing Type Casting


It means converting a higher data type into a lower.

Class HelloWorld {
Public static void main(String args[]) {
Double x = 40005;
Int var_name = (int) x;
[Link](var_name);
}
}

Decision Control Statements


Conditional statements are used to perform operations based on some condition.

If Statement
If (condition) {
// block of code to be executed if the condition is true
}

If-else Statement
If (condition) {
// If condition is True then this block will get executed
} else {
// If condition is False then this block will get executed
}

If else-if Statement
If (condition1) {
// Codes
Page 13 of 24
PSNACET

} else if(condition2) {
// Codes
} else if (condition3) {
// Codes
} else {
// Codes
}

Ternary Operator
It is shorthand for an if-else statement.

Syntax
Variable = (condition) ? expressionTrue : expressionFalse;

Example
Public class TernaryOperatorExample {
Public static void main(String args[]) {
Int x, y;
X = 20;
Y = (x == 1) ? 61 : 90;
[Link](“Value of y is: “ + y);
Y = (x == 20) ? 61 : 90;
[Link](“Value of y is: “ + y);
}
}

Switch Statements
It allows a variable to be tested for equality against a list of values (cases).
Page 14 of 24
PSNACET

Class SwitchExample {
Public static void main(String args[]) {
Int day = 4;
Switch (day) {
Case 1:
[Link](“Monday”);
Break;
Case 2:
[Link](“Tuesday”);
Break;
Case 3:
[Link](“Wednesday”);
Break;
Case 4:
[Link](“Thursday”);
Break;
Case 5:
[Link](“Friday”);
Break;
Case 6:
[Link](“Saturday”);
Break;
Case 7:
[Link](“Sunday”);
Break;
}
}
}
Page 15 of 24
PSNACET

Iterative Statements
Iterative statements facilitate programmers to execute any block of code lines repeatedly and
can be controlled as per conditions added by the coder.

While Loop
It iterates the block of code as long as a specified condition is True.

Public class WhileExample {


Public static void main(String[] args) {
Int i = 1;
While(i <= 10) {
[Link](i);
I++;
}
}
}

For Loop
For loop is used to run a block of code several times.

Class HelloWorld {
Public static void main(String args[]) {
For(int i = 1; i < 100; i++) {
[Link](i);
}
}
}

For-each Loop
Public class HelloWorld {
Page 16 of 24
PSNACET

Public static void main(String args[]) {


Int[] arr = {2, 4, 5, 7, 8, 0, 3, 5};
For (int i : arr) {
[Link](i);
}
}
}

Do-while Loop
It is an exit-controlled loop. It is very similar to the while loop with one difference, i.e., the
body of the do-while loop is executed at least once even if the condition is False.

Public class HelloWorld {


Public static void main(String args[]) {
Int i = 1;
Do {
[Link](i);
I++;
} while(i <= 100);
}
}

Break statement
Break keyword inside the loop is used to terminate the loop.

Class HelloWorld {
Public static void main(String args[]) {
For(int i = 1; i < 100; i++) {
[Link](i);
Page 17 of 24
PSNACET

If(i == 50)
Break;
}
}
}

Continue statement
Continue keyword skips the rest of the current iteration of the loop and returns to the starting
point of the loop.

Class HelloWorld {
Public static void main(String args[]) {
For(int i = 1; i < 100; i++) {
[Link](i);
If(i == 50)
Continue;
}
}
}

Arrays
Arrays are used to store multiple values in a single variable.

Declaring an array
Declaration of an array.

Public class HelloWorld {


Public static void main(String args[]) {
String[] var_name;
}
Page 18 of 24
PSNACET

Defining an array
Defining an array.

Public class HelloWorld {


Public static void main(String args[]) {
String[] var_name = {“harry”, “rohan”, “aakash”};
}
}

Accessing an array
Accessing the elements of an array.

Public class HelloWorld {


Public static void main(String args[]) {
String[] var_name = {“Harry”, “Rohan”, “Aakash”};
[Link](var_name[0]);
}
}

Changing an element
Changing any element in an array.

Public class HelloWorld {


Public static void main(String args[]) {
String[] var_name = {“Harry”, “Rohan”, “Aakash”};
Var_name[2] = “Shubham”;
} }
Page 19 of 24
PSNACET

Array length
It gives the length of the array.

Public class HelloWorld {


Public static void main(String args[]) {
String[] var_name = {“Harry”, “Rohan”, “Aakash”};
[Link](var_name.length);
}
}

Loop through an array


It allows us to iterate through each array element.

Public class HelloWorld {


Public static void main(String args[]) {
String[] var_name = {“Harry”, “Rohan”, “Aakash”};
For (int i = 0; i < var_name.length; i++) {
[Link](var_name[i]);
}
}
}

Multi-dimensional Arrays
Arrays can be 1-D, 2-D, or multi-dimensional.

// Creating a 2x3 array (two rows, three columns)


Int[][] matrix = new int[2][3];
Matrix[0][0] = 10;
Page 20 of 24
PSNACET

// Shortcut
Int[][] matrix = {
{ 1, 2, 3 },
{ 4, 5, 6 }
};

Methods
Methods are used to divide an extensive program into smaller pieces. It can be called multiple
times to provide reusability to the program.

Declaration
Declaration of a method.

returnType methodName(parameters) {
// statements
}

Calling a method
Calling a method.

methodName(arguments);

Example
Public static void findEvenOdd(int num) {
// method body
If(num % 2 == 0)
[Link](num + “ is even”);
Else
[Link](num + “ is odd”);
}
Page 21 of 24
PSNACET

Import [Link];
Public class EvenOdd {
Public static void main (String args[]) {
// creating Scanner class object
Scanner scan = new Scanner([Link]);
[Link](“Enter the number: “);
// reading value from the user
Int num = [Link]();
// method calling
findEvenOdd(num);
}
}

Method Overloading
Method overloading means having multiple methods with the same name, but different
parameters.

Class Calculate {
Void sum(int x, int y) {
[Link](“Sum is: “ + (x + y));
}
Void sum(float x, float y) {
[Link](“Sum is: “ + (x + y));
}
Public static void main(String[] args) {
Calculate calc = new Calculate();
[Link](5, 4); // sum(int x, int y) is called.
[Link](1.2f, 5.6f); // sum(float x, float y) is
called.
Page 22 of 24
PSNACET

}
}

Recursion
Recursion is when a function calls a copy of itself to work on a minor problem. The function
that calls itself is known as the Recursive function.

Void Recurse() {
Recurse();
}

Strings
It is a collection of characters surrounded by double quotes.

Creating String Variable


String var_name = “Hello World”;

String Length
Returns the length of the string.

Public class str {


Public static void main(String args[]) {
String var_name = “Harry”;
[Link](“The length of the string is: “ +
var_name.length());
}
}
Page 23 of 24
PSNACET

String Methods
toUpperCase()
Convert the string into uppercase.

Public class str {


Public static void main(String args[]) {
String var_name = “Harry”;
[Link](var_name.toUpperCase());
}
}

toLowerCase()
Convert the string into lowercase.

Public class str {


Public static void main(String args[]) {
String var_name = “Harry”;
[Link](var_name.toLowerCase());
}
}

indexOf()
Returns the index of a specified character from the string.

Public class str {


Public static void main(String args[]) {
String var_name = “Harry”;
[Link](var_name.indexOf(“a”));
} }
Page 24 of 24
PSNACET

Concat()
Used to concatenate two strings.

Public class str {


Public static void main(String args[]) {
String var1 = “Harry”;
String var2 = “Bhai”;
[Link]([Link](var2));
}
}

Math Class
Math class allows you to perform mathematical operations.

Methods max() method


It is used to find the greater number among the two.

Public class Demo {


Public static void main(String[] args) {
// using the max() method of Math class
[Link](“The maximum number is
}

You might also like