programming Archives - SoftUni Global https://softuni.org/tag/programming/ Learn Programming and Start a Developer Job Fri, 25 Nov 2022 09:16:17 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.3 https://softuni.org/wp-content/uploads/2022/04/cropped-SoftUni-Global-Logo-Square-notext-32x32.png programming Archives - SoftUni Global https://softuni.org/tag/programming/ 32 32 Making A Sliding Puzzle in Java: Step-by-step Guide [Project Tutorials] https://softuni.org/project-tutorials/making-a-sliding-puzzle-in-java/ https://softuni.org/project-tutorials/making-a-sliding-puzzle-in-java/#respond Mon, 17 Oct 2022 13:05:04 +0000 https://softuni.org/?p=23354 In this edition of the Project Tutorial series, we will create a simple sliding puzzle game in Java.

The post Making A Sliding Puzzle in Java: Step-by-step Guide [Project Tutorials] appeared first on SoftUni Global.

]]>

Sliding puzzles are mechanical devices made of blocks of wood or plastic set into a frame as well as simple but addictive computer games that improve your problem-solving skills. The pieces are usually simple shapes or imprinted with colors, patterns, sections of a bigger picture, numbers, or letters.  Sliding puzzles, also known as sliders or sliding-block puzzles, are different from rearrangement puzzles in that the pieces cannot be lifted or removed from the frame. To win, you have to arrange them in a specific pattern by sliding them into certain routes on the board. Each move opens a new path and rearranges the pieces, so you have to plan carefully in order to achieve the end configuration.

Following this tutorial, you will make your own 3×3 sliding puzzle using Java.

Sliding-Puzzle-Gameplay

Note: To create the game, you can use more advanced implementations like arrays and matrices. The method used in this tutorial is simple and targets absolute beginners.
Let’s begin.

Before You Start

For the user interface, you use Swing. Swing is a GUI (Graphical User Interface) widget toolkit for Java. It is built on top of the AWT (Abstract Windowing Toolkit) API. Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for the Java Swing API such as JButton, JTextField, JLabel, JMenu, etc. You will use the Main method to start the program, but the programming logic will be written in a separate class.

Preparing Variables

Create a new project and give it a descriptive and meaningful name.

Your Main method should look like this:

				
					public class Main {
   public static void main(String[] args){
       new Puzzle();
   }
}
				
			

Right-click on your project folder and create a new Java class – Puzzle. To use the functionalities (methods) of Swing, the class should extend JFrame. To make certain actions happen when you click on the puzzle pieces, you also need an event listener. Make the class implement ActionListener.

				
					import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Puzzle extends JFrame implements ActionListener{
}
				
			

Your puzzle will be 3×3 so you need to declare 9 buttons for each of the puzzle pieces, as well as a shuffle button to rearrange them. You can also implement a counter for the number of clicks the user has performed. To make the counter, you need an integer and a label to visualize the number.

				
					JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,shuffle;
int counter = 0;
JLabel counterLabel;
				
			

Creating Constructor

When you start the game, the first thing you will see is a new game window. Let’s set it up. Because the Puzzle class inherits (extends) from JFrame, it can call JFrame methods like setSize() and add(element).

				
					Puzzle(){
   setSize(400,400);
   setLayout(null);
   setVisible(true);
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				
			

It is 400×400 pixels in size (which you can customize to your preference) and will close when you click the X button on the top right.

Next, you need to initialize all the elements.

				
					b1 = new JButton("1");
b2 = new JButton(" ");
b3 = new JButton("3");
b4 = new JButton("4");
b5 = new JButton("5");
b6 = new JButton("6");
b7 = new JButton("7");
b8 = new JButton("8");
b9 = new JButton("2");
shuffle = new JButton("Shuffle!");
counterLabel = new JLabel("Clicks: 0");
				
			

Then add these elements to the window and set proper bounds.

				
					add(b1);add(b2);add(b3);add(b4);add(b5);add(b6);add(b7);add(b8);add(b9); add(shuffle);
Container contentPane = this.getContentPane();
contentPane.add(counterLabel);

b1.setBounds(90,60,50,40);
b2.setBounds(160,60,50,40);
b3.setBounds(230,60,50,40);
b4.setBounds(90,115,50,40);
b5.setBounds(160,115,50,40);
b6.setBounds(230,115,50,40);
b7.setBounds(90,170,50,40);
b8.setBounds(160,170,50,40);
b9.setBounds(230,170,50,40);
shuffle.setBounds(135,245,100,40);
counterLabel.setBounds(145,15,180,40);
				
			

Now run the program. It should look like this:

Sliding-Puzzle

The next step is optional, but it will improve the visual appeal of your game. It involves changing the background color of the puzzle pieces, the font, and the font size. You can select your own or use the ones from this example.

				
					shuffle.setBackground(Color.LIGHT_GRAY);

b1.setBackground(Color.decode("#5adbb5"));
b2.setBackground(Color.decode("#5adbb5"));
b3.setBackground(Color.decode("#5adbb5"));
b4.setBackground(Color.decode("#5adbb5"));
b5.setBackground(Color.decode("#5adbb5"));
b6.setBackground(Color.decode("#5adbb5"));
b7.setBackground(Color.decode("#5adbb5"));
b8.setBackground(Color.decode("#5adbb5"));
b9.setBackground(Color.decode("#5adbb5"));

b1.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 18));
b2.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 18));
b3.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 18));
b4.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 18));
b5.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 18));
b6.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 18));
b7.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 18));
b8.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 18));
b9.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 18));
shuffle.setFont(new Font(Font.DIALOG, Font.PLAIN, 18));
counterLabel.setFont(new Font(Font.DIALOG, Font.PLAIN, 18));

				
			

In the end, you get:

Finally, attach an action listener to every button:

				
					b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
shuffle.addActionListener(this);
}
				
			

And the Puzzle constructor is done.

Adding Action

The Action Listener is a simple event handler with only one method – actionPerformed (ActionEvent e). It is used to define what should happen when a user performs a certain operation. It registers the event of clicking a button, for example. The ActionListener is one for all buttons, so you have to make a separate if statement for each one of them in the actionPerformed method. Let’s start with the Shuffle button.

				
					public void actionPerformed(ActionEvent e){
   if(e.getSource() == shuffle){
       String s = b4.getText();
       b4.setText(b9.getText());
       b9.setText(s);
       s = b1.getText();
       b1.setText(b5.getText());
       b5.setText(s);
       s = b2.getText();
       b2.setText(b7.getText());
       b7.setText(s);
       counter = -1;
       counterLabel.setText("Clicks: 0");
   }
				
			

The logic of moving puzzle pieces is simple: instead of physically moving the pieces around the board, you simply change their text.

				
					if(e.getSource() == b1){
   String s = b1.getText();
   if(b2.getText().equals(" ")){ b2.setText(s); b1.setText(" ");}
   else if(b4.getText().equals(" ")){ b4.setText(s); b1.setText(" ");}
}
				
			

Let’s break the process into a few steps:

  1. Extract the text from the current button;
  2. Determine which of the adjacent buttons has no text;
  3. Substitute the empty text with the extracted one;
  4. Set the text of the current button to an empty string.

Follow this logic for the other pieces as well.

				
					if(e.getSource() == b2){
   String s=b2.getText();
   if(b1.getText().equals(" ")){ b1.setText(s); b2.setText(" ");}
   else if(b3.getText().equals(" ")){ b3.setText(s); b2.setText(" ");}
   else if(b5.getText().equals(" ")){ b5.setText(s); b2.setText(" ");}
}
if(e.getSource() == b3){
   String s=b3.getText();
   if(b2.getText().equals(" ")){ b2.setText(s); b3.setText(" ");}
   else if(b6.getText().equals(" ")){ b6.setText(s); b3.setText(" ");}
}
if(e.getSource() == b4){
   String s=b4.getText();
   if(b1.getText().equals(" ")){ b1.setText(s); b4.setText(" ");}
   else if(b7.getText().equals(" ")){ b7.setText(s); b4.setText(" ");}
   else if(b5.getText().equals(" ")){ b5.setText(s); b4.setText(" ");}
}
if(e.getSource() == b5){
   String s=b5.getText();
   if(b2.getText().equals(" ")){ b2.setText(s); b5.setText(" ");}
   else if(b4.getText().equals(" ")){ b4.setText(s); b5.setText(" ");}
   else if(b6.getText().equals(" ")){ b6.setText(s); b5.setText(" ");}
   else if(b8.getText().equals(" ")){ b8.setText(s); b5.setText(" ");}
}
if(e.getSource() == b6){

   String s=b6.getText();
   if(b9.getText().equals(" ")){ b9.setText(s); b6.setText(" ");}
   else if(b3.getText().equals(" ")){ b3.setText(s); b6.setText(" ");}
   else if(b5.getText().equals(" ")){ b5.setText(s); b6.setText(" ");}

}
if(e.getSource() == b7){
   String s=b7.getText();
   if(b4.getText().equals(" ")){ b4.setText(s); b7.setText(" ");}
   else if(b8.getText().equals(" ")){ b8.setText(s); b7.setText(" ");}

}
if(e.getSource() == b8){
   String s=b8.getText();
   if(b7.getText().equals(" ")){ b7.setText(s); b8.setText(" ");}
   else if(b9.getText().equals(" ")){ b9.setText(s); b8.setText(" ");}
   else if(b5.getText().equals(" ")){ b5.setText(s); b8.setText(" ");}
}

				
			

The last button marks the end of the puzzle, so it should also include a statement that checks whether it has been solved. For that to happen, the pieces must be put in the following order:
1 2 3
4 5 6
7 8 empty

Therefore, the simplest way to verify this order is to check the text on each button.

				
					if(e.getSource() == b9){
   String s=b9.getText();
   if(b6.getText().equals(" ")){ b6.setText(s); b9.setText(" ");}
   else if(b8.getText().equals(" ")){ b8.setText(s); b9.setText(" ");}

   if(b1.getText().equals("1")&&b2.getText().equals("2")&&b3.getText()
           .equals("3")&&b4.getText().equals("4")&&b5.getText().equals("5")
           &&b6.getText().equals("6")&&b7.getText().equals("7")&&b8.getText()
           .equals("8")&&b9.getText().equals(" ")){
       JOptionPane.showMessageDialog(Puzzle.this,"YOU WON!\n" + "You clicked: " + counter + " times.");
   }
}
				
			

You can add a dialog box with a custom message that will pop up when the puzzle is solved. To do that, use the JOptionPane.showMessageDialog() method.

Finally, increase the counter integer and update the label’s text to the new value at the end of the if statements.

				
					counter++;
counterLabel.setText("Clicks: " + counter);
				
			

Your sliding puzzle is ready!

Conclusion

By following this tutorial, you have programmed your own sliding puzzle in Java using simple if statements and some basic functionality of the Swing library. Explore the library’s other features and think of ways to expand your project by adding, for example, a scoreboard, an option to switch between different puzzle sizes, randomization of the shuffle, etc. And don’t forget to upload it to your GitHub profile.

To check out the final code and compare it to yours, click the link below.

If you need any help or advice, leave a comment.

Lesson Topics

In this tutorial we cover the following steps:
  • Preparing Variables
  • Creating Constructor
  • Adding Logic to Action Listener

The post Making A Sliding Puzzle in Java: Step-by-step Guide [Project Tutorials] appeared first on SoftUni Global.

]]>
https://softuni.org/project-tutorials/making-a-sliding-puzzle-in-java/feed/ 0
Acing The Web Developer Interview – A Guide [Dev Talks] https://softuni.org/dev-talks/web-developer-interview-guide/ https://softuni.org/dev-talks/web-developer-interview-guide/#respond Fri, 30 Sep 2022 14:26:57 +0000 https://softuni.org/?p=23287 This article will walk you through the steps of the interview process, giving you some samples of the questions you can expect and advice on how to answer them.

