How a static method call works in Java? - java

When calling out the function testFunc(), I am not using the syntax
Apples.testFunc(). Yet the code runs successfully. How so?
class Apples {
public static void main(String args[] ) {
testFunc();
}
public static void testFunc() {
System.out.println("Hello world!");
}
}

Since, the static method is in the same class. So, you don't need to specify the class name.
If it is in different class, then you need to specify the class name.
Remember: Non-static methods can access both static and non-static members whereas static methods can access only static members.
For example :
Calling a static method present in different class, you need to do like this :
import com.example.Test;
public class Apples {
public static void main(String args[]) {
Test.testFunc();
}
}
package com.example;
public class Test {
public static void testFunc() {
System.out.println("Hello world!");
}
}

Your function testFunc() is in same class where the function main is. So you don't need to use class name before function testFunc().

When the memory is allocated for the class, Static method or static variable is assigned memory within a class. So we can access static member function or data variable using class name.
we can call static function as below
class Main1 {
public static void main(String args[] ) {
Main1.testFunc();
}
public static void testFunc() {
System.out.println("Hello world!");
}
}
or
class Main1 {
public static void main(String args[] ) {
testFunc();
}
public static void testFunc() {
System.out.println("Hello world!");
}
}
the answer will be same, but when static function is in other class then we must use classname to call it

Related

Unable to call function in java

When I try to call the lyrics function in this code, "invalid method declaration; return type required" occurs.
I'm learning java and very very new to it. I'm confused how to define the function and call the function so that code may run.
public class Main {
public static void main(String[] args) {
}
public void lyrics() {
System.out.println("some lyrics here");
}
lyrics();
}
Normally, one can't just invoke a method randomly in the body of the code. However, there is something called an initialization block (this gets run in the body of the constructors of the object). I think an example might clarify. Like,
public class Main {
public static void main(String[] args) {
new Main(); // <-- instantiate an instance of Main
}
public void lyrics() {
System.out.println("some lyrics here");
}
{ // <-- this is an initialization block
lyrics();
}
}
The above uses the default constructor, we can add an explicit one. Like,
public Main() {
super();
System.out.println("In Main constructor");
}
Note how the output changes.
They can also be static (and run when the class is first referenced). Like,
public class Main {
public static void main(String[] args) {
}
public static void lyrics() {
System.out.println("some lyrics here");
}
static {
lyrics();
}
}
Your code is nearly correct. Your lyrics() method must be static if you want to call it inside main method because main method is static. Non static members cannot be accessed from static method (without creating an instance to invoke it).
public class Main {
public static void main(String[] args) {
lyrics();
}
public static void lyrics() {
System.out.println("some lyrics here");
}
}
You can invoke non-static methods from static method by creating an instance of the class containing non-static method inside your main method as mentioned in comments by Elliott Frisch.
new Main().lyrics();
Since you're learning Java, you must remember that the only way to call a non-static method from a static method is to have an instance of the class containing the non-static method.
Or you can simply make your function static. Also, you need to call the function inside the main block.
public class Main {
public static void main(String[] args)
{
lyrics();
}
public static void lyrics()
{
System.out.println("some lyrics here");
}
}
Happy coding!
The method should be declared as static and function call should be within main method. The correct code should look like as follows:
public class Main {
public static void main(String[] args)
{
lyrics();
}
public static void lyrics()
{
System.out.println("some lyrics here");
}
}
You need to move the call to lyrics() into the main method where code is actually executed. Where you have it now, the compiler is expecting a new method defination.
public class Main {
public static void main(String[] args) {
// execution begins here.
new Main().lyrics();
}
public void lyrics() {
System.out.println("some lyrics here");
}
}
EDIT: created new class Main class to avoid errors.

How to handle class's from Two Different .Java Files?

