0% found this document useful (0 votes)
2 views20 pages

Java Pract1

Uploaded by

jpnawade
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)
2 views20 pages

Java Pract1

Uploaded by

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

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

Why Use Java?


 Java works on different platforms (Windows, Mac, Linux, Raspberry Pi,
etc.)
 It is one of the most popular programming languages in the world
 It has a large demand in the current job market
 It is easy to learn and simple to use
 It is open-source and free
 It is secure, fast and powerful
 It has huge community support (tens of millions of developers)
 Java is an object oriented language which gives a clear structure to
programs and allows code to be reused, lowering development costs
 As Java is close to C++ and C#, it makes it easy for programmers to
switch to Java or vice versa

public static void main(String[] args)

public

 This is an access modifier.


 It means the method is accessible from anywhere, i.e., other classes or the Java
runtime environment (JRE) can call this method.

static

 This means the method belongs to the class, not to an object of the class.
 The Java Virtual Machine (JVM) calls this method without creating an object of the
class.

void

 This is the return type of the method.


 It means the method does not return any value.
🔹 main

 This is the name of the method.


 It is predefined in Java as the starting point of a Java program.
 JVM looks for the main() method to start the execution of a Java application.

String[] args

 This is a parameter to the main method.


 It is an array of Strings.
 It is used to accept command-line arguments when the program is run.

Example:

java
CopyEdit
java MyProgram Hello World

Then args[0] is "Hello" and args[1] is "World".

public static void main(String[] args)

Is the starting point of a Java program.

It must be written exactly like this (with minor variations like String... args).

Without it, the program won’t run, and you'll get an error like:

Error: Main method not found in class

The Print() Method


There is also a print() method, which is similar to println().

The only difference is that it does not insert a new line at the end of the
output:

Example
System.out.print("Hello World! ");

System.out.print("I will print on the same line.");

System.out.println("This sentence will work!");

System.out.println(This sentence will produce an error);

You can also use the println() method to print numbers.


System.out.println(2 * 5);

Java Comments
Comments can be used to explain Java code, and to make it more readable. It
can also be used to prevent execution when testing alternative code.

Single-line Comments
Single-line comments start with two forward slashes ( //).

Any text between // and the end of the line is ignored by Java (will not be
executed).

This example uses a single-line comment before a line of code:

ExampleGet your own Java Server


// This is a comment

System.out.println("Hello World");

Java Multi-line Comments


Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Java.

This example uses a multi-line comment (a comment block) to explain the


code:

Example
/* The code below will print the words Hello World

to the screen, and it is amazing */

System.out.println("Hello World");

Java Variables
Variables are containers for storing data values.
In Java, there are different types of variables, for example:

 String - stores text, such as "Hello". String values are surrounded by


double quotes
 int - stores integers (whole numbers), without decimals, such as 123 or
-123
 float - stores floating point numbers, with decimals, such as 19.99 or -
19.99
 char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
 boolean - stores values with two states: true or false

Declaring (Creating) Variables


To create a variable in Java, you need to:

 Choose a type (like int or String)


 Give the variable a name (like x, age, or name)
 Optionally assign it a value using =

 type variableName = value;


 Create a variable called name of type String and assign it the value
"John".
Then we use println() to print the name variable:
 String name = "John";
 System.out.println(name);

 To create a variable that should store a number, you can use int:

 Example
 Create a variable called myNum of type int and assign it the
value 15:

 int myNum = 15;

 System.out.println(myNum);

 You can also declare a variable without assigning the value, and assign
the value later:

 Example
 int myNum;

 myNum = 15;

 System.out.println(myNum);
 Note that if you assign a new value to an existing variable, it will
overwrite the previous value:

 Example
 Change the value of myNum from 15 to 20:

 int myNum = 15;

 myNum = 20; // myNum is now 20

 System.out.println(myNum);

Other Types
A demonstration of how to declare variables of other types:

Example
int myNum = 5;

float myFloatNum = 5.99f;

char myLetter = 'D';

boolean myBool = true;