The post Acing The Web Developer Interview – A Guide [Dev Talks] appeared first on SoftUni Global.

]]>

There are a lot of steps you need to take before going to an interview. Even when you complete them all, applying for your first programming job can be an intimidating process, especially when you do not have any professional experience to back up your technical knowledge. A good way to showcase your practical competence is to set up a GitHub profile with all the projects you have completed so far.  In addition to assessing your coding skills, an interview serves as an opportunity for the recruiter to get to know you better and determine whether or not you would fit well into the company culture.

Although every organization has a different interviewing policy, the process usually includes the following steps: 

  • Initial Conversation with a hiring manager;
  • Technical Interview with a software developer;
  • Coding Challenges.

There are three general groups of questions corresponding to each stage of the interview process – personal, technical, and practical. To give you a better idea of what to expect, we made a list of the most common ones and included hints on how to best answer them. 

Personal Questions

In most cases, you will first speak with a hiring manager, who will ask you open-ended questions common to most job interviews, irrespective of the industry:

  • Tell me about yourself.
    Hint: You do not have to go into too many personal details. After all, you are there on a business matter. Share what sparked your interest in programming and what you expect to gain from the role you are applying for. Explain why you are a good fit for this position, and which of your skills and abilities would benefit the company and make you stand out as a candidate. 
  • Where do you see yourself in five (or ten) years time?
    Hint:
    The purpose of this question is to find out if you plan in the long term and whether your goals align with the position you are applying for. 
  • How did you hear about our company?
    Hint: Be prepared with specific information about the company. Look for information in forums, blogs, on the company’s Web site, etc. Research their goals and mission and the position you are applying for and mention how they align with your future plans.
  • What are your greatest strengths and weaknesses?
    Hint: Mention actual personal qualities that are relevant to the current position. Give context, details, and an example from your own experience or a potential situation in which you would use these strengths to get through a challenge.
    When talking about your weaknesses you want to give a well-thought answer that does not sound too rehearsed. The best way is to give an example of a small shortcoming you are working on overcoming. Share what you have learnt from the process and how you will use the experience in your future work.
  • What are your hobbies and interests?
    Hint: To dig deeper into your character, the hiring manager might ask you about your interests outside of work. Mention hobbies that you are really into, but make sure to clarify that they will not affect your dedication to the job. Sharing your interests outside of work is a genuine way to show your personality and connect with the interviewer. 

Technical Questions

The interview will continue with a test of your technical knowledge in the form of some behavioral and theoretical questions. At this stage, you are likely to have a software engineer who will ask you progressively harder theoretical questions. Although the technical part of an interview is highly dependent on the job requirements, there are some general questions at the start, like:

  • Why did you choose this programming language, and what interests you about it?
    Hint: Express your understanding of the technology you chose. Describe its features, advantages, and disadvantages, as well as the applications you can develop with it. To show that you have at least a basic understanding of other languages, you can also draw comparisons with some of them.
  • Describe the steps you take to develop a program, from getting the assignment or an initial idea to its final execution.
    Hint: Explain the actual sequence of steps you take when developing a program. Interviewers are particularly interested in your project planning process, what coding techniques you use, and whether you follow the best practices that guarantee high-quality and readable code.
  • How do you debug your code and approach problems?
    Hint: Since troubleshooting and debugging are crucial components of a software engineer’s work, it is important to describe how you handle issues. This will demonstrate your level of logical and algorithmic thinking and problem-solving skills.

The more in-depth questions are usually theoretical, so it is entirely up to you to be prepared beforehand. This is a sample list of technical questions for four of the most popular programming languages for web development, as well as a separate section about Object Oriented Programming (OOP).

Java

  • What are the main features of Java?
  • Why is Java platform-independent?
  • What is the difference between the JDK, JRE, and JVM?
  • How do Heap and Stack memory differ?
  • Explain the access modifiers used in Java.
  • What is the role of the garbage collector?
  • What is Final word in Java used for?
  • What is the difference between Stack and Queue?

C#

  • What are the main features of C#?
  • How is C# compiled?
  • What is the difference between managed and unmanaged code?
  • Explain the different types of classes.
  • Explain the access modifiers used in C#.
  • What are boxing and unboxing in C#?
  • What are the main differences between Array and ArrayList in C#?
  • What is the difference between throw exception and throw clause? 

Python

  • What are the main features of Python?
  • What is the difference between list and tuples?
  • What are the built-in data types?
  • What is a namespace?
  • What is PEP?
  • How is Python interpreted?
  • What are local and global variables?

JavaScript

  • What are the main features of JavaScript?
  • What are the data types in JS?
  • What is the difference between ViewState and SessionState?
  • What are JavaScript Cookies?
  • What is the difference between pop() and shift() method?
  • What are the disadvantages of using innerHTML?
  • What are the different types of errors in JavaScript?
  • What is the Strict Mode in JavaScript, and how can it be enabled?

OOP

  • What are the principles of OOP?
  • What are the features of OOP?
  • What is the Singleton Class and how to implement it?
  • What is inheritance?
  • What is the difference between a class and an object?
  • Explain superclass and subclass.
  • What is the difference between method overloading and method overriding?

These questions can be asked specifically about your projects, in case you have any uploaded on your GitHub profile. The interviewer might be interested in discussing the technologies and practices that you used to develop them.

Coding Challenges

In addition to the theoretical questions, you might be given a problem to solve. It can be a take-home assignment or a coding challenge to do live during the interview. Make sure you are familiar with the syntax of the programming language required for the position you are applying for, because a coding challenge may require you to debug a block of code or determine what its result would be. It is possible that the code is intentionally made confusing in order to gauge how you would respond when faced with a challenge or in a stressful situation. In this case, the most important things are to stay calm, fight off any anxiety, and try to find a logical and well-structured solution to the problem. Demonstrating genuine enthusiasm for coding, algorithmic thinking, and a desire to learn is sometimes more important than coming up with the right answer.

Listed below are some basic junior coding challenges and hints on how to resolve them:

  • Factorial
    The factorial of a positive integer is the sum of the multiplication of all the integers smaller than that positive integer. For example:
    4! = 4*3*2*1 = 24
    5! = 5*4*3*2*1 = 120
    Task: Write a program that takes a positive integer as an input and calculates the factorial of that number.
    Hint: To solve this problem, use either a loop or recursion.