I have two java class file's in my project.
First one is main.Java
Second one is function.java
How to call function.java method from main.java
for Example.
main.Java
public class main {
//call function here
}
function.Java
public class function {
public void example(){
System.out.println("Function working");
}
}
How to call function.java example method from Main.Java?
Class name should be always start with Upper letter.
This is the way to call a function in another class in another .java
In Main.java
public class Main{
public static void main(String[] args){
SecondClass sc = new SecondClass();
sc.go();
}
}
In SecondClass.java
public class SecondClass{
public void go(){
System.out.println("Done");
}
}
If you want to call the method in the same class
public class Main{
public void go(){
System.out.println("Done");
}
public static void main(String[] args){
Main m = new Main();
m.go();
}
}
or this
public class Main{
public static void go(){
System.out.println("Done");
}
public static void main(String[] args){
go();
}
}
First make the example() method static
public static void example(){
System.out.println("Function working");
}
Then call
public class main {
//call function here
public static void main(String[] args) {
function.example();
}
}
if they are not in the same package you should import function.java in main.java like this
import function
then you should create an instance of function class like this where you want to use it
function func = new function();
then you can call the example method using func object you created like this
func.example();
Your method isn't static, so you need to instantiate object from this class(function) to obtain access to the example method. First of all read some java specific book, so you can understand what static keyword is and how you can use it.
The code below will work :
package main.Java; //this is from where you want to call.
public class function {
public void inFunction(){
function.Java.function function = new function.Java.function();
function.example();
}
}
Happy learning :)

Access static variable from a different class

So I have two classes:
A Main class with the public static void main(String args[]) method
and a Voice class that accesses a static variable from that class.
Within the main class are methods that are used by itself, and are required to be static along with some of its variables.
So I have a static variable within the Main class (that's created/filled in the public static void main(String args[]) method. That's why this case is special) which the other class should be able to access.
Here is an example of what's happening:
public class Main(){
public static int variable;
/*
Unrelated methods go here.
*/
public static void main(String args[]){
Voice v = new Voice();//This is just here for the code to make sense.
variable = 5;
v.doSomething();
}
}
public class Voice(){
public void doSomething(){
System.out.println(Main.variable);
}
}
Upon calling the doSomething() method in Voice, it leads to a nullPointerException.
I could fix this by passing on the variable variable to the Voice class, but is there a more easy way to fix this in the long run, if for instance, I needed to use more than one static variable from the Main class?
Your code is having syntax error. You can use this
class Main{
public static int variable;
/*
Unrelated methods go here.
*/
public static void main(String args[]){
Voice v = new Voice();//This is just here for the code to make sense.
variable = 5;
v.doSomething();
}
}
class Voice{
public void doSomething(){
System.out.println(Main.variable);
}
}
Output will be 5
You should do as follows
public class Main{
public static int variable;
/*
Unrelated methods go here.
*/
public static void main(String args[]){
Voice v = new Voice();//This is just here for the code to make sense.
variable = 5;
v.doSomething();
}
}
class Voice{
public void doSomething(){
System.out.println(Main.variable);
}
}

How do I refer to a variable from a method in the same class

