You are reading the article Static Variable In Java: What Is Static Block & Method updated in December 2023 on the website Katfastfood.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 Static Variable In Java: What Is Static Block & Method
The static can be:
Let’s look at static variables and static methods first.
What is Static Variable in Java?Static variable in Java is variable which belongs to the class and initialized only once at the start of the execution. It is a variable which belongs to the class and not to object(instance ). Static variables are initialized only once, at the start of the execution. These variables will be initialized first, before the initialization of any instance variables.
A single copy to be shared by all instances of the class
A static variable can be accessed directly by the class name and doesn’t need any object
Syntax:
What is Static Method in Java?Static method in Java is a method which belongs to the class and not to the object. A static method can access only static data. It is a method which belongs to the class and not to the object(instance). A static method can access only static data. It cannot access non-static data (instance variables).
A static method can call only other static methods and can not call a non-static method from it.
A static method can be accessed directly by the class name and doesn’t need any object
A static method cannot refer to “this” or “super” keywords in anyway
Syntax:
Note: main method is static, since it must be accessible for an application to run, before any instantiation takes place.
Lets learn the nuances of the static keywords by doing some excercises!
Example: How to call static variables & methodsLets learn the nuances of the static keywords by doing some excercises!
Step 1) Copy the following code into a editor
public class Demo{ public static void main(String args[]){ Student s1 = new Student(); s1.showData(); Student s2 = new Student(); s2.showData(); } } class Student { int a; static int b; Student(){ b++; } public void showData(){ System.out.println("Value of a = "+a); System.out.println("Value of b = "+b); } }Step 2) Save & Compile the code. Run the code as, java Demo.
Step 3) Expected output show below
Following diagram shows, how reference variables & objects are created and static variables are accessed by the different instances.
Value of a = 0 Value of b = 1 Value of a = 0 Value of b = 2 Value of a = 0 Value of b = 3 error: non-static variable a cannot be referenced from a static context a++; What is Static Block in Java?The static block is a block of statement inside a Java class that will be executed when a class is first loaded into the JVM. A static block helps to initialize the static data members, just like constructors help to initialize instance members.
class Test{ static { } }Following program is the example of java static block.
Example: How to access static block public class Demo { static int a; static int b; static { a = 10; b = 20; } public static void main(String args[]) { System.out.println("Value of a = " + a); System.out.println("Value of b = " + b); } }you will get following output of the program.
Value of a = 10 Value of b = 20
You're reading Static Variable In Java: What Is Static Block & Method
Does Static Factory Method Internally Use New Keyword To Create Object In Java?
Factory pattern is a design pattern (creational pattern) which is used to create multiple objects based on the data we provide. In it we create an object abstracting the process of creation.
ExampleBelow given is the example implementation of the factory pattern. Here, we have an interface with name Employee and 3 classes: Student, Lecturer, NonTeachingStaff, implementing it. We have created a factory class (EmployeeFactory) with a method named getEmployee(). This method accepts a String value and returns an object of one of the classes, based on the given String value.
import java.util.Scanner; interface Person{ void dsplay(); } class Student implements Person{ public void dsplay() { System.out.println("This is display method of the Student class"); } } class Lecturer implements Person{ public void dsplay() { System.out.println("This is display method of the Lecturer class"); } } class NonTeachingStaff implements Person{ public void dsplay() { System.out.println("This is display method of the NonTeachingStaff class"); } } class PersonFactory{ public Person getPerson(String empType) { if(empType == null){ return null; } if(empType.equalsIgnoreCase("student")){ return new Student(); } else if(empType.equalsIgnoreCase("lecturer")){ return new Lecturer(); } else if(empType.equalsIgnoreCase("non teaching staff")){ return new NonTeachingStaff(); } return null; } } public class FactoryPattern { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter the type of the object you want: (student, lecturer, non teaching staff)"); String type = sc.next(); PersonFactory obj = new PersonFactory(); Person emp = obj.getPerson(type); emp.dsplay(); } } Output Enter the type of the object you want: (student, lecturer, non teaching staff) lecturer This is display method of the Lecturer class Static factory methodThough it is said that there are five ways to create an object in Java namely −
Using the new keyword.
Using the Factory method.
Using cloning.
Using Class.forName().
Using object deserialization.
The only way to create an object in Java is using the new keyword all other ways are abstractions to it. Intact all these methods internally use the new keyword.
Example import java.util.Scanner; interface Employee{ void dsplay(); } class Student implements Employee{ public void dsplay() { System.out.println("This is display method of the Student class"); } } class Lecturer implements Employee{ public void dsplay() { System.out.println("This is display method of the Lecturer class"); } } class NonTeachingStaff implements Employee{ public void dsplay() { System.out.println("This is display method of the NonTeachingStaff class"); } } class EmployeeFactory{ public static Employee getEmployee(String empType) { if(empType == null){ return null; } if(empType.equalsIgnoreCase("student")){ return new Student(); } else if(empType.equalsIgnoreCase("lecturer")){ return new Lecturer(); } else if(empType.equalsIgnoreCase("non teaching staff")){ return new NonTeachingStaff(); } return null; } } public class FactoryPattern { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter the type of the object you want: (student, lecturer, non teaching staff)"); String type = sc.next(); EmployeeFactory obj = new EmployeeFactory(); Employee emp = EmployeeFactory.getEmployee(type); emp.dsplay(); } } Output Enter the type of the object you want: (student, lecturer, non teaching staff) lecturer This is display method of the Lecturer classStatic Website Vs Dynamic Website
Difference Between Static Website vs Dynamic Website
Web development, programming languages, Software testing & others
Head to Head Comparison Between Static Website vs Dynamic Website (Infographics)Below are the top 7 Comparisons between Static Website and Dynamic Website
Key Differences of Static Website vs Dynamic Website DefinitionA static website is scripted in HTML has the code on its page, and that’s the one displayed to the user. Whereas in the dynamic website, it is scripted in ASP, PHP, Coldfusion, or JSP. In such dynamic websites, the written content is executed by scripting language by imported files or databases, which depends on the user’s functions.
CostA static website’s cost is comparatively lower in front-end and consumes for the ongoing task to update contents on every page. Whereas in a dynamic website, it doesn’t require any ongoing cost until if there are no changes in the fundamental design or any additional functions are fed. The dynamic website’s cost is maximum than a static website for additional functionalities, especially when something is not encountered at origin and needs re-scripting of the code chunks or database.
AdvantagesIn dynamic sites, they can be associated with every database, which easily retrieves to pull the information in a structured and organized way to develop pages and categorise associated products filtered in different techniques based on the user’s display pane. The capability to link the database signifies that the user wants to develop a content management system. It is an interface that enables the client to manage the data through web-based administration pages. The related content can be in a message format in images and pages to navigate through items or text in ranges of categories, images, specifications, minimum and maximum descriptions. This column is left to the preference of the user and can be made as simple or complex.
LimitationsThe important problem in a static website appears if the user wants to update the context in his webpages. Unless the user is familiar with HTML, the designing methods deployed in the website should be reflected in the developer who doesn’t have to make any changes in content. It looks perfectly fine when any fresh page is added; he needs a design input. But if it wanted to be executed on all the webpages, it won’t be very pleasant to both the developer and the client. Next, there are scalability issues on static websites. If the user wants to sell his products on his websites, it takes a lot of effort to construct every individual page and takes maximum effort, cost, and time.
A dynamic website’s layout is completely fixed and stable that static as most of the pages is an attractive template where it requires more content and data to develop many pages in the same type. So the product pages are mandatory in the same layout displaying the different data. Few customization abilities are built-in with limited by choosing the pre-defined options. The changes in individual layout to the concerned pages are not possible.
Comparison Table of Static Website vs Dynamic WebsiteAttributes
Static websites
Dynamic websites
Scripting language It is scripted using HTML, JavaScript, CSS code to develop a website. It uses PHP, JSP, ASP, Servlet, and .NET to develop dynamic websites.
Definition The content of a static website is constant whenever the page is loaded. It interacts with the same response for every single request. The content of dynamic websites keeps on changing whenever it is refreshed. It produces different HTML codes for every new request.
Function The content is changed if the client publishes and updates the file connected to the server. The web pages comprise server-side codes that enable the server to produce unique content whenever the page is refreshed.
Advantages
Cost Development cost is minimum. The cost of development is maximum.
Database It doesn’t interact with the database. It interacts with the database.
Layout It displays the same layout and content to the user whenever they visit. It provides a mix of content and designs, dynamic elements and attractive features according to the user’s preference.
ConclusionMost of the cyberspaces use dynamic websites and can be deployed easily than static websites. But it is possible in a dynamic website to do basic changes which reflect in the rest of the web pages.
Recommended ArticlesThis is a guide to Static Website vs Dynamic Website. Here we discuss the difference between Static Website vs Dynamic Website and the key differences and comparison table. You can also go through our other related articles to learn more –
Difference Between Static Relays And Electromagnetic Relays
In electrical and electronics engineering, a Relay is an electrically operated switch which is used to connect or disconnect two circuits. Since the operation of a Relay is governed by an electric control signal, hence it can be operated automatically. Basically, the relays are designed for switching of high power circuits by using low power electric signals.
Depending on the technology used, the relays can be broadly classified into two types namely
Electromagnetic Relays
Static or Solid-State Relays
In this article, we will highlight all the key differences between an electromagnetic relay and a solid state relay by considering different parameters. But before getting into the differences, let’s start with some basics of electromagnetic relay and solid state relay so that it becomes easier to understand the differences between them.
What is an Electromagnetic Relay?A type of relay that uses an electromagnet to perform the switching function is known as electromagnetic relay. The working of an electromagnetic relay is based on the principle of electromagnetic induction.
A typical electromagnetic relay consists of the following main parts
Electromagnet
Movable contact, called armature
Set of input terminals
Set of contact terminals or switching points
Control spring
The electromagnet of the Relay is made by wounding a copper wire on a soft iron core. The two terminals of the electromagnetic coil are used as the input terminals to provide the control signal to the relay. The magnetic field produced by the electromagnet is used to open and close the switching terminal of the relay. The electromagnetic relays are widely used in several applications such as lighting control system, industrial processes, power generation, transmission and distribution, power system protection, automotive, etc.
What is a Static Relay?A solid state relay or static relay is the one which uses electrical and optical properties of semiconductor materials to perform the switching functions. Therefore, a solid state relay does not contain any moving part.
The solid state relays provide a complete electrical isolation and connection between two circuits. It is because, in the off state, it offers an infinite resistance between the two circuits and when it is in on state, it offers almost zero resistance.
The main switching components of the solid state relays are transistor, SCRs, TRIAC, etc. The relays do not have moving parts, hence there operation is faster than electromagnetic relays. Also, the solid state relays are comparatively smaller in size, hence these are widely in a number of electronic circuits like computer, UPS, robotics, control systems, etc.
Difference between Static Relay and Electromagnetic RelayBoth static and electromagnetic relays are used for automatic switching of electrical and electronic circuits. However, there are several differences between static and electromagnetic relays that are listed in the following table
Basis of Difference Electromagnetic Relay Static Relay
Definition An electromagnetic relay is the one which uses an electromagnet to perform the switching function. A static relay is the one that uses solid state semiconductor devices like transistor, MOSFET, SCR, etc. to perform the switching function.
Abbreviation EMR is the abbreviation used for electromagnetic relay. SSR is the abbreviation used for solid state or static relay.
Alternate name Electromagnetic relay is also called as electromechanical relay Static relay is also called as solidstate relay.
Main components The main components of an electromagnetic relay are-
Electromagnet
Moving armature
Set of input and switching terminals
The main components of a static relay are −
Semiconductor switching device
Set of input and switching terminals
Opto-coupler
Working principle Electromagnetic relays work on the principle of electromagnetic induction. Static relays operate on the electrical and optical properties of semiconductors.
Moving parts Electromagnetic relays consists of moving parts such as armature. Static relays do not consist any moving part.
Switching noise Electromagnetic relays produce switching noise. Static relays do not produce switching noise.
Power consumption Electromagnetic relays consume high power. Static relays consume very less power, usually of the order of mW.
Problem of arcing Due to presence of moving contacts, there is a problem of arcing at contact terminals in the electromagnetic relays. As a static relay does not have any moving contact, hence there is no problem of arcing at switching terminals.
Replacement of contact In an electromagnetic relay, the replacement of contact terminals is necessary. Static relays do not require the replacement of contact terminals.
Position & location of relay Electromagnetic relay is always installed in straight position and at the location away from the magnetic fields. Static relay can be installed in any position and at any location.
Functions A single electromagnetic relay can perform only a single function. For example, if one electromagnetic relay is used for over-voltage protection, then another EM relay has to be used for over-current protection. A single static relay can perform multiple functions. For example, one SSR can be used for both overcurrent and over-voltage protection.
Effect of gravity on operation The gravity can influence the operation of electromagnetic relays. The operation of static relays is independent of the gravitation force.
Effect of shocks & vibrations The operation of electromagnetic relays get affected by the shocks and vibrations. There is no effect of shocks and vibrations on the operation of static relays.
Effect of temperature In the electromagnetic relays, there is no significant effect of change in temperature. Solid state relays may get damaged due to high temperature.
Size Electromagnetic relays are comparatively large in size. Static relays have compact size.
Accuracy Electromagnetic relays are less accurate. The accuracy of static relays is high.
Speed Electromagnetic relays are slow. Static relays are fast.
Cost Electromagnetic relays are less expensive. Static relays are comparatively costlier.
ConclusionThe most significant difference between the two is that an Electromagnetic Relay has mechanically moving parts, while a Static Relay does not have any moving parts. However, both EMR and SSR are widely used in several applications like lighting control systems, automotive, robotics, instrumentation and automation, etc.
What Is The Url Variable In Google Tag Manager?
The URL Variable in Google Tag Manager allows you to extract any component of a URL and reuse it in your GTM setup.
In this blog post, I will show you how to use this powerful feature in GTM.
🚨 Note: If you haven’t installed it already, check out our guide on how to install Google Tag Manager on WordPress.
An overview of what we’ll cover:
So let’s dive in!
Why Should you Care About the URL Variable in GTM?With the URL Variable, you can access all components of an URL that are either called up directly or returned by another variable. This can be helpful when extracting the path of a URL, but it’s also great when you need to extract query values that were added to an URL, such as campaign parameters. To demonstrate the power of the URL Variable, let’s consider the following example.
🚨 Note: Check out our handy guide on ActiveCampaign tracking with GTM.
What Does the URL Variable Do? The Components of a URL ExplainedBefore we dive into our example, let’s look at the individual components of a URL, using our example URL from above.
resource/redirect-tracking-template/ – The third part is the path, which describes the folders and page name that comes after the host name, but without any query or fragment that may follow.
#summary – the last potential piece of a URL is called a fragment. Fragments always have a leading hash (#) symbol. They specify a location on the resource that the URL describes. You will probably know them as anchors in HTML.
All these URL components can be extracted with the URL Variable in GTM. You can additionally choose to extract the full URL or the port number used in the URL. When the URL points directly to documents, such as PDFs, you can also extract the filename extension (i.e. “pdf”).
How to Extract Part of the URL PathIf you want to extract any of the described components from the URL using the URL Variable, here’s how to do this in GTM.
Next, we’ll choose URL as the Variable Type in GTM.
In the Component Type dropdown menu, select which part of the URL you want to extract. In this example, we want to extract the Query, as this is where the UTM parameters are located:
The UTM parameters are called utm_source, utm_medium, and utm_campaign, so we need to create each of these Variables by entering their corresponding Query Keys in GTM. See below the configuration for utm_source:
utm_medium:
And utm_campaign:
In order to check that these are implemented correctly, simply turn on the preview and debug mode in GTM. Visit the website that is running your GTM code and add the query component of our example URL to the end of your website URL like this:
CODE: ?utm_source=newsletter&utm_medium=email&utm_campaign=newsletter+4-28-2023#summary
(if your URL already has a query, use & instead of the leading ?).
And that’s it. Now you can reuse these extracted variables in other tags and variables within your GTM setup.
How to Extract only Specific Subdirectory Levels of the URL pathYou can follow the pattern above to extract other parts of your URL. However, there is one shortcoming of the URL Variable: When it comes to the URL path, you can only extract the entire path and not just a specific part of it. When you are running a blog with different categories and you want to extract just the category name of the URL, this could be an obstacle.
Fortunately, there is a solution. In order to extract just the category name of your blog’s URL (assuming the category name always appears in the same subdirectory level), you need to apply a custom JavaScript.
function() { var pageUrl = window.location.href; return pageUrl.split("/")[X]; }In this code, X specifies the level of the subdirectory that you want to extract. You may need to test this on your website, but the 2nd level subdirectory should be extracted when you insert 3 instead of X.
And that’s all you need to do. Using this method, you can extract any directory level from a full URL.
Other Useful GTM VariablesIf you liked this tutorial on the URL Variable in the GTM, you may want to look at the Top 10 Variables for Google Tag Manager, which includes favorites like the DataLayer Variable, Constant Variable, and GA Settings Variable.
FAQ How do I extract parts of the URL using the URL Variable in GTM?To extract parts of the URL using the URL Variable in GTM, you need to create a new URL variable in GTM and specify the component type you want to extract, such as the query, path, or fragment. You can configure the variable to extract specific values, such as UTM parameters, by defining the corresponding query keys.
How can I test my URL Variable configuration in GTM?To test your URL Variable configuration in GTM, you can enable the preview and debug mode in GTM, visit the website with the GTM code, and add the relevant URL components to the end of the website URL. In the GTM preview pane, you can check the extracted values in the Variables tab and verify if they match your expectations.
Can I extract specific subdirectory levels from the URL path using the URL Variable?The URL Variable itself doesn’t provide a direct way to extract specific subdirectory levels from the URL path. However, you can achieve this by using a custom JavaScript variable in GTM. The JavaScript code splits the URL path into components and allows you to extract a specific subdirectory level based on your requirements.
SummaryThe URL Variable in GTM lets you extract any component of a given URL: from the protocol to host name, the URL path and queries and fragments appended to the URL.
In order to extract only specific parts of the URL path, you need the help of a little JavaScript, but all other components can be extracted using the built-in settings in GTM. You can then reuse the extracted variables in your GTM in other tags and variables.
🚨 Note: Keep up with the changes in GTM – learn about server-side tagging in GTM and how it can be useful for your tracking deployment.
What Are The Different Types Of Classes In Java?
Types of classes in Java Concrete class
Any normal class which does not have any abstract method or a class that has an implementation of all the methods of its parent class or interface and its own methods is a concrete class.
ExampleLive Demo
public class Concrete { static int product(int a, int b) { return a * b; } public static void main(String args[]) { int p = product(2, 3); System.out.println("Product: " + p); } } Output Product: 6 Abstract classA class declared with abstract keyword and have zero or more abstract methods are known as abstract class. The abstract classes are incomplete classes, therefore, to use we strictly need to extend the abstract classes to a concrete class.
ExampleLive Demo
abstract class Animal { public abstract void sound(); } public class Dog extends Animal { public void sound() { System.out.println("Woof"); } public static void main(String args[]) { Animal a = new Dog(); a.sound(); } } Output Woof Final classA class declared with the final keyword is a final class and it cannot be extended by another class, for example, java.lang.System class.
ExampleLive Demo
final class BaseClass { void Display() { System.out.print("This is Display() method of BaseClass."); } } class DerivedClass extends BaseClass { void Display() { System.out.print("This is Display() method of DerivedClass."); } } public class FinalClassDemo { public static void main(String[] arg) { DerivedClass d = new DerivedClass(); d.Display(); } }In the above example, DerivedClass extends BaseClass(final), we can’t extend a final class, so compiler will throw an error. The above program doesn’t execute.
Output cannot inherit from final BaseClass Compile-time error - can't inherit final class POJO classA class that contains only private variables and setter and getter methods to use those variables is called POJO (Plain Old Java Object) class. It is a fully encapsulated class.
ExampleLive Demo
class POJO { private int value=100; public int getValue() { return value; } public void setValue(int value) { this.value = value; } } public class Test { public static void main(String args[]){ POJO p = new POJO(); System.out.println(p.getValue()); } } Output 100 Static classStatic classes are nested classes means a class declared within another class as a static member is called a static class.
ExampleLive Demo
import java.util.Scanner; class staticclasses { static int s; static void met(int a, int b) { System.out.println("static method to calculate sum"); s = a + b; System.out.println(a + "+" + b); } static class MyNestedClass { static { System.out.println("static block inside a static class"); } public void disp() { int c, d; Scanner sc = new Scanner(System.in); System.out.println("Enter two values"); c = sc.nextInt(); d = sc.nextInt(); met(c, d); System.out.println("Sum of two numbers-" + s); } } } public class Test { public static void main(String args[]) { staticclasses.MyNestedClass mnc = new staticclasses.MyNestedClass(); mnc.disp(); } } Output static block inside a static class Enter two values 10 20 static method to calculate sum 10+20 Sum of two numbers-30 Inner ClassA class declared within another class or method is called an inner class.
ExampleLive Demo
public class OuterClass { public static void main(String[] args) { System.out.println("Outer"); } class InnerClass { public void inner_print() { System.out.println("Inner"); } } } Output OuterUpdate the detailed information about Static Variable In Java: What Is Static Block & Method on the Katfastfood.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!