Factorial-Formula
  • Palindrome
    A palindrome is a sequence of characters which reads the same backward as forward. For example, “radar”, “rotator”, and even longer phrases like “pull up if I pull up”.
    Task: Write a program that takes a string as an input and returns if it is a palindrome.
    Hint: You can: 
      1. Check if the input is a string;
      2. Turn it to lower or uppercase;
      3. Reverse it (using a method or a loop);
      4. Check if the reversed string is equal to the input string;
      5. Return the result.
  • FizzBuzz
    Task: Write a program that counts the numbers from 1 to 100 on a new line.
    If the number is divisible by 3, print “Fizz”.
    If the number is divisible by 5, print “Buzz”.
    If the number is divisible by both 3 and 5, print “FizzBuzz”.
    Otherwise, print the number.
    Hint: Make a loop that iterates over the numbers, and for every number, check the given conditions using the remainder operator. Be careful with the order of conditions because it can be crucial to the end result.

  • Fibonacci
    The Fibonacci sequence is a series of integers (the Fibonacci numbers) like the following one:
    0, 1, 1, 2, 3, 5, 8, 13, 21, 34
    Every number after the first two (0 and 1) is the sum of the two preceding ones:
    2 is the sum of the preceding two numbers – 1+1
    0, 1, 1, 2, 3, 5, 8, 13, 21, 34
    3 is the sum of the preceding two numbers – 1+2
    And so on.
    Task: Write a program that takes a positive integer N as an input and returns the N-th element of the Fibonacci sequence.
    Hint: The easiest way to solve this is to use recursion, like in this example of Java code:
				
					public int fib(int n){

if (n<2) return n;

return fib(n-1) + fib(n-2);
}
				
			
  • Anagram
    Anagrams are words with the same number of letters, but they may be arranged differently. For example, race and care, listen and silent.
    Task: Write a program that receives two strings as an input and returns true if they are anagrams.
    Hint: Sorting the two words and then comparing them is the quickest way, but it is not the best solution because usually sorting algorithms are time- and memory-consuming.
    Another approach is to generate HashMaps of both words and then compare them. Use the HashMaps to check if they contain the same elements and if these elements occurred the same number of times in both maps.

Conclusion

Most people are anxious when going to an interview, especially if it is their first time.
Preparing in advance will always work in your favor giving you a leg up over the other candidates and the chance to make a good impression. Having an idea of the general process will help you come up with the best answers to the most common personal, technical, and practical questions when interviewing for a software engineer position.

The post Acing The Web Developer Interview – A Guide [Dev Talks] appeared first on SoftUni Global.

]]>
https://softuni.org/dev-talks/web-developer-interview-guide/feed/ 0
How To Make A Pong Game in C#: Step-by-step Guide [Project Tutorials] https://softuni.org/project-tutorials/how-to-make-a-pong-game-in-csharp-guide/ https://softuni.org/project-tutorials/how-to-make-a-pong-game-in-csharp-guide/#respond Thu, 01 Sep 2022 14:15:30 +0000 https://softuni.org/?p=23082 In this edition of the Project Tutorial series, we will create a simple Pong game with C#.

The post How To Make A Pong Game in C#: Step-by-step Guide [Project Tutorials] appeared first on SoftUni Global.

]]>

Pong is a two-dimensional sports game that is similar to table tennis. It is one of the earliest video games, first released in 1972. Since then, it has been recreated multiple times in different programming languages. Today, you will learn how to make your own version of the game using simple programming concepts in C#.

Let’s begin.

Creating the Field

First, you need to prepare the field with an upper and a lower border and two rackets. Declare two constants of type int that define the dimensions of the field – fieldWidth and fieldLength. To visualize the upper and the lower border, use the string method Repeat on the fieldTile character variable.

				
					const int fieldLength = 50, fieldWidth = 15;
const char fieldTile = '#';
string line = string.Concat(Enumerable.Repeat(fieldTile, fieldLength));
				
			

Then create the game loop and print the borders on the console. The first line starts from coordinates 0,0 and the second one – 0, fieldWidth(15).

				
					while(true) 
{ 
    Console.SetCursorPosition(0,0);
    Console.WriteLine(line);

    Console.SetCursorPosition(0,fieldWidth);
    Console.WriteLine(line);
}

				
			

Next, make a variable for the rackets’ size – racketLength, for the character used to visualize them – racketTile, and for their positions – leftRacketHeight and rightRacketHeight.

				
					const int racketLength = fieldWidth / 4;
const char racketTile = '|';
            
int leftRacketHeight = 0;
int rightRacketHeight = 0;
				
			

To make the rackets appear on the field,add a for loop in the game loop.

				
					for(int i = 0; i < racketLength; i++)
{
    Console.SetCursorPosition(0, i + 1 + leftRacketHeight);
    Console.WriteLine(racketTile);
    Console.SetCursorPosition(fieldLength - 1, i + 1 + rightRacketHeight);
    Console.WriteLine(racketTile);
}
				
			

Player Movement

Make a loop that will continue until a key is pressed. After the loop, check which key has been pressed using a switch and update the rackets’ positions based on that. Clear the previous positions with another for loop.

				
					while(!Console.KeyAvailable)
{
    
}
           
//Check which key has been pressed
switch(Console.ReadKey().Key)
{
    case ConsoleKey.UpArrow:
    if(rightRacketHeight > 0)
    {
        rightRacketHeight--;
    }
    break;

    case ConsoleKey.DownArrow:
    if(rightRacketHeight < fieldWidth - racketLength - 1)
    {
        rightRacketHeight++;
    }
    break;

    case ConsoleKey.W:
    if(leftRacketHeight > 0)
    {
        leftRacketHeight--;
    }
    break;
    
    case ConsoleKey.S:
    if(leftRacketHeight < fieldWidth - racketLength - 1)
    {
        leftRacketHeight++;
    }
    break;
}

//Clear the rackets’ previous positions
for(int i = 1; i < fieldWidth; i++)             
{
Console.SetCursorPosition(0,i);
Console.WriteLine(" ");
Console.SetCursorPosition(fieldLength - 1,i);
Console.WriteLine(" ");
}
				
			

Adding a Ball

What you need to know about the ball is its coordinates, the character representation on the field, and its direction.

				
					int ballX = fieldLength / 2;
    int ballY = fieldWidth / 2;
    const char ballTile = 'O';

    bool isBallGoingDown = true;
    bool isBallGoingRight = true;
				
			

Let’s go back to the empty while loop that waits for a key to be pressed. It has to update the ball’s position.

				
					while(!Console.KeyAvailable)
{
    Console.SetCursorPosition(ballX, ballY);
    Console.WriteLine(ballTile);
    Thread.Sleep(100); //Adds a timer so that the players have time to react
    
    Console.SetCursorPosition(ballX, ballY);
    Console.WriteLine(" "); //Clears the previous position of the ball
    
    //Update position of the ball
    if(isBallGoingDown)
    {
    ballY++;
    } else
    {
    ballY--;
    }
    if(isBallGoingRight)
    {
    ballX++;
    } else
    {
    ballX--;
    }
}
				
			

However, this code does not limit the movement of the ball to the borders of the field. You need to add more conditions to the same while loop and declare variables to store the players’ points.

				
					int leftPlayerPoints = 0;
int rightPlayerPoints = 0;

				
			
				
					if(ballY == 1 || ballY == fieldWidth - 1)
{
isBallGoingDown = !isBallGoingDown; //Change direction
}

if(ballX == 1)
{
    //Left racket hits the ball and it bounces
   if(ballY >= leftRacketHeight + 1 && ballY <= leftRacketHeight + racketLength) 
   {
       isBallGoingRight = !isBallGoingRight;
   }
   else //Ball goes out of the field; Right player scores
   {
      rightPlayerPoints++;
      ballY = fieldWidth / 2;
      ballX = fieldLength / 2;
      Console.SetCursorPosition(scoreboardX, scoreboardY);
      Console.WriteLine($"{leftPlayerPoints} | {rightPlayerPoints}");
      if(rightPlayerPoints == 10)
      {
          goto outer;
      }
   }
}

if(ballX == fieldLength - 2)
{
    //Right racket hits the ball and it bounces
   if(ballY >= rightRacketHeight + 1 && ballY <= rightRacketHeight + racketLength) 
   {
       isBallGoingRight = !isBallGoingRight;
   }
   else //Ball goes out of the field; Left player scores
   {
      leftPlayerPoints++;
      ballY = fieldWidth / 2;
      ballX = fieldLength / 2;
      Console.SetCursorPosition(scoreboardX, scoreboardY);
      Console.WriteLine($"{leftPlayerPoints} | {rightPlayerPoints}");
      if(leftPlayerPoints == 10)
      {
          goto outer;
      }
       
   }
}
				
			

Scoreboard Visualization

To add a scoreboard, you need variables that store its position.

				
					int scoreboardX = fieldLength / 2 -2;
int scoreboardY = fieldWidth + 1;

				
			

The scoreboard is printed on the console every time a player increases their score. Let’s say the game ends when one of the players reaches 10 points. You need to break out of the game loop with the goto command.

				
					//Left Player
leftPlayerPoints++;
ballY = fieldWidth / 2;
ballX = fieldLength / 2;
Console.SetCursorPosition(scoreboardX, scoreboardY);
Console.WriteLine("${leftPlayerPoints} | {rightPlayerPoints}")

if(leftPlayerPoints == 10)
{
      goto outer;
}