String myText = "Hello";

Display Variables
The println() method is often used to display variables.

To combine both text and a variable, use the + character:

ExampleGet your own Java Server


String name = "John";

System.out.println("Hello " + name);

You can also use the + character to add a variable to another variable:

Example
String firstName = "John ";

String lastName = "Doe";


String fullName = firstName + lastName;

System.out.println(fullName);

int x = 5;

int y = 6;

System.out.println(x + y); // Print the value of x + y

The general rules for naming variables are:

 Names can contain letters, digits, underscores, and dollar signs


 Names must begin with a letter
 Names should start with a lowercase letter, and cannot contain
whitespace
 Names can also begin with $ and _
 Names are case-sensitive ("myVar" and "myvar" are different
variables)
 Reserved words (like Java keywords, such as int or boolean) cannot be
used as names

public class Main {

public static void main(String[] args) {

// Create integer variables

int length = 4;

int width = 6;

int area;

// Calculate the area of a rectangle

area = length * width;

// Print variables

System.out.println("Length is: " + length);

System.out.println("Width is: " + width);

System.out.println("Area of the rectangle is: " + area);

}
Boolean Types
Very often in programming, you will need a data type that can only have one
of two values, like:

 YES / NO
 ON / OFF
 TRUE / FALSE

For this, Java has a boolean data type, which can only take the
values true or false:

Example

public class Main {

public static void main(String[] args) {

boolean isJavaFun = true;

boolean isFishTasty = false;

System.out.println(isJavaFun);

System.out.println(isFishTasty);

Characters
The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c':

Example

public class Main {

public static void main(String[] args) {

char myGrade = 'B';

System.out.println(myGrade);

}
Strings
The String data type is used to store a sequence of characters (text). String
values must be surrounded by double quotes:

Example
Strings
The String data type is used to store a sequence of characters (text). String
values must be surrounded by double quotes:

Example
public class Main {

public static void main(String[] args) {

String greeting = "Hello World";

System.out.println(greeting);

Java Conditions and If Statements


You already know that Java supports the usual logical conditions from
mathematics:

 Less than: a < b


 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
 Equal to a == b
 Not Equal to: a != b

You can use these conditions to perform different actions for different
decisions.

Java has the following conditional statements:

 Use if to specify a block of code to be executed, if a specified


condition is true
 Use else to specify a block of code to be executed, if the same
condition is false
 Use else if to specify a new condition to test, if the first condition is
false
 Use switch to specify many alternative blocks of code to be executed

The if Statement
Use the if statement to specify a block of Java code to be executed if a
condition is true.

Syntax
if (condition) {

// block of code to be executed if the condition is true

}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate
an error.

public class Main {

public static void main(String[] args) {

if (20 > 18) {

System.out.println("20 is greater than 18"); // obviously

The else Statement


Use the else statement to specify a block of code to be executed if the
condition is false.

Syntax
if (condition) {

// block of code to be executed if the condition is true

} else {
// block of code to be executed if the condition is false

Example

public class Main {

public static void main(String[] args) {

int time = 20;

if (time < 18) {

System.out.println("Good day.");

} else {

System.out.println("Good evening.");

The else if Statement


Use the else if statement to specify a new condition if the first condition
is false.

Syntax
if (condition1) {

// block of code to be executed if condition1 is true

} else if (condition2) {

// block of code to be executed if the condition1 is false and


condition2 is true

} else {

// block of code to be executed if the condition1 is false and


condition2 is false

}
Example

public class Main {

public static void main(String[] args) {

int time = 22;

if (time < 10) {

System.out.println("Good morning.");

} else if (time < 18) {

System.out.println("Good day.");

} else {

System.out.println("Good evening.");

This example shows how you can use if..else to find out if a number is
positive or negative:

Example
public class Main {

public static void main(String[] args) {

int myNum = 10; // Is this a positive or negative number?

if (myNum > 0) {

System.out.println("The value is a positive number.");

} else if (myNum < 0) {

System.out.println("The value is a negative number.");

} else {
System.out.println("The value is 0.");

Java Switch Statements


Instead of writing many if..else statements, you can use
the switch statement.

The switch statement selects one of many code blocks to be executed:

Syntax
switch(expression) {

case x:

// code block

break;

case y:

// code block

break;

default:

// code block

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 The break and default keywords are optional

Example

public class Main {

public static void main(String[] args) {

int day = 4;
switch (day) {

case 1:

System.out.println("Monday");

break;

case 2:

System.out.println("Tuesday");

break;

case 3:

System.out.println("Wednesday");

break;

case 4:

System.out.println("Thursday");

break;

case 5:

System.out.println("Friday");

break;

case 6:

System.out.println("Saturday");

break;

case 7:

System.out.println("Sunday");

break;

}
The break Keyword
When Java reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no
need for more testing.

A break can save a lot of execution time because it "ignores" the execution of
all the rest of the code in the switch block.

The default Keyword


The default keyword specifies some code to run if there is no case match:

public class Main {

public static void main(String[] args) {

int day = 4;

switch (day) {

case 6:

System.out.println("Today is Saturday");

break;

case 7:

System.out.println("Today is Sunday");

break;

default:

System.out.println("Looking forward to the Weekend");

Java While Loop


Loops
Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code
more readable.

Java While Loop


The while loop loops through a block of code as long as a specified condition
is true:

Syntax
while (condition) {

// code block to be executed

In the example below, the code in the loop will run, over and over again, as
long as a variable (i) is less than 5: public class Main {

public static void main(String[] args) {

int i = 0;

while (i < 5) {

System.out.println(i);

i++;

Note: Do not forget to increase the variable used in the condition ( i++),
otherwise the loop will never end!

Do you wonder why we used the letter i in the example above? It's
a counter variable and a common choice in simple loops because it's short,
traditional, and stands for 'index' or 'iterator'.

public class Main {


public static void main(String[] args) {

int countdown = 3;

while (countdown > 0) {

System.out.println(countdown);

countdown--;

System.out.println("Happy New Year!!");

The Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute the
code block once, before checking if the condition is true. Then it will repeat
the loop as long as the condition is true.

Syntax
do {

// code block to be executed

while (condition);

Example

public class Main {

public static void main(String[] args) {

int i = 0;

do {

System.out.println(i);

i++;
}

while (i < 5);

Condition is False from the Start


In the example above, the condition i < 5 was true at the beginning, so the
loop executed multiple times. But what if the condition is false right from the
start?

In the example below, the variable i starts at 10, so the condition i < 5 is
false immediately - yet the do/while loop still runs once:

Example
public class Main {

public static void main(String[] args) {

int i = 10;

do {

System.out.println("i is " + i);

i++;

} while (i < 5);

Example

public class Main {

public static void main(String[] args) {

int countdown = 3;

while (countdown > 0) {


System.out.println(countdown);

countdown--;

System.out.println("Happy New Year!!");

Java For Loop


When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop:

Syntax
for (statement 1; statement 2; statement 3) {

// code block to be executed

public class Main {

public static void main(String[] args) {

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

System.out.println(i);

Print Even Numbers


This example prints even values between 0 and 10:

public class Main {

public static void main(String[] args) {

for (int i = 0; i <= 10; i = i + 2) {


System.out.println(i);

Sum of Numbers
This example calculates the sum of numbers from 1 to 5:

public class Main {

public static void main(String[] args) {

int sum = 0;

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

sum = sum + i;

System.out.println("Sum is " + sum);

Nested Loops
It is also possible to place a loop inside another loop. This is called a nested
loop.

The "inner loop" will be executed one time for each iteration of the "outer
loop":

Example

public class Main {

public static void main(String[] args) {

// Outer loop.

for (int i = 1; i <= 2; i++) {


System.out.println("Outer: " + i); // Executes 2 times

// Inner loop

for (int j = 1; j <= 3; j++) {

System.out.println(" Inner: " + j); // Executes 6 times (2 * 3)

You might also like