Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Switch and loops in Java programming?

 

Hello everyone Today we will read about switch and loop statement in java.

If you haven't seen Java last post, read that too first. here is the link click here






What is switch statement in java?

In Java, a switch statement is used to execute different code blocks based on the value of a variable or expression. It is similar to a series of if statements but can be more efficient and easier to read in some cases.

Syntax for switch statement

switch (expression) {

case value1:
    // code to execute if expression equals value1
    break;
    case value2:
    // code to execute if expression equals value2
    break;
    // more cases can be added here
    default:
    // code to execute if expression does not match any case
    break;
}

Here switch is java keyword. Expression is a variable whose value will decide which case statement will run.

Case is also a keyword. Here we will put different values of variables.

Default is a keyword which is used when no case value matches with variable value.

what is a good example of switch statement in java?

switch.png

Output:

Here days, case 3 will run and the rest of the cases will not. Thus dayName value will be Wednesday.

So in output, Wednesday will be printed.OfWeek=3

One more thing here we have used a break statements. Why?

What is the use of a break statement?

In Java, the break statement is used to exit a loop or switch statement. When a break statement is encountered inside a loop or switch statement, control is immediately transferred to the statement immediately following the loop or switch block.

In this example, the switch statement sets the dayName variable based on the value of dayOfWeek. When dayOfWeek is 3, the case 3 block is executed and sets dayName to "Wednesday". The break statement then exits the switch statement, and control is transferred to the statement immediately following the switch block, which prints "Today is Wednesday". If the break statements were not included, the switch statement would continue executing the code in the subsequent case labels and will print the rest of the cases as well.


what are loops in java?

In Java, loops are used to execute a block of code repeatedly while a certain condition is true.

There are three types of loops in Java:

  • for loop:A for loop is used to iterate over a range of values. It has three parts: initialization, condition, and iteration. Here's an example:
for-loop.png

In this example, the loop initializes the i variable to 0, checks if i is less than 10, and increments i by 1 after each iteration. The loop continues to execute as long as the condition (i < 10) is true.

  • while loop: A while loop is used to run a piece of code continuously while a condition is true. It has only one part: the condition. Here's an example:A while loop is used to repeatedly run a block of code while a condition is true. It just has one component: the condition. Here's an illustration:
while-loop.png

In this example, the loop checks if i is less than 10 before each iteration. The loop continues to execute as long as the condition (i < 10) is true. I variable is incremented by 1 after each iteration.

  • do-while loop: A do-while loop is similar to a while loop, but it guarantees that the loop body is executed at least once before checking the condition. Here's an example.
do-while-loop.png

In this example, the loop initializes the i variable to 0 and executes the loop body at least once. The loop checks if i is less than 10 after each iteration. The loop continues to execute as long as the condition (i < 10) is true.

All three types of loops can be used to execute a block of code repeatedly, but they differ in how the condition is checked and when the loop body is executed. It's important to choose the appropriate loop type for the task at hand to ensure efficient and correct code execution.

Code to find factorial of a number:
example.png

Output:

output.png


what is Java continue statement?

In Java, the continue statement is used to skip the current iteration of a loop and continue with the next iteration. When the continue statement is encountered within a loop, the remaining statements in the loop body are skipped and the loop control passes to the next iteration.

Here's an example that uses the continue statement to skip even numbers in a loop:

continue-statement.png

Output:

output.png

As you can see, the even numbers (2, 4, 6, 8, 10) are skipped due to the continued statement.

So that’s it for today guys if you want to learn more about javascript follow and stay tuned with guerillateck.com

Thanks for learning give us your feedback?



Question for practice:

1. find the sum of two 3*3 matrices.

2. Find compound interest without using direct formula?


Thanks for Reading…


How java is important programming language in cyber security part-2

Hello everyone, this is the second post on Java programming language. Today we will read about operators.

if you haven't seen the last post on Java programming, then go and see it first. 

what are operators?

operators are symbols that are used to perform operations on variables and manipulate the values of the operands. Each operator performs specific operations. Let us consider an expression 5 + 1 = 6; here, 5 and 1 are operands, and the symbol + (plus) is called the operator. We will also learn about operator precedence and operator associativity.

Here we will talk about Arithmetic operators, Relational operators, Unary operators, etc.

  • Arithmetic Operators:-  There are five operators: ‘+’, ‘ – ‘, ‘ * ‘, ‘ / ‘, and ‘ % '.
    • ‘ + ‘ used for addition and concatenation (adding two strings).
    • ‘ – ‘is used for subtracting two values.
    • ‘ * ‘ is used for multiplication.
    • ‘ / ‘is used for division.
    • ‘ % ‘Is used for finding the remainder.

operator.png

Output:-

output.png

I used float data type so that on dividing output should be in decimal value.