I surprisingly find this confusing. I must be missing something.
So I have this simple syntax
public class OMG{
public static void main(String args[]){
int hi=2;
letsDoIt();
System.out.println(hi);
}
public static void letsDoIt(){
hi+=1;
}
}
Obviously this cause an error, since hi is a local variable.
Judging from my experience from python I added this
public class OMG{
public static void main(String args[]){
int hi=2;
letsDoIt();
System.out.println(hi);
}
public static void letsDoIt(){
this.hi+=1;
}
}
Which adds extra error when non-static variable cannot be accessed from a static method.
I added static to hi
public class OMG{
public static void main(String args[]){
static int hi=2;
letsDoIt();
System.out.println(hi);
}
public static void letsDoIt(){
this.hi+=1;
}
}
The compiler scolds me for a illegal expression. I substitute the static with private (which some SO answers, recommend) but same error.
Where's my mistake? Is there any way I can solve this, without making global class?
You cannot declare static variables inside a method because static modifier means that a method or field belongs to the class.
The easiest solution to this problem would be to declare the variable as static class variable. Using this approach, you also need to remove this from this.hi in lestDoIt method. The code would be like this:
public class OMG {
static int hi=2;
public static void main(String args[]) {
letsDoIt();
System.out.println(hi);
}
public static void letsDoIt() {
hi+=1;
}
}
Another solution may be using a non static variable hi. This would need you to also remove the static modifier to the letsDoIt method to access to hi field, because static methods cannot access to instance fields because, as explained above, static means that a method or field belongs to the class and not to a specific object instance of the class.
The solution would be:
public class OMG {
int hi=2;
public static void main(String args[]) {
//note that we have to create a new instance of OMG
//because, again, static methods cannot access to non-static methods/fields
OMG omg = new OMG();
omg.letsDoIt();
System.out.println(omg.hi);
}
public void letsDoIt() {
this.hi+=1;
}
}
More info:
Java Tutorials. Using the this Keyword
Java Tutorials. Understanding Class Members
There are two elements causing your issue.
variable hi must be referenced within a shared context between your main method and your letsDoIt method
because your main method is static, and so your letsDoIt, the will only have visibility on static fields (unless passed an instance as argument, that is)
Hence:
Declare hi as a static field of OMG:
public class OMG {
static int hi;
...
Remove the local variable declaration in your main method.
Reference it with OMG.hi or just hi within a static context, not with this.hi as this implies an instance of Main, which is not visible from a static context
You can not do "this.hi+=1" in a static context and in order to access the hi variable from "letsDoIt()" you have to declare it as a class variable like I did in the code below:
public class OMG{
public static int hi;
public static void main(String args[]){
hi=2;
letsDoIt();
System.out.println(hi);
}
public static void letsDoIt(){
hi+=1;
}
}
Static variables are variables of the class, not its instances. You can't have a static variable inside a method.
To fix this error, move hi outside the main method (keeping it static). Also get rid of the this in letsDoIt().
public class OMG {
static int hi=2;
public static void main(String args[]){
letsDoIt();
System.out.println(hi);
}
public static void letsDoIt() {
hi+=1;
}
}

Simple Java OOP Class Error

I'm trying to print my name using Java OOP Classes, Objects and Method. Below are the two scripts I'm using. Nothing is showing on the screen. I'm using Netbeans IDE.
package name;
public class Begin {
public static void displayName(){
System.out.print("Say My Name");
}
}
===========================
package usename;
import name.Begin;
public Useaname {
public static void main(String[] args){
Begin.displayName();
}
}
You're missing the class in your "Useaname" class declaration.
public class Useaname {
Where is Your Keyword class before your Username ?? :)
public class Useaname {
public static void main(String[] args) {
Begin.displayName();
}
}
You have to declare the method static in order to call it like Begin.displayName().
public static void displayName() {
This tells makes the method a function of the class as opposed to any particular instance of the class.
Alternatively, you can instantiate an object to call the method:
Begin begin = new Begin();
begin.displayName();
You have missed the keyword class before the class name Useaname. Here is the solution code.
package usename;
import name.Begin;
public class Useaname {
public static void main(String[] args) {
Begin.displayName();
}
}
This code should not compile.
Begin.displayName(); tries to invoke static method - you dont have such a thing :).
you have to ways - create new Begin object and invoke method on it - new Begin().displayName()
or declare displayName as static method.
There are at least two solutions to this problem:
(1) You can make the displayName() method static. This will allow you to call it with the class name.
public static void displayName() {
// snip
}
(2) You can create an object from your Begin class in order to call the non-static member method:
public static void main(String[] args){
Begin b = new Begin();
b.displayName();
}
To summarize, you should learn about objects and object creation as a beginning step to understanding Java and OOP in general.
You could use a static modifier on your displayName() method or create a new instance of your Begin class:
package usename;
public class Useaname {
public static void main(String[] args){
Begin begin = new Begin();
begin.displayName();
}
}
You haven't use the keyword "class" before "usename"
package usename;
import name.Begin;
public Useaname {
public static void main(String[] args){
Begin.displayName();
}
}
Correction
package usename;
import name.Begin;
public class Useaname {
public static void main(String[] args){
Begin.displayName();
}
}
you forgot class keyword ! and you can create object for class Begin
import name.Begin;
public class Usaname
{
public static void main(String []args)
{
Begin ob = new Begin();
ob.displayName();
}
}
You forgot to add class before Username
package username;
import name.Begin;
public class username{
public static void main(String[] args){
Begin.displayName();
}
}
What you are missing here is the class keyword before Username class declaration
Since you declared the displayName() method as static using the static access modifier , there is no need to create an object of the Begin class in order to invoke the displayName() method.
In general , this is how the Username class should be :
package usename;
import name.Begin;
public class Useaname {
public static void main(String[] args){
Begin.displayName();
}
}
Alternatively, you can invoke the displayName() using a class instance by creating an object of the Begin class, just like this:
package usename;
import name.Begin;
public Useaname {
public static void main(String[] args){
Begin b = new Begin();
b.displayName();
}
}

Categories