//Right Player
rightPlayerPoints++;
ballY = fieldWidth / 2;
ballX = fieldLength / 2;
Console.SetCursorPosition(scoreboardX, scoreboardY);
Console.WriteLine("${leftPlayerPoints} | {rightPlayerPoints}")
if(rightPlayerPoints == 10)
{
      goto outer;
}

				
			

Outside of the game loop put a marker, clear the console and reset the cursor. Check who the winner is and print the appropriate message.

				
					outer:;
        Console.Clear();
        Console.SetCursorPosition(0,0);
        
        if(rightPlayerPoints == 10)
        {
        Console.WriteLine("Right player won!");
        } 
        else 
        {
        Console.WriteLine("Left player won!");
        }
				
			

If you’ve followed all the steps your project should be finished and working now. You can always adjust the values of the variables. For example, you can make the field bigger or smaller or increase the speed of the ball to make the game more challenging.

To check out the final code and compare it to yours click the link below.

Lesson Topics

In this tutorial we cover the following steps:
  • Creating a Field
  • Implementing Player Movement
  • Adding a Ball
  • Scoreboard Visualization

The post How To Make A Pong Game in C#: Step-by-step Guide [Project Tutorials] appeared first on SoftUni Global.

]]>
https://softuni.org/project-tutorials/how-to-make-a-pong-game-in-csharp-guide/feed/ 0
All The New JavaScript Features Coming Up with ECMAScript 2022 https://softuni.org/dev-talks/all-the-new-javascript-features-coming-up-with-ecmascript-2022/ https://softuni.org/dev-talks/all-the-new-javascript-features-coming-up-with-ecmascript-2022/#respond Thu, 25 Aug 2022 08:48:25 +0000 https://softuni.org/?p=22801 In this article, you will learn about the new JavaScript features of 2022 and how to use them to ease your work as a software developer.

The post All The New JavaScript Features Coming Up with ECMAScript 2022 appeared first on SoftUni Global.

]]>

The thirteenth edition of ECMAScript Language specification was officially approved on June 22, 2022. With its release, new features were added to the JavaScript language:

  • Method .at();
  • Object.hasOwn();
  • RegExp: match indices(‘d’ flag);
  • Error: .cause;
  • New members of Classes;
  • Private Slot Checks;
  • Top-level Await.

Now let’s find out more about each new feature.

Method .at()

The method .at() is supported by indexable values like Array, String, or TypedArray. It takes a positive or negative integer value and returns the element at the given index. 

In this example, there is an array with three elements, which means that its length is 3. The first element is at index 0 and the last is at index array length -1 (in this example at index 2).

To check what the element at a certain index is, use the bracket operator (animals[0]). For indexes out of the range, the program returns “Undefined“.

				
					let animals = ["Cat", "Dog", "Cow"];

console.log(animals[0]);
console.log(animals[animals.length - 1]) 
console.log(animals[animals.length])

//Cat
//Cow
//undefined

				
			

The new feature works exactly like the bracket operator but it allows negative indexing of elements. The last element is accessed easily by replacing animals[animals.length – 1] with animals.at(-1)

				
					let animals = ["Cat", "Dog", "Cow"];

console.log(animals.at(0));
console.log(animals.at(-1));

//Cat
//Cow

				
			
				
					//Example with a String
let string = "Hello, World!";

console.log(string.at(-1));

//!

				
			

Object: .hasOwn()

Object.hasOwn() returns true if the specified object has the indicated property as its own property. If the property is inherited or does not exist, the method returns false.

Object.hasOwn() is intended as a replacement of Object.hasOwnProperty()

Before:

				
					let user = {
name: 'John Doe',
role: 'Admin'
};

console.log(user.hasOwnProperty('role'));
console.log(user.hasOwnProperty('age'));

//true
//false


				
			

After:

				
					let user = {
name: 'John Doe',
role: 'Admin'
};

console.log(Object.hasOwn(user, 'role'));
console.log(Object.hasOwn(user, 'age'));

//true
//false

				
			

RegExp: match indices(‘d’ flag)

ECMA Script 2022 introduced a new /d flag for Regular Expressions. It provides some additional information about the start and indices position end of each match in the input string.

Without the new feature the following information has been provided:

				
					let string = 'hello1helloAll';
let regEx = /hello(\w)/g;
let result = [...string.matchAll(regEx)];
console.log(result[0]);
//[ 'hello1', '1', index: 0, input: 'hello1helloAll', groups: undefined ]

let string = 'hello1helloAll';
let regEx = /hello(\w)/g;
let result = [...string.matchAll(regEx)];
let regEx2 = /hello(\w)/dg;
let result2 = [...string.matchAll(regEx2)];
console.log(result2[0]);


				
			

With the /d flag there is an array with the indices of the different elements that match the regex:

				
					[
  'hello1',
  '1',
  index: 0,
  input: 'hello1helloAll',
  groups: undefined,
  indices: [ [ 0, 6 ], [ 5, 6 ], groups: undefined ]
]


				
			

Error: .cause

With the Error .cause, you can add more essential information to the errors you receive. You should specify the error options as a second parameter, and with the “cause“ key you can pass the error that you want to chain.

Before:

				
					const weatherNow = async (city) => {
    try {
      const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=67a20d293903cbcf9aab38633b30fbf9`);
      const info = await response.json();
      const description = info.weather[0].description;
      return description;
    } catch (error) {
throw new Error('Something went wrong')
    }
  }
 
try {
    await weatherNow('');           //Empty string
} catch(error) {
    console.log(error);
}

//Error: Something went wrong
    //at weatherNow (<anonymous>:8:7)
    //at async <anonymous>:13:5

				
			

After:

				
					const weatherNow = async (city) => {
    try {
      const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=67a20d293903cbcf9aab38633b30fbf9`);
      const info = await response.json();
      const description = info.weather[0].description;
      return description;
    } catch (error) {
throw new Error('Something went wrong', { cause: error })
    }
  }
 
try {
    await weatherNow('');        //Empty String
} catch(error) {
    console.log(error.cause);
}

//TypeError: Cannot read properties of undefined (reading '0')
    //at weatherNow (<anonymous>:5:39)
    //at async <anonymous>:13:5


				
			

New Members of Classes

Static class fields and methods are not used on instances of a class. Instead, they can be called on the class itself and are declared using the static keyword. Static methods are often utility functions and helpers, whereas static properties are useful for caches, fixed-configuration, or any other data we do not need to be replicated across instances.

Before:

				
					class User {
    firstName = 'Jon';
};
  
console.log(User.firstName); 
  
//undefined

				
			

After:

				
					class User {
    static firstName = 'Jon';
};

console.log(User.firstName); 
  
//Jon

				
			

Private Slot Checks

EcmaScript 2022 added new features such as private instance fields, methods, and accessors. To initialize a private method or a field before you had to add an underscore at the beginning of its name, but this did not guarantee that the method/field will be private. Now, you just need to add a # at the beginning of the method name to have it declared as private.

It looks like this:

				
					class User {
    firstName = 'John';
    lastName = 'Doe';
    #role = 'Admin';
}
 
const adminUser = new User();
console.log(adminUser.role); 
  
//undefined
				
			
				
					class User {
    firstName = 'John';
    lastName = 'Doe';
    role = 'Admin';
    #sayHi() {
        return this.firstName + ' ' + this.lastName + ' with role ' + this.role + ' says Hi!';
    }
}
 
  const adminUser = new User();
  console.log(adminUser.sayHi());      
  
//TypeError: adminUser.sayHi is not a function

				
			

Top-level Await