If I have used int then on division the answer will be 2.

  • Relational Operators:- 
    • Comparison Operators:  
      • ‘a<b' means a is less than b.
      • ‘a>b’ means a is greater than b.
      • ‘a<=b’ means a is less than or equal to b.
      • ‘a>=b’ means a is greater than or equal to b.
    • Equality Operators :
      • ‘==’ it is used to check equal values.
      • ‘!=’ it is used to check whether two values are unequal.
  • Unary Operator:-
The Java unary operators require only one operand. Unary operators are used to performing various operations i.e.:

incrementing/decrementing a value by one

inverting the value of a boolean

If value of a = 10;

Then

System.out.println(a++); //It will print the value of an i.e., 10 and then it will increase to 11.

System.out.println(++a); //It will first increase the value and then print it increased value.

Similarly ‘—a’ and ‘a—’ are used for decreasing the value.

If c = true;  // a Boolean variable

Then

System.out.pritnln(!c); //it will print opposite of c i.e., false

  • Logical Operator:-
We have two types of logical operators && and ||
These operators are used to check two or more conditions

Use of &&: If all conditions are true simultaneously then only it will show true otherwise false.

example:-

&&operator.png

Output:- True

&&operator.png

Output:- False

It will show false because only one condition is true.

Use of ||: If all conditions are false simultaneously then only it will show false otherwise true.

That means even if only 1 condition is true in all then also it will return true.

| | operator.png

Output: True

As one of the two conditions are true so it will show true

| | operator.png

Output: false 

As both conditions are false here so it will print false

  • Assignment Operator:

It is employed to translate the operand on its left into the value on its right.

assignment operator.png


Java Control Statements

The Java compiler runs the code from top to bottom. The statements of the code are executed in the order they appear. Statements in Java, however, can be used to control how Java code is executed. Control flow statements are the phrases that fit this description. It guarantees a smooth flow of programs, which is one of Java's fundamental features.

Java provides three types of control flow statements.

  • Decision-Making statements
    1. if statements
    2. switch statement
  • Loop statements
    1. do while loop
    2. while loop
    3. for loop
    4. for-each loop
  • Jump statements
    1. break statement.
    2. continue statement

Decision-Making statements

Decision-making statements, as the name implies, choose which statement to execute and when. Depending on the outcome of the condition given, decision-making statements analyze the Boolean expression and regulate the program flow. In Java, there are two different categories of decision-making statements: If statements and switch statements.

1) If Statement:

In Java, a condition is evaluated using the "if" expression. Depending on the circumstances, the software's control is changed. The If statement's condition produces a Boolean value, either true or false. In Java, there are four types of if-statements given below.

  • Simple if statement
  • if-else statement
  • if-else-if ladder
  • Nested if-statement

Let's understand the if-statements one by one.

Simple if statement:
Among all Java's control flow statements, it is the simplest. It tests a Boolean statement and, if it returns true, allows the program to enter a block of code.
simple-if-statement.png

Output: x+ y is greater than 20

if-else statement

Among all Java's control flow statements, it is the simplest. It tests a Boolean statement and, if it returns true, allows the program to enter a block of code.

if-else_statement.png

Output:

x + y is greater than 20


if-else-if ladder:


A series of else-if statements are placed after an if statement in an if-else-if statement. In other words, the series of if-else statements build a decision tree that allows the program to execute the block of code when the condition is true. At the chain's conclusion, we can define an else statement.

if-else-if ladder.png

Output: Delhi

Nested if-statement

The if statement can have an if or an if-else statement inside of another if or else-if statement in nested if statements.

nested_if-else.png

Output: Delhi




so, that's it for today, follow us to learn more about Java.

thank's for learning.



How java is important programming language in cyber security?

INTRODUCTION


Java is well-known for its portability, which means that a Java program can run on any platform that includes a Java Virtual Machine (JVM). This simplifies the creation of programs that can operate on multiple platforms without having to rewrite the code for each one.

Java is commonly utilized in a range of areas, including finance, healthcare, and telecommunications. It is also widely used for developing enterprise-level applications and is a preferred choice for server-side development.

What is Java?


Sun Microsystems released Java as a programming language in 1995. James Gosling started it all. It is based on C and C++ syntax. 

it is a programming language that is class-based, object-oriented, high-level,  and  secure


Here are some examples of how Java is used:-

  1. Java is used in the E-commerce and web applications space.
  2. Java is also used in Financial Services. Companies like Goldman Sachs, Citigroup, and Barclays use java.
  3. Java is also used in Financial Services. Companies like Goldman Sachs, Citigroup, and Barclays use java.
  4. Java is used to develop Software tools like Eclipse IDE, IntelliJ Idea, and NetBeans IDE.

Now let's write our first code of Java.

