Well I was messing around with it more and I am getting an error message now that says can not resolve symbol where I have return larger;. Dam I thought I had it there. Ian public class Lab13C { public static void main(String[] args) { System.out.println("Larger number: " + Calc.larger(7, 3.5)); } } class Calc { public static double larger(double p1,double ... |
I'm with C#. Nothing to do with violation of OO, in my opinion, but the C# style is more clear. Static memebers are not a part of an object and it makes sense to prohibit the use of calling them using objects. Allowing to call the static methods on objects can be misleading. Consider the following piece of code public class ... |
Hey Sir As we know that static function in a class is concerned with class not with object then if we declear a function in a class as static then in main it should call only with class name or free not with object but it is calling with object also why? like public class first { static int abc=90; public ... |
Hi. I'm now studying static methods and got stucked in one excercise which I found from the net. So, I should make one class which only contains one static method (let's call it as staticMethod). I know how to create it, but then I can't understand the next thing: "This staticMethod should get one scanner-object as it's parameter and it may ... |
Well, you can't do that because initialize() returns void (of course). For that to work, initialize() would have to return an instance of A. This would be kind of silly, as the instance wouldn't be used; furthermore, many IDEs would warn about the usage. It's never occurred to be as a general rule before, but it's obvious that in fact static ... |
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - ... |
Hi All, May be I still don't get the sequence of how static methods are called and how class is loaded, but I stumbled across some strange behavior by static method. For your easy checking, I am copying the program here below. Can anyone tell me why the static method call to highID() always returns the number of objects that are ... |
|
|
Hi, would you be able to show me how static method call non-static method in same class? I tried to put a simple of my two program below. please show me how to fix this problem. Regards, e.g package pgm; import pgm.*; class A; public static Map getValues(String ISBN_digit) { Hashtable ht = new Hashtable(); String message = "from CCHKDigit() "; ... |
hey ,program is all correct and will run.you have created instance of palindrome class in static method and then calling nonstatic method on that instance which is ok.actually the constraint on nonstatic method is because static method is only one for whole class and does not have any information about any particular (instance of class)object so if you call nonstatic method ... |
Static methods are conceptually the same as static variables, thus the reasons to use or not use them are similar. They belong to the class, not specific objects of that class. An example from the java API is Math, all the variables are static. Does it make sense to have to create a Math object just to call a single method? ... |
Jose - You have all my sympathy - since I beat my head against your exact question for MONTHS! And just recently had a flash of insight ... So I will try to elaborate on what Jeanne said without just confusing it. Normally, you have to have an object in order to call a non-static method. So if you have a ... |
I wrote the below program with the intention of doing some exercises about static variables and methods.I want to find out ,when a variable is declared within a static method without defining the variable as static , that the declared variable is static or not.How am I to find it out from a program like this. public class StaticTest{ /* This ... |
|
Hi, 1)Can we synchronize a static method?if yes what is the effect on multithreading? 2)say,we have class Abc{ static Myclass myobject=new Myclass(); } now,if we use synchronized static method to access the myobject using one thread. Can we use that myobject of that Myclass in another thread cuncarently: Dont forget the method in Sunchronized. please explain in brief. Thanks. |
|
Yes, sorry about the compile errors. It is my experience that this works also. This occurs in a front end method that references a public class with a static method. This method makes a call to a mainframe application that updates files on the server. Once complete it should return back to the calling method to finish some cleanup. What appears ... |
Hi, I'm trying to read two lines from the console. The first line is oke, but the second gives and exception "Stream closed" In the Beginners FAQ I read "Static fields belong to a class, and we all know there's only one of each class, so there's only one copy of each static field." I'm having trouble to apply the faq ... |
|
|
I have a method which has following signature public Boolean postRequest(NameValuePair[] params, String url, String postMethod) It makes a connection to the server and sens a post request. Now my doubt is if the method is static and it is currently executing the code means making a connection and during that process another class tries to access it then what will ... |
|
I am trying to write a program that calculates the surface gravity on each planet in our solar system. I have the printing of the results assigned to a static method. However, I have a problem. There are two for statements I am using in this program. The last for statement is causing me trouble. It calls back up the printResults ... |
Hi, I am seeing something strange and I don't see how or why it could happen. If someone can help 'enlighten' me, it would be very appreciated. I have an abstract class, Product, that contains a static public void method, createPrototypes(). I am calling Product.createPrototypes() during my application bootup but the code in the method is not reached or processed. The ... |
Static means you only get one per class. That is pretty much the definition. Please be patient in waiting for responses. Response times vary due to time zones, work, etc. It's a good bet that you could have to wait up to 24 hours for a response. Bumping the thread to ask for a response just makes you look impatient. |
|
Hi, public class ClassTwo { public static void main(String args[]) { Sequencer classone = ClassOne.getSequencer(); MidiDevice player = new Player(); connect (clasone, player); ... } ... public void connect(MidiDevice from, MidiDevice to) { try { ... } catch (MidiUnavailableException e){//stacktrace} } } I'm getting the error "non-static method connect cannot be referenced from a static context" in the main method, so ... |
I think by "structural", Sut Pat means "procedural". Only instance members (ie anything not marked static) can be used to represent or use the information in an object. Static members belong to the class, and all instances of that class have access to its static members, but imagine you have 3 instances of a class and a static method. Which instance ... |
|
Hi Anuj, Static methods or variables are class level not instance level. You can directly access static methods without creating object for that class. Static methods can't be overridden but can be re-defined in its subclass. Consider the following example public class TestSample { public static void main(String[] args){ ClassA.test(); // Prints "Hello A" ClassB.test(); // Prints "Hello B" ClassB cb ... |
Praveen, I prefer static methods at cases when method functionality can be achieved by using the parameters sent to the method rather than the instance variables. Say you want to append n zero's to int and convert to String . A simple and reusable solution would be a static method taking 2 int parameters ( one for the number of zeros ... |
Hi All, I wanted to know if it is a good practice to have a java class with a static method which is called by servlets in different sessions to add objects of a particular type in that particular session. My confusion is whether different sessions accessing a static method would behave weird. Please let me know. Thanks, SM. |
Well, it depends on what you do in that method. I can think of a couple scenarios where even simple logging gets messed up if that call isn't synchronized in some way. On that note, I'm not sure I agree with the suggestion that all exceptions have to be handled in one place. |
|
Thanks, that makes sense. But now I have another question. When you say that System.out is a PrintStream object, can a reference variable be a reference to two objects? I found the following snippet on the web: "Out is a reference variable or class variable of the system class. It is an object of the System class and therefore a reference ... |
|
for this program class rajan { public static void sum() { System.out.println("i am base class"); } } class erode extends rajan { public static void sum() { System.out.println("i am derived class"); } } class rajanerode { public static void main(String args[]) { erode e=new erode(); e.sum(); } } method from class erode will get called . A static method cannot override ... |
|
While studying for the SCJP 6 exam, I ran into this question in a test exam: class A{ private static String staticProperty = " a "; String getStaticProperty() { return staticProperty; } } class B extends A { private static String staticProperty = " b "; public static void main(String[] args){ new B().go(new A()); } void go(A t){ String s = ... |
|
I had an original code: import java.util.*; class Exercise1 { public static void main ( String[] args) { Scanner scan = new Scanner ( System.in ); System.out.println("Enter number of levels: "); int levels = scan.nextInt(); TriangleCalc tri = new TriangleCalc(); if (levels > 0) { int result = tri.Triangle( levels ); System.out.println("Triangle(" + levels +") is " + result ); } ... |
Hi, This is a problem with Java allowing a static method to be accessible with a class instance. Okay, to answer your question 1) Is your question with in a context of multiple threads ?. This would cause havoc, unless you synchronize the static method. 2) Is your question with in a context of a single thread ?. Not an issue. ... |
|
|
public class static_exp { public static void main(String args[]) { hobbit o1=new hobbit(); hobbit_exp o2=new hobbit_exp(); o1.func1(); o2.func1(); o1=o2; o1.func1(); } } class hobbit { int a=1; static void func1() { System.out.println("Static func1 of hobbit"); } } class hobbit_exp extends hobbit { static void func1() { System.out.println("Static func1 of hobbit_exp"); } } It's output is : Static func1 of hobbit Static ... |
I am very new to Java and am having a difficult time grasping the concepts being taught in my class. I think what keeps throwing me off is that the more I research the more I find that people do things differently. There are so many ways to do things how do I know if I am doing them right? I ... |
Im writing a class LeapYearExpert with one static method: isLeapYear(int year). This methods should return true, if the year given as a parameter is a leap year and false otherwise. Does this accomplish that? Im not sure, if I'm doing it right and I also have to write a tester, but I wanna make sure my class atleast works first. public ... |
|
Hi All, I have a question about static methods. If I call a non-static method from a static method in a class, I get an error "non-static method XXX() cannot be refrenced from a static context". But if I call a non-static method which is present in some other class, it works. How is that possible ? Because its still vague ... |
I am really confused about this static method . Firstly in this public static void main() we are supposed to declare and use only static methods . But still when we declare object of another class with its object reference we can call a non static member too . What my doubt is indirectly we are calling a non static member ... |
A is a class, AA is a subclass of A, AAA and AAB are subclasses of AA. The important thing to me is the hierarchical relationships of the classes, so when I use AAA , I just want it gives me a static instance with type of AAA while does not create a new instance. I add an static method "get()"in ... |
public class LargeNum { public int n1 = 10; public int n2 = 20; public int n3 = 30; public static int n4 = 40 ; public static int n5 = 50; public void go(int n1, int n2, int n3) { if(n1>n2){ if(n1 > n3) { System.out.println("n1 is largest") ; } else { System.out.println("n3 is the largest"); } } else { ... |
I have to write a static method which does a simple check to the passed string: a) whether the string length is of seven characters b) whether the 4th character is a dash '-' if both are true then return true, else return false The method is: public static boolean isLicenseNumber(String s) { if(s.length()==7 && s.charAt(3)=='-') return true; return false; } ... |
I'm extremely confused on the use of static methods. I've been writing a code to calculate the surface gravity of each planet in our solar system. I got help from my teacher and I thought I understood but when I tried to finish the program I was still very confused. I know the problems somewhere in the main method and the ... |
I have 3 questions related to the following program:- class Y { } class Xyz { public static void main(String[] args) { int x=0; System.out.println(x); Y y1=new Y(); Xyz x1=new Xyz(); S1 st=new S1();//this will give me an error } class S1 { } } My question starts from the eight'th line .... 1.if we cannot access non static variables why ... |
|
|
The word static indicates to the compiler that the declared member is static (both at compile time and at run time). When you implement a static method in your sub class it is not overriding but rather re defining the method for that particular class. Run time polymorphism does not work here. |
|
We have an application that uses a class that has static methods. This class contains methods that do "database work". There are many methods in the class but, for this issue, there are two that I am concerned about - one that reads records in a DB2 table (using sql) that are "ready to process" and one that updates records that ... |
I want to implement an interface with some methods, but all of these methods are static. The problem now is all of the code which I have is for Client side & all are static i.e. about 300 variables & 50 functions calls are all done as static. But now if I want to change these back to non-static I have ... |
:confused: Java Code: [B]PairTestOne.java[/B] package homenetwork.bkr.training; public class PairTestOne { public static void main (String[] args) { String[] words = {"Mary", "had", "a", "little", "lamb"}; [B]Pair mm = ArrayAlg.minmax(words);[/B] System.out.println("min = " + mm.getFirst()); System.out.println("max = " + mm.getSecond()); } } [B]ArrayAlg.java[/B] package homenetwork.bkr.training; /** Gets the minimum and maximum of an array of strings. * @param a: an array of ... |
Hello, I made a simple console program which has a main method and another method I'll call testMethod. If I call the method from inside main I get a compiler error about the testMethod not being static. If I make the method static all is well. I did not create the executing program using the new command but I would believe ... |
I am very new to Java and am having a difficult time grasping the concepts being taught in my class. I think what keeps throwing me off is that the more I research the more I find that people do things differently. There are so many ways to do things how do I know if I am doing them right? I ... |
|
|
Hi everyone, I'm fairly new to object orientated programming quite familiar with procedural programming do, used to think it was easier until i bought a book an Java (now i don't know what i was thinking must've been crazy) . Anyway, the problem i'm having is Eclipse is telling me that one of my methods must be static. Game.checkBlock() is the ... |
public class Example2{ public static boolean isPrime(int n){ int x = Math.sqrt(n); boolean flag = true; for(int i = 2; i< x; i++){ if(n % i == 0){ flag = false; break; } } return flag; } public static void main(String[] args){ System.out.println("Please enter a number: "); int y; Scanner scan = new Scanner(System.in); y = scan.nextInt(); ArrayList primes = new ... |
Here is my code: import java.util.*; import java.text.NumberFormat; import java.lang.*; public class EnhancedInvoiceApp{ public static void main(String[] args){ double discountAmount=0; double total=0; double discountPercent; String customerType; //create a scanner object called sc Scanner sc = new Scanner(System.in); String choice = "y";//initialize choice while(!choice.equalsIgnoreCase("n")){ //get input from the user System.out.println("Enter customer type (r/c/t): "); System.out.println(); customerType = sc.next(); //check for non r/t/c ... |
My bad, thanks for correcting me! I guess I'm still to much of a newbie to be helping :P This is what I meant to write though. which does compile: public class numbers { public numbers() { int number = 1; System.out.println(triple(number)); } //main public static void main(String[] args) { new numbers(); } public int triple(int n) { return 3*n; } ... |
|
Hi everyone, I am a beginner with coding and one of the many parts of my assignment is to use static methods to write the first seven verses of the nursery rhyme, This is the house that Jack built," that i pasted on here. I have no idea how to write the code. Any help would be greatly appreciated! Thanks so ... |
Hi All, I am preparing for the java 6 certification. Below is a piece of code which says we can access a static method using a reference var..is that right?can you please clarify... class frog{ static int frogcount=0; public frog(){ frogcount+=1; } } class testfrog{ public static void main(String args){ frog f= new frog(); int frogs = f.frogcount; System.out.println(frogs); } } ... |
|
|
Hi All, In a SCJP preparation book(Author: Kathy Sierra), I actually read that static methods can't be overridden but can be re-defined in its subclass. How does re-definition differ from overriding them? How does a Java Interpreter look at re-defined static methods in a sub-class? I request the forum to shed some light on this. Thanks in Advance... /Varaga |
|
|
The variables in the watchlist will show "not known variable" when the point of execution is not in their scope. It doesn't mean there's a problem with the variable, just that wherever the program currently is has no knowledge of the variable. In your Method2() method, if you put a break point, 'ii' will not be a known variable, since Method2() ... |
I'm having problems with a static method. Coming from PHP to Java, I miss the implode() function, so I wrote my own. I have a program with several classes. I need to use this method in all classes, and MainWindow is my central class. I've added the method to MainWindow with the following signature: {code}public static String implode(String[] ary, String delim) ... |
|
static has nothing to do with the scope of the method. It means that the method or variable is to be accessed through the class and not its object. for instance a class has a variable int value, each object of the class has a different value. but if its static all the objects share a same value. |
That's not what I meant. I want to use static methods for sections of my code. The sections are addition() subtraction() multiplication(). Selecting 1, 2 or 3 causes the program to go to one of the following static methods. I then want to use a switch statement to process the selection. Does that make any sense? |
HI all, I am new to java. I have been going thru the java concepts. I came across the topic Static Methods. All it says, it doesn't need a object instance to use it. That's an advantage of it. Can someone please tell some practical use of it. I mean where this will be more useful. As I am new to ... |
|
|
|
Yea I saw that and I'm just throwing it in the air. Something is not right but i can not figure out what. Validator.java:7: dataEntry is already defined in getIsValid(java.lang.String) String dataEntry = ""; ^ Validator.java:22: cannot find symbol symbol : variable strthirdMessage location: class Validator dataEntry = JOptionPane.showInputDialog(strthirdMessage, ""+JOptionPane.ERROR_MESSAGE); ^ Validator.java:22: cannot find symbol symbol : variable JOptionPane location: class ... |
Hi. I'm studying override method. I'm confused with final and static method in overriding when we used final method? when we used static method? what differences are ? In my opinion if we use final method in super class then we can't write override method in sub class. if we use static method in super class thenn we can write override ... |
Apologies if this has been asked a million times before. I am just wondering what happens if a static method is called from different places at the same time? I presume only 1 copy of a class is loaded, is there a queueing system for access to the static method? Thanks for any help. |
static imports are a huge mistake and anyone using them should be shot, lest I end up having to work on their code. ~Tim If anyone can give me a case where they are acceptable, I'd like to hear it, as it is I think they should be removed from the language spec. |
What is this? A static method is a class method (and not an object method (also called instance method)). Why we need to use this type of method? A static method deals with class level information, that is information that's not specific to any object in particular but to the class as a whole. Examples can be a method which tells ... |
It doesn't matter if the method is static or not. What does matter is that Java is pass by value and not pass by reference. So when you create a new Item in the modifyDesc method it is a totally seperate object and the it object in main is not affected. Try commenting out the new Item line in the method ... |
According to Cay Horstmann in Big Java about static methods: "in general you want to minimize the use of static methods. If you find yourself using a lot of static methods, then that's an indication that you may not have found the right classes to solve your problem in an object-oriented way" (p.299) Further he states about Static Fields that:" When ... |
|
|
yes like the above code. And also it can simply access other class methods and data members like class Sample { int a; void display() { System.out.println("a= "+a); } } class StatTest { public static void main(String args[]) { Sample sp=new Sample(); sp.a=10;//main accesses a which is not static sp.display();//main accesses display which is not static } } how is this ... |
Now why i am confused is that the main method in teh AccessTest class is a static method , then how is it able to call a non static method of class Test. As it was said in the book that "static methods can only call other static methods" Please help me clear this confusion. Thanks in advance. |
Hi guys, Before anyone starts accusing me of trolling: I never did and I quite frankly speaking don't have time for this. My prev. questions were always genuine, and just because I have different (sometimes) opinion on what is logical and what is not it doesn't mean that I'm trolling. Ok that's sorted, I hope so. Now my question. In multithreaded ... |
|