Before ECMAScript 2022 await could only be used in the scope of asynchronous functions. Now the await keyword can be used outside of an async function within a JavaScript module. This means that a module waits for its child modules that use await to execute before it runs itself.

				
					const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=london&appid=67a20d293903cbcf9aab38633b30fbf9`);
const info = await response.json();
const description = info.weather[0].description;
console.log(description);
				
			

We will receive an error:

				
					SyntaxError: await is only validin async functions and the top-level bodies of modules
				
			

With ECMAScript 2022  it works fine and you will see the following:

				
					//clear sky
				
			

Conclusion

Nowadays when technology is rapidly evolving being up to date is an important part of working as a software developer.

The EcmaScript specification for 2022 contains some significant changes that aim to provide convenience and efficiency in programming by allowing you to write more expressive and concise code. After reading this post, you are now familiar with all of the new features and it is up to you to choose which of them to use into your JavaScript programming.

The post All The New JavaScript Features Coming Up with ECMAScript 2022 appeared first on SoftUni Global.

]]>
https://softuni.org/dev-talks/all-the-new-javascript-features-coming-up-with-ecmascript-2022/feed/ 0
Cybersecurity Expert On Phishing, Cyber Hygiene, And Device Safety [Dev Talks #4] https://softuni.org/dev-talks/cybersecurity-expert-on-phishing-cyber-hygiene-and-device-safety/ https://softuni.org/dev-talks/cybersecurity-expert-on-phishing-cyber-hygiene-and-device-safety/#respond Fri, 19 Aug 2022 13:05:33 +0000 https://softuni.org/?p=22868 Lyubomir Tulev, a cybercrime expert, shares valuable information about the types of malware and ways of dealing with them.

The post Cybersecurity Expert On Phishing, Cyber Hygiene, And Device Safety [Dev Talks #4] appeared first on SoftUni Global.

]]>

Let us introduce you to Lyubomir Tulev. He is a cybercrime expert who has been working internationally for more than 10 years on cybercrime investigations in countries like New Zealand, Russia and many others across Europe. In 2015 he was recognized by the Federal Bureau of Investigation (FBI) as one of the top 10 international cybercrime experts. He is in the private sector now and his work involves penetration testing, social engineering, consultancy and cyber forensics. He is also a trainer for Information Security Management course at SoftUni. Lyubomir shared more about his professional motivation as well as practical tips that will help you protect yourself and your devices from cyber attacks.

Helping And Protecting People Has Always Been His Driving Force

“The fact that I have been involved in the police structure for seven years means that I have been first inspired to help and protect people.”

After 7 years on the force, he decided move to the private sector in search of career growth. The inspiration behind this move was a friend. Lyubomir still helps people but his main focus is on companies in need of strengthening their cyber security.

Basic Measures Against Cyber Attacks

Cyber-Security-Hacker

“The Coronavirus pandemic has spread across the globe and the one positive thing about this is the opportunity to rediscover the methods of transformation of our digital lives. On the other side, it possesses many obstacles coming from the hackers.”, says Lyubomir.

He explains that now, when people are spending more time at their homes working remotely, hackers are more likely to attack their devices and business. In order to protect from potential cyber attacks, people have to take basic measures like:

  • Securing the Wi-Fi connection and monitoring the connected devices;
  • Using VPN to access business infrastructure;
  • Securing the endpoint device – laptops, tablets, mobile phones;
  • Being aware of phishing emails and other possible cyber attacks.

“In cyber security, there is a saying that the employees are actually the weakest possible link in the security chain within an organization. I don’t really think so. My idea is that we have to look at the emloyees as a firewall.”, says Lyubomir

According to him, raising awareness among employees about cyber security is important for business because if they are well educated on the topic, they can become a ‘human firewall‘ that protects the company from within.

How To Recognize A Phishing Email

“Usually, the phishing emails are giving a sense of urgency. This is because hackers do not want you to have enough time to think about it carefully.”

He explains that there are three types of phishing emails depending on their content:

  • With attachments;
  • With a phish link;
  • With a text that requires you to send valuable information.
Cyber-Security-Email

“Usually, the phishing emails are giving a sense of urgency. This is because hackers do not want you to have enough time to think about it carefully.”

He explains that there are three types of phishing emails depending on their content:

  • With attachments;
  • With a phish link;
  • With a text that requires you to send valuable information.

If you receive an email with an attachment, Tulev advises to download it, check it with some publicly available software for virus scanning, and then finally open it.

If there is a link that you are instructed to follow, do not click on it, instead hover the mouse over it. In the bottom left corner of the browser you will see the address this link will take you, and compare if the destination matches the one stated in the email.

The last possible scenario is receiving a malicious email with just text. In this case, open the email header and check – if you reply, does it go back to the same address it says it came from? If there is a third party listed there, this email is probably phishing.

Common Types Of Cyber Attacks

“If we are talking about businesses, the most common cyber attack is the ransomware. It is vast majority of cases that we are dealing with.”, shares Lyubomir.

The ransomware encrypts all available files on the attacked device. The hacker then wants a certain amount of money to decrypt the files. However, there is no guarantee that they will do it after you pay the ransom. This is why having a backup stored remotely is so important.

Cyber-Security-Password

He adds that, “Other cyber attacks that happen to businesses and people are usually related to their credentials. Be very careful with your passwords. They are an object of many types of attacks like credential harvesting, password spraying, and brute forcing.

We, as cyber security professionals, always have to think about three elements of the information: confidentiality, integrity, availability.”

Lyubomir further explains what this means:

  • Confidentiality – to protect the data at any stage, make a remote backup, and set up access control;
  • Integrity – to not let a hacker modify the information and to protect the backend to avoid SQL injections;
  • Availability – to make sure the data is available when needed and use cloud storage.

To Be Aware Is To Be Protected

Lyubomir stresses: “Be aware what the attackers may use in order to take advantage of you. Train your people and yourself on what attack vectors are and how to recognize them in order to protect yourselves better.”

He adds that there are more examples of social engineering attack vectors like USB flash drives, smishing (SMS), and vishing (voice-using frauds).

How To Become A Cybersecurity Expert

Lyubomir has some advice for everyone interested in becoming a cybersecurity specialist: “When you put a lot of effort to improve yourself in one specific field of cyber security, you will become an expert only in this field, not in the cyber security generally. If you want to become an expert on cyber security you have to put a lot of effort in different fields like cyber forensics, penetration testing and consultancy.”.

“Businesses are now thinking more and more about digitalizing. This means that they will need the consultancy of cyber security experts. So, yes, I definitely foresee that the demand of cyber securty professionals will grow in the next couple of years.”, says Lyubomir.

The post Cybersecurity Expert On Phishing, Cyber Hygiene, And Device Safety [Dev Talks #4] appeared first on SoftUni Global.

]]>
https://softuni.org/dev-talks/cybersecurity-expert-on-phishing-cyber-hygiene-and-device-safety/feed/ 0
How to Build and Use Problem-solving Skills [Dev Concepts #41] https://softuni.org/dev-concepts/how-to-build-and-use-problem-solving-skills/ https://softuni.org/dev-concepts/how-to-build-and-use-problem-solving-skills/#respond Fri, 22 Jul 2022 13:32:30 +0000 https://softuni.org/?p=22676 In this lesson, you will learn about problem solving and algorithmic thinking and other fundamental skills of software developers, as well as some approaches to solving tech problems.

The post How to Build and Use Problem-solving Skills [Dev Concepts #41] appeared first on SoftUni Global.

]]>

To become a skilful developer means not only being familiar with a programming language or software but also having a set of skills that are fundamental to the software development process. These skills can be classified into four groups :

  • Coding skills;
  • Algorithmic thinking and problem solving skills;
  • Fundamental software development concepts;
  • Programming languages and software technologies.

Technical Skills

The skill of coding is knowledge of the basic concepts of programming. They are universal and once learned, can be applied in many programming languages. The programming language does not matter to the ability to code.

You need to know how to:

  • Use development environments (the so-called IDEs) and developer tools;
  • Work with variables and data, calculations, conditional statements, loops and data structures;
  • Use functions, methods, classes and objects, programming APIs and libraries;
  • Troubleshoot and debug code.

 

Now that you are familiar with the foundations of programming, you need to put that knowledge together and plan every step of finding a solution to a problem. This will require your algorithmic thinking and problem-solving skills

Problem-Solving-Lamp

 

Algorithmic thinking is the ability to break a problem into a logical sequence of steps (called “algorithm”), to find a solution for every step (or break it further into sub-steps) and then assemble these steps into a working solution. 

Algorithmic thinking is similar to logical, engineering, mathematical, abstract, and problem solving. All these concepts are related to the ability to solve problems: to think logically, analyse the problems, and find and implement solutions. Problem solving is a more general skill, while algorithmic thinking is a more technical.

The fundamental computer science and software development concepts include many programming paradigms, essential software development knowledge and skills, and software engineering principles and concepts that developers typically acquire as they gain experience over time.

Some of these knowledge areas and concepts are:

  • Object-oriented programming (OOP);
  • Functional programming (FP);
  • Asynchronous programming ;
  • Relational and non-relational databases;
  • The concepts behind the Web technologies.

To implement your knowledge you need to be familiar with programming languages, software development technologies, software platforms, software libraries, development frameworks and developer tools.

On the graphic below you can see an example technology stack for a Java developer.

Example-Of-A-Java-Tech-Stack

Technologies are ever-changing and evolving, but these four groups of skills described above represent essential and stable knowledge since they will not change significantly over time. In fact, technologies are highly dependent on these skills.

Soft Skills

Soft skills are as important as the ones described above. They include the ability to communicate with people and work in a team which is essential since you as a developer will work on projects with your colleagues. You need to manage your time effectively, to be empathetic, adaptable and creative. Having attention to detail will increase your productivity at work and reduce the chances of error.

Tech Problem Solving

In the IT industry, a tech problem is often an assignment to design and implement a set of functionality which has certain input data and program state and produces output data and program state. 

Every tech problem has a goal. In programming, the goals are to design and write a working code, build an app or software system, which corresponds to the assignment and implement its requirements and functionality. Developers may encounter certain technical difficulties or limitations in designing and implementing the required functionality, like lack of resources, experience or knowledge. The process of problem solving includes finding a way to overcome these difficulties. This can be, for example, learning a new programming language, software library or framework.

Stages of Problem Solving

How to approach a tech problem?
You can see in the graphic below seven stages of resolving a problem.

Stages-Of-Problem-Solving

First of all, you need to define the problem. This involves gathering the requirements of the assignment.

After that, you analyse them. Here you should think about constraints, objects, processes and potential obstacles related to the problem. Based on a deeper understanding of the problem, you can extract the important information from the requirements and discard the non-important information, and explore its properties, which will be useful for building a solution.

The next step is to identify several solutions. You try to generate and explore different ideas and technical approaches on how to build a well-working solution. Then you analyse these ideas, their correctness, their strengths and weaknesses, their practical applicability and the costs of their implementation.   

After you have gathered some ideas you need to choose one of them. This is a decision-making process and depends mainly on the requirements, your capabilities and available resources.

After that, you need to plan and describe your actions for executing the chosen solution. You plan your algorithm. Technically, this means to write the definition of several functions, methods or classes, which will implement the chosen idea.

Sometimes planning of the algorithm is done together with its implementation, and there is no clear separation between the stages of algorithm design and algorithm implementation.

Once you have a clearly defined algorithm, you implement it. This means writing code to execute the planned steps. In software development, the implementation process includes also testing and debugging.

The last stage of problem solving is to review the results or test the solution with different input data and conditions. For software problems and apps, you need to perform testing of the code, feature by feature: to check for usual and unusual input data and conditions, check for edge cases and special cases.

Tips for Solving Problems

When it comes to solving a tech problem, the first and foremost important thing is understanding it. Take your time to read and analyse it thoroughly. Do not start to code immediately, because if you have not read the problem carefully, there is a chance of making hasty assumptions about the requirements.

Use a sheet of paper or other visualization tools. This will help you sketch your ideas fast and will improve your logical thinking. Squared paper is preferable. It works best for algorithmic problems. It helps build drawings, diagrams, tables and coordinate systems.

Problem-Solving-Paper-Pen

Write down the given input and the required output.
For example, if your task is to find all odd numbers of a given array ask yourself some questions:

  • What do I have?  →  An array and odd numbers.
  • What is an array and how does it work? What is an odd number? What data type should I use to store it?  →  These questions will help you understand the problem.
  • What is the end goal? → To filter odd numbers in the array and return it.
  • How can I do it?  →  You may have multiple answers to this question and they are your potential solutions. Write them down, compare their advantages and disadvantages and then choose one of them.

After you implement the code test and debug it if needed. Make sure that you have covered all cases. Then look back and try to optimize and simplify your code making it easier to understand.

Lesson Topics

In this tutorial, we cover the following topics:
  • Technical Skills;
  • Soft Skills;
  • Definition of a Tech Problem;
  • Stages of Problem Solving;
  • Tips for Solving Problems.

Lesson Slides

The post How to Build and Use Problem-solving Skills [Dev Concepts #41] appeared first on SoftUni Global.

]]>
https://softuni.org/dev-concepts/how-to-build-and-use-problem-solving-skills/feed/ 0
What is a Uniform Resource Locator (URL)? [Dev Concepts #40] https://softuni.org/dev-concepts/what-is-a-uniform-resource-locator-url/ https://softuni.org/dev-concepts/what-is-a-uniform-resource-locator-url/#respond Wed, 13 Jul 2022 14:03:00 +0000 https://softuni.org/?p=22193 After this lesson, you will understand what a Uniform Resource Locator (URL) is, how it is used, what the URL encoding rules are, and more.

The post What is a Uniform Resource Locator (URL)? [Dev Concepts #40] appeared first on SoftUni Global.

]]>

Uniform Resource Locator (URL) identifiers are unique addresses on the Internet.  A URL is a specific type of Uniform Resource Identifier (URI). It is used to reference Web pages and identify and transfer documents on the Web by providing an abstract identification of the resource’s location. This is why it is also known as a web address.

Structure of a URL

A URL is what you type in the browser address bar to request a specific resource. You can see the parts it consists of in the graphic below.

URL Structure

The first part of a URL specifies the protocol that the browser must follow to talk to the server. The protocol is used to access remote resources, such as files, documents, and streaming media. It can be http, https, ftp, sftp, or other. Usually, for webpages is used HTTP and HTTPS.

After the protocol is the host. The host is usually a domain name, but an IP address can also be used. It indicates the web server that you request resources from. 

The third part of the URL is the port This is an integer in the range of [0…65535] that comes from the underlying TCP protocol, which operates with port numbers. The port is a virtual point through which network communication happens. It can be omitted if the server uses default ports of the HTTP protocol which are 80 for HTTP and 443 for HTTPS.

The host and the port define the endpoint for establishing the connection with the server.

The next part of the URL is the path. It specifies the location of the web page, file, or other resources to which the user wishes to gain access. If you want to request a file from the Web server, this will be the full path to the file, relative to the server root folder.

After the path follows the query string, which is optional. It is separated from the path by a question mark symbol. It holds parameters passed in the URL which are separated from each other by an ampersand symbol.

The fragment is the last optional part of the URL. It follows after the “hash” symbol. For example, the URL can end with “#slides“, which instructs the Web browser to scroll to the section “slides” in the loaded HTML document. The fragment is never sent to the server with the request.

A rarely used URL format can also include authentication data, sent through the “Authorization” HTTP header. For example http://username:password@example.com/

Query String

The query string is an optional part of the URL. It contains data that is not part of the path structure.

For example, let’s look at this URL:

http://example.com/path/to/page?name=tom&color=purple

The query string is ?name=tom&color=purple

The query string is commonly used in searches and dynamic pages. It consists of name=value pairs separated by an ampersand delimiter. Names and values that hold special characters are URL-encoded

For example https://nakov.com/?s=Svetlin%20Nakov

URL Encoding

URL Escape Codes

Sometimes the query string parameters need to hold special characters like the “=” symbol or the “?” symbol. To maintain this, the query string needs character escaping, which means that some special characters are replaced by sequences of other characters. This is called “URL encoding“. URLs are encoded according to RFC 1738 standard, which describes the URLs). Normal URL characters (such as digits and Latin letters) have no special meaning in the URLs and are not encoded. Reserved URL characters have a special meaning and are encoded in order to be part of the URL without breaking it. This is done with the so-called “percent encoding“, which uses the “%” symbol plus the hex code of the character in its UTF-8 representation. You can see some examples of URL escape codes in the graphic above.

Lesson Topics

In this tutorial, we cover the following topics:
  • What is URL;
  • Structure of a URL;
  • Query Strings;
  • URL Encoding.

Lesson Slides

The post What is a Uniform Resource Locator (URL)? [Dev Concepts #40] appeared first on SoftUni Global.

]]>
https://softuni.org/dev-concepts/what-is-a-uniform-resource-locator-url/feed/ 0
Everything You Need To Know About HTTP Protocol [Dev Concepts #39] https://softuni.org/dev-concepts/everything-you-need-to-know-about-http-protocol/ https://softuni.org/dev-concepts/everything-you-need-to-know-about-http-protocol/#respond Fri, 08 Jul 2022 10:37:30 +0000 https://softuni.org/?p=21985 In this lesson, you will understand the basic concepts of the HTTP protocol used for communication between browsers and applications over the Internet.

The post Everything You Need To Know About HTTP Protocol [Dev Concepts #39] appeared first on SoftUni Global.

]]>

The Hypertext Transfer Protocol (HTTP) is the standard protocol used to transmit data across the web. It is originally created to transfer HTML, CSS, images and other Web resources within the global distributed information system called the “World Wide Web” (or just Web). Later, HTTP is extended to a general-purpose client-server protocol for the Internet and is widely used for transferring almost anything: text, images, documents, audio and video and more.

What is a protocol?

A communication protocol is a set of rules, which define how two or more parties are talking to each other. It is like a common language used for communication between machines. 

HTTP is a text-based client-server protocol. Client-server defines the parties communicating with each other: the client – software that reads and visualizes the data from the server, and the server – software that stores the data and provides it upon request in the form of an HTML document. 

The HTTP protocol uses the request-response model. It means that a site or a resource will not be open unless the client has asked for it. Therefore, the client has to send a request for a given data and the server will return a response containing the required data. 

The HTTP protocol relies on unique resource locators (URLs), like “https, column, slash, slash, softuni dot org”. When a resource is downloaded from the Web server, it comes with metadata (such as content type and encoding), which helps in visualizing the resource correctly.

Moreover, the HTTP protocol is stateless. Each HTTP request is independent from the others. Stateful HTTP conversations can be implemented by extra effort, using cookies, custom header fields, Web storage or other techniques.

HTTP Request Structure

Let’s see the structure of an actual request.

HTTP Requests Example

HTTP requests have a line, headers, a new line (CR + LF) after that, and a body at the end.

The HTTP request line is the command you send to the server to indicate what resource you want to get or process. It consists of:

  •       Request method (in our example “GET”);
  •       Request-URL (this is the resource path);
  •       HTTP version string.

Web browsers use URLs, but HTTP uses URIs to address the resources.

  •       URL stands for “uniform resource locator” and it describes a full unique address for a resource on the Internet, which consists of protocol + host + resource path, like in the example above
  •       URI stands for “uniform resource identifier” and it holds a full or relative unique path to a resource, for example “/about“.

When you request a resource over HTTP, you specify the relative URI of the resource in the request line and you specify the host name in the request headers. Both relative URI and host name come from the URL you want to access.

After the request line, the HTTP request headers are given. Headers specify specific parameters about the requested resource:

  •       “Host” is an important header, holding the requested resource. If we have several Web sites on the same Web server (for example softuni.org and learn.softuni.org), this “Host” header will tell the server which website to access.
  •       The other headers specify settings like what kind of content the client can accept and understands (for example only HTML or any content), what is the preferred language the client wants to use, what kind of compression the client understands (for example gzip and deflate), what are the client Web browser’s brand and version (encoded as the so-called “user agent” identifier) and other parameters.
  •       The headers section in the HTTP request ends by an empty line (CR + LF twice).

After the request headers, comes the request body.

  •       It can hold anything, for example, URL-encoded data or JSON objects or binary data.
  •       In the given example the body is empty, which is typical for HTTP GET requests.

HTTP Request Methods

The HTTP request method defines what action will be performed on the identified resource. The most commonly used HTTP methods are GET, POST, PUT, DELETE and PATCH which correspond to read, create, update and delete (or CRUD) operations, respectively.

Idempotency and safety are properties of HTTP methods.

Safe methods can only be used for read-only operations since they do not alter the server state. Using GET or HEAD on a resource URL, for example, should never change the resource. Safe methods are considered GET, HEAD, TRACE and OPTIONS.

Idempotent methods can send multiple identical requests to the server and the outcome will always be the same and it does not matter how many times the requests will be sent. This does not mean, however, that the server has to respond in the same way to each request. For example, if we want to delete a resource we send a DELETE request. The first time the server returns a response that the file has been deleted. If you try to send the same request again the server will respond that the file has already been deleted. Here we have two different responses but the second request did not alter the server state. In this case, the DELETE operation is idempotent.

The following HTTP methods are idempotent: GET, HEAD, OPTIONS, TRACE, PUT and DELETE. All safe HTTP methods are idempotent. PUT and DELETE are idempotent but not safe.

You can see all methods and their function in the graphic below.

HTTP Request Methods

The main HTTP methods corresponding to the CRUD operations are POST, GET, PUT/PATCH and DELETE.

  •   The GET method retrieves a specified resource (a list or a single resource). If there are no errors the method returns a representation of the resource in XML or JSON. GET is used to download a Web page, CSS file, script, document or other resources from a Web site. For example, a Web page’s content (fonts, images, etc.) is loaded using HTTP GET requests. This does not modify the state at the server-side, it only ‘reads’ it.
  •       The POST method modifies the state of the server since it creates new resources. For example, when you login into a website, the login sends your credentials to the server using a POST request.
  •       DELETE is used to delete (or remove) an existing resource. An example of an HTTP DELETE request is for deleting an item from the shopping cart in an e-commerce Web application.
  •       The PATCH method updates an existing resource partially. It is used to modify a field of a given object. An example is an HTTP PATCH request for updating the quantity of an order item in the shopping cart in an e-commerce Web application.
  •   The HTTP HEAD method retrieves the resource’s headers, without the resource itself. HEAD is used rarely, for example, to check for modifications on the server-side.

HTTP Response Structure

After receiving and interpreting a request message, the server sends an HTTP response message. You can see an example below.

HTTP Responses Example

The response message gives information on whether our request has been successfully executed or has failed. It consists of a status line, response headers and a response body.

The HTTP response status line starts with the protocol version, followed by the response status code, followed by a human-readable text explanation of the status code.

The status code tells the client whether the requested operation was successful or not. It is a three-digit integer whose first digit defines the response class.

Status codes are:

  • Informational responses (100–199)
  • Successful responses (200–299)
  • Redirection messages (300–399)
  • Client error responses (400–499)
  • Server error responses (500–599)

You can check the graphic below to see the most common status codes.

HTTP Response Status Codes

After the HTTP status line come the HTTP response headers that provide metadata for the returned resource (or the returned error), such as content-encoding, content size in bytes, content last-modify date and many others.

After the response headers and the empty line separator, the HTTP response body comes. This is the requested resource that can be text, binary data or it can be empty. In the example we used above, the Web server returns a CSS script for styling a navigation bar.

Content-Type and Disposition Headers

HTTP headers play an important role in modern Web development.

The “Content-Type” and the “Content-Dispositionheaders specify how to process the data in the HTTP request or in the HTTP response body. These headers can be used both in the HTTP requests and in the HTTP responses.

In the HTTP requests, the “Content-Type” header specifies what kind of data the client sends to the server, for example, a JSON document or URL-encoded form data or a plain-text document or a JPEG image. In the HTTP responses, the “Content-Type” header specifies what kind of data the server returns to the client, for example an HTML document or a JPEG image.

For example, the header “Content-Type: application/json” specifies a JSON-encoded data (a JSON object). By default, the UTF-8 encoding is used.

The “Content-Type: text/html; charset=utf-8” specifies an HTML document with UTF-8 encoding. Note that the encoding (or the charset) specified in the HTTP headers has a higher priority than the encoding specified in the header of the HTML document (using the “meta charset” HTML tag).

HTTP Dev Tools

Postman Client Tool Logo

There are browser built-in tools and client tools that help developers monitor the request-response traffic. An example of a client tool is the Postman HTTP client. Web developers use it for composing and sending HTTP requests and analyzing the HTTP response from the server, testing, debugging server APIs, researching how to use certain service APIs and for resolving technical issues during the software development. If you are interested in other HTTP client tools, you can try out Insomnia Core REST Client and Hoppscotch.

Lesson Topics

In this tutorial, we cover the following topics:
  • What is the HTTP Protocol
  • HTTP Request Structure
  • HTTP Request Methods
  • HTTP Response Status Codes
  • Content-Type and Disposition Headers

Lesson Slides

The post Everything You Need To Know About HTTP Protocol [Dev Concepts #39] appeared first on SoftUni Global.

]]>
https://softuni.org/dev-concepts/everything-you-need-to-know-about-http-protocol/feed/ 0
Handling an HTML Form – GET and POST Methods, and Data Encoding [Dev Concepts #38] https://softuni.org/dev-concepts/handling-an-html-form/ https://softuni.org/dev-concepts/handling-an-html-form/#respond Thu, 30 Jun 2022 06:00:00 +0000 https://softuni.org/?p=21526 In this lesson, we discuss HTML Forms and how to use GET and POST methods to send encoded data to the server for processing.

The post Handling an HTML Form – GET and POST Methods, and Data Encoding [Dev Concepts #38] appeared first on SoftUni Global.

]]>

HTML Forms are used to collect input from users and send it to the server for processing.
Examples are registration form that users fill out to sign up on a website and order submission forms on e-commerce sites.

HTML Form Structure

HTML has input elements displayed in different ways such as input field, checkbox (for selecting zero or more of multiple choices), radio buttons (for selecting one of multiple choices), submit button etc. The basic structure of a form consists of input fields and a submit button. The user fills out the input fields with the required information and upon clicking the submit button the data is sent to a form handler. Typically, the form handler is a file on the server with a script for processing input data.

HTML Forms Structure

Form Action Attribute

You add an action attribute to the form to define where the submitted data goes. In the example above the submitted information will be handled by the script of the home.html document.

In this case, the URL is called relative. Relative URLs are compared to the current URL that is loaded in the Web browser. We can use slashes and the “double dot” notation to address a different folder or the parent folder of the virtual folder structure on the Web server.

Full URLs are used to submit the form data to completely different Web site. For example, a Web site may embed an HTML form for newsletter subscription which submits its form fields to an external Web site, which provides email newsletter services.

Form Method Attribute

In the following example, we have added an HTTP method attribute to the form. The method can be either GET or POST. Both methods are used to transfer data from client to server.

The GET method transfers data in the URL with a query string. Therefore, the length of the URL is limited. GET is preferable for images, word documents or data that does not require any security.

POST is an HTTP method that encodes form data in a specified format and sends it to the server via the HTTP message body. The World Wide Web frequently uses POST to send user-generated data or an uploaded file to the web server.

In the example above, you can see the standard URL encoding used to encode the HTML form fields and URLs. The URL encoding is a long string of name and value pairs. Each pair is separated from one another by an ampersand (&) sign and each name is separated from the value by an equals (=) sign. For example: key1=value1&key2=value2.

This encoding can be used for text and other data fields, but it does not support file upload fields. We can overcome this limitation by switching to multipart encoding.

Differences Between GET and POST Methods

If you want to send one or two simple variables (for example search parameters) to your server, then you use GET. However, if your form includes passwords, credit card information, or any other data that needs extra protection then POST is a better choice. You can see a side to side comparison between the two methods in the example below.

GET and POST Methods Comparison

Lesson Topics

In this tutorial, we cover the following topics:
  • HTML Form Structure

  • Form Action Attribute

  • Form Method Attribute

  • Differences Between GET and POST Methods

Lesson Slides

The post Handling an HTML Form – GET and POST Methods, and Data Encoding [Dev Concepts #38] appeared first on SoftUni Global.

]]>
https://softuni.org/dev-concepts/handling-an-html-form/feed/ 0
Understanding HTTP Dev Tools [Dev Concepts #37] https://softuni.org/dev-concepts/understanding-http-dev-tools-37/ https://softuni.org/dev-concepts/understanding-http-dev-tools-37/#respond Fri, 24 Jun 2022 06:00:00 +0000 https://softuni.org/?p=21404 In this lesson, we talk about the browser Dev Tools and explain how to use them to your best advantage. Learn how the network inspector and client tools can ease your work as a developer.

The post Understanding HTTP Dev Tools [Dev Concepts #37] appeared first on SoftUni Global.

]]>

The HTTP flow of requests and responses can give you useful information about how the web application communicates with the server. It can improve your software development process, and save you time and effort when debugging.

Built-in Browser Tools

Modern Web browsers have a set of built-in tools for monitoring the HTTP traffic. The functionality of these tools includes also inspecting the already rendered HTML elements and debugging right into the browser. 

Open Inspect Menu In Browser

Chrome Developer Tools can be accessed by pressing the [F12] key in Google Chrome. Another way is to right-click anywhere on the Web page and select [Inspect] in the context menu.

This opens a panel with several tabs. The Elements tab shows the HTML used to build the current Web page. It holds information about the UI controls in the Document Object Model (DOM) tree.

The Console tab shows errors and logs for the currently loaded Web Page. The tab is also used for executing JavaScript commands and interacting with the page.

You can set breakpoints and evaluate expressions in JavaScript through the Sources tab. All files that were used to make the website are listed here.

Error 404! Image

To monitor the data exchanged between the current  page and the Web server, we use the Network tab. This tab is commonly used to confirm that resources are downloaded or uploaded correctly.

When you click on a link, the browser sends multiple requests to the server regarding different elements of the page. The HTML required to render the page is sent back in the form of responses from the server. There is information about every response that includes HTTP request URL, the request method, remote server IP address and port, status code and many other technical details.

HTTP Requests and Responses Traffic

Client Tools

Another useful tool for developers who need information on HTTP traffic is the Postman HTTP client. This tool is used for composing and sending requests, analyzing HTTP responses from the server for testing, debugging server APIs and for resolving technical issues during the software development process.

Postman Client Tool Logo

With Postman you can create an HTTP request, send it to the Web server, view the HTTP response, and generate a source code to execute the HTTP request in many languages, such as JavaScript, C#, Java, Python, PHP and many others.

Another alternative for an HTTP client tool is the Insomnia Core Rest Client. In case you prefer a Web-based HTTP tool, you can try Hoppscotch.

Lesson Topics

In this tutorial, we cover the following topics:
  • Network Inspector

  • Postman Client Tool

  • Sending and Analyzing HTTP Requests

Lesson Slides

The post Understanding HTTP Dev Tools [Dev Concepts #37] appeared first on SoftUni Global.

]]>
https://softuni.org/dev-concepts/understanding-http-dev-tools-37/feed/ 0
How to Become Google Expert Developer? [Dev Talks #3] https://softuni.org/dev-talks/how-to-become-google-expert-developer/ https://softuni.org/dev-talks/how-to-become-google-expert-developer/#respond Thu, 16 Jun 2022 14:10:31 +0000 https://softuni.org/?p=21300 Say hello to Iliya Idakiev. He will take you into the world of Google Developer Experts

The post How to Become Google Expert Developer? [Dev Talks #3] appeared first on SoftUni Global.

]]>

Meet Iliya Idakiev. He is a Google Developer Expert (GDE) in Angular and Web Technologies and he has been working with JavaScript for over 7 years. He teaches at Sofia University and has been running his own company (Hillgrand) for almost 5 years where he develops various web applications. He likes to organize and participate in JavaScript events and he and his team have a YouTube channel (commitjs). 

Today he is here to answer some questions you probably have about the process of becoming a GDE.

What inspired you to become a developer?

“My experience began at University. My major was Informatics. I was studying C++ and also working with .NET and C#. Then I decided to learn JavaScript. Shortly after that, I started teaching JavaScript and opened my own company.”

How did you become a Google Developer Expert?

“To be a Google Developer Expert means to be recognized by Google for the things that you do for certain technologies. I wanted for a long time to become a Google Angular Expert. I was organizing events and a lot of courses. I started to go to conferences and I met with a lot of people who were already Google Developer Experts. So one day I decided to go on several interviews and everything went pretty smooth.”

What is the process of becoming a Google Developer Expert?

“First, you have to be recommended by another Google Developer Expert and you must send all the background that you have (open-source projects, events, courses, etc.). You need to contribute to the community. The person from Google will check your background and you will have 2 or 3 interviews (personal and technical). Among all the benefits of becoming a Google Developer Expert, the biggest one for me is that you get recognized by Google and people look at you differently.”

What is your experience with contributing to open-source projects?

“When you are working on some application and you are using some modules, at a certain point you will start to discover issues with these modules or new features that can be added. If you have time, you can fix these issues or add new features and make a pull request. This is a way to become a contributor.

Another way is to open-source the useful libraries that you developed in your projects.”

How do you relax?

“I like walking and traveling to peaceful and beautiful places. I was a DJ before and still do it from time to time.”

What are the projects that you are working on?

“I mostly do private JavaScript-related training. I like live coding, which is much more interesting and effective for the students. One of the biggest projects we developed is the Front-End of a customer portal for monitoring and controlling off-grid and hybrid power systems. It was very challenging, and I am proud of this project.”

When do you realize that you are successful?

“This is other people’s decision, not mine. But I can say that I succeed when I accomplish my goals.”

What tips for success would you give?

“I think that everyone should find what he/ she is happy and enthusiastic about and try to become the best in it. Do not focus on the money/ salary, but focus on becoming better in what you do. Dedicate yourself and do not give up. This will make you successful.”

How did you manage to stay motivated?

“Going to meet-ups and knowledge sharing is very good and useful. This will keep you awake and inspired.”

What advice will you give to young people who study at University?

“The University is a place where you can learn something that is going to be like a base for your life ahead. My advice is to start teaching other people as soon as you can because this will make you better in your field. Be a part of the community that is doing what you are doing and try to solve other people’s problems (for example, on Stack Overflow). Sharing knowledge is amazing!”

Do you have a favorite book on programming?

“I would recommend books like “Clean Code”,Clean Architecture”, and “Enterprise System Architecture”. It is wise to invest time in something useful for your field. Also, GitHub is the best “book” that I would recommend.”

How do you see yourself in 5 years?

“My goals are to develop my company and give my team a better working environment. I see myself still teaching other people and contributing to the community.”

The post How to Become Google Expert Developer? [Dev Talks #3] appeared first on SoftUni Global.

]]>
https://softuni.org/dev-talks/how-to-become-google-expert-developer/feed/ 0
What is a Database System (DBMS)? [Dev Concepts #36] https://softuni.org/dev-concepts/what-is-a-database-system/ https://softuni.org/dev-concepts/what-is-a-database-system/#respond Thu, 26 May 2022 06:00:00 +0000 https://softuni.org/?p=21165 In this lesson, we explain the concept of databases and typical CRUD operations. We will also take a look at relational and NoSQL databases.

The post What is a Database System (DBMS)? [Dev Concepts #36] appeared first on SoftUni Global.

]]>

database is a collection of data that is organized so that it can be easily accessedmanaged, and updated.

  • Usually, you need to store data that will be accessible even after you end the program execution.
  • One way to do that is by using a text file, but this is not scalable and does not provide any structure.

database-with-serverDatabases hold and manage data in the back-end systems. Almost all modern software systems use a database in some form. The data in database systems is organized in tables, collections, key-value pairs or other structures. The software, which managesretrieves and manipulates data in a database, is called Database Management System(DBMS).

Relational and Non-Relational Model

In this section, we will explain the difference between these two database models:

  • The relational model is based on tables and relationships.
  • The non-relational model is based on collections of documents.

The structure of relational databases is strict, while the non-relational is not so strict. SQL databases regulate the input data, what their format is, how different types of data are connected, etc. RDBMS systems manage relational databases and expose a universal interface for developers: the SQL language. Relational databases organize data in tables, which hold data rows, and each row holds columns.

relational-vs-nosql

Non-Relational databases have a dynamic schema. A schema is the structure of the database, which describes all its objects (tables, collections, views, and others) and their structures. The data stored in NoSQL databases are not strictly structured. Sometimes these databases are called “schema-free databases“. Properties of an entity (the columns in the SQL database) can be added dynamically. NoSQL databases can be based on several data models (several ways to structure data).

Define, Manipulate, Retrieve and Manage Data with DBMS

Database Management System (DBMS) is a server software, which takes data queries of manipulation commands from the clients, execute the commands in the database, and returns the results to the clients.

dbms-diagram

While a database could be just a collection of data files, the DBMS is what makes it so powerful with its structure, algorithms, optimizations, and APIs. For comparison, in a text file, you will be able to save whatever information you like, while in a database, managed by a DBMS, you can set rules on the incoming data. DBMS systems implement a programming API or specialized language, such as SQL, to manage data.

To do so, first, we create a query (or command) through the client that is passed to the engine through its API. The engine processes the query and accesses the data files. Then, the database storage returns the desired data from the data files to the engine. Finally, the engine processes the returned data and passes it to the client for visualizing in a human-readable format.

Databases are very powerful in keeping collections of entities. The relational model is based on tables and relationships, and the non-relational model is based on collections of documents. Database systems are an important component of most modern software systems, and therefore software engineers must have at least basic database skills

Lesson Topics

In this tutorial, we cover the following topics:
  • Databases Introduction

  • SQL vs NoSQL Databases

  • DBMS Systems

Lesson Slides

The post What is a Database System (DBMS)? [Dev Concepts #36] appeared first on SoftUni Global.

]]>
https://softuni.org/dev-concepts/what-is-a-database-system/feed/ 0