java.png


Explanation of code:

  • Whatever code we create in Java must be placed in a class. If it is a public class then file name should be same as class name.
  • public: public is a access modifier which tells us where we can access the variables and all in code. In simple words it means visibility.
 We will talk about it in depth later on
  • JVM: its full form is Java virtual machine. It creates an environment where java code can compile. Due to this Java is machine independent

You can use the same Java code to run on any machine.

  • static: Static is a keyword. Any method that is declared static is known as a static method. The primary advantage of the static technique

is that no object is required to activate the static method (as mentioned below). The JVM executes the main() method, therefore it does not need to be called.

 To invoke the main() method, you must first create an object. As a result, it conserves memory.


  • main: main is function name. Every class has many functions which have some code with some functionalities. main function is always the starting point of all program.
  • String: it is the data type for the 'a[]' array. There are other data types also available. we will see them in just a while.
  • void: It is the main function's return type.
  • System.out.println("..."): Whenever we want to print anything on the console we have to use this command.

    Where to write code and how to run it?


    If you are a beginner it will be best if you use Notepad or Notepad++ to run java codes. Else you can use many IDEs to run java like IntelliJ Idea,

    Netbeans, Eclipse, VScode etc.

    To run the code save the file with name same as class name and with extension.java . Then go to command prompt write javac <'your file name'.java> click enter

    then write java <file name> without extension hit enter. 

    cmd prmpt.png

    Note:

    1. Java is case sensitive language so 'a' and 'A' are considered as different
    2. Before running the code, ensure that you have downloaded and installed jdk.
    3. here you can notice I used cd desktop. Cd is used for changing directories. This command is used to locate the directory in which our file is saved. If you save the file I some other directory then do it accordingly.


    Variables in JAVA

    A variable is like a container which stores value for you that you can use later or at any time.

    Variables can be of three types:

    1. Local Variables: These variables can be accessed only inside the body where they are declared. They cannot be defined static.
    2. Instance Variable: An instance variable is a variable declared within the class but outside the method body. It's not marked as static.
    3. Static: A variable that is declared static is called a static variable. It cannot be local. You can make a single duplicate of the static variable and distribute it to all instances of the class. Static variable memory allocation occurs only once when the class is loaded into memory.

    Example
    variable.png

    What is an object in Java?

    An object is a type of instance that we utilize to call a function. An object is always created for a specific class. Then we can use that object to call any function of that class.

    example: 


    Explanation of code: here we create a class 'object_example' then we create a function 'method1' to call this function we create an object O1 in the main method.

    It is important to note that we create the object and call the function in the main method since every program begins with the main method.

    what is memory allocation?


    When the JVM begins the program, the first thing it does is locate all objects and variables and assign their memory in the computer ram. This is known as memory allocation.

    Variables and functions with static keywords must first have memory in RAM. Furthermore, memory has only been given to static variables and static functions once in one program.

    As a result, they are memory efficient.

    Data Types in Java

    There are two types of variables: 

    • Primitive variables:
      1. int: It is used to store integer values. Its default size is 4 bytes. That means for every variable it will cover 4 bytes of space in ram.

      2. float: It is used to store decimal values. Its default size is 4 bytes. That means for every variable it will cover 4 bytes of space in ram.

      3. long: It is used to store integer values. Its default size is 8 bytes. That means for every variable it will cover 4 bytes of space in ram. This is the same as int but it has a larger range than int. That means whenever you are required to store large numbers you will use long.

      4. double: It is used to store decimal values. Its default size is 8 bytes. That means for every variable it will cover 4 bytes of space in ram. This is the same as float

      5. char: It is used to store a single character value like 'A', 'B' etc; Its default size is 2 bytes.

      6. boolean: It is used to store either 'true' or 'false'. Its default size is 1 byte.


    • Non-Primitive Variables:
    Non-primitive data types are user-defined data types.

      1. String: It's used to save a string of characters. like any sentence or name etc. (will discuss it in an upcoming blog)

      2. array: It is used to store several values. (This will be covered in future posts)


    Example for data types



    Type Name

    Bytes

    Range of Values

    int

    4

    -2,147,483,648 to 2,147,483,647

    bool

    1

    false or true

    char

    1

    -128 to 127 by default

    short

    2

    -32,768 to 32,767

    long

    4

    -2,147,483,648 to 2,147,483,647

    float

    4

    3.4E +/- 38 (7 digits)

    double

    8

    1.7E +/- 308 (15 digits)

    long double

    same as double

    Same as double


    Comments: Comments are that part of code that JVM will ignore and not interpret as code. they are written as '//' If they were ignored by JVM

    then why do we use comments. Comments are used to aid in the self-understanding of code or to make code more understandable to others.



    So that's it for today and follow us for more...


    thanks for reading...