i was trying to run the following code but i am getting error please clarify my doubt
import java.util.*;
class Except
{ public class AlfaException extends Exception{}
public static void main(String[] args)
{
int b;
Scanner s=new Scanner(System.in);
try
{
b=s.nextInt();
}
catch(InputMismatchException ex)
{
try
{
if(('b'> 67)&&('b'<83)){}
}
catch(AlfaException e){
throw new AlfaException("hello");
}
System.out.println("error found");
}
}
}
Except.java:20: non-static variable this cannot be referenced from a static cont
ext
throw new AlfaException("hello");
^
1 error
Static context is a context that runs on class without actual instance of that class. Your main method is static, that means it can only access static variables. However, your AlfaException is not static. Meaning that it will be bound to an instance of Except class - which you do not have.
Therefore you have 2 choises:
Make AlfaException also static: public static class AlfaException extends Exception{}. That will make it reside in static scope so it will be possible to access it from static functions.
Move all the main(...) method logic into non-static context. Create a function called doWork() that is not static, move all the code from main to doWork, and then call it like this:
.
public static void main(String[] args) {
Except instance = new Except();
instance.doWork();
}
Your AlfaException is a non-static inner class of Except, so it can only be instantiated from inside an instance of Except. The main method is static, so doesn't have an enclosing instance.
Change the declaration of AlfaException to:
public static class AlfaException extends Exception{}
and it should work.
There are couple of mistakes:
AlfaException is never thrown in your try-block
AlfaException is a non-static inner class of Except (see other answers)
If you rethrow AlfaException in catch-block, the main needs a throws like this:
public static void main(String[] args) throws AlfaException { ...
import java.util.*;
class Except
{ public static class AlfaException extends Exception{
public AlfaException(String string) {
super();
}
}
public static void main(String[] args) throws AlfaException
{
int b;
Scanner s=new Scanner(System.in);
try
{
System.out.println("Enter the value for b");
b=s.nextInt();
System.out.println("b value is "+b);
}
catch(InputMismatchException ex)
{
if(('b'> 67)&&('b'<83)){}
System.out.println("error found");
}
}
}
output:
Enter the value for b
80b
error found
Related
package constructorlatest;
import java.util.*;
public class ConstructorLatest {
public static void main(String[] args) {
A a1=new A();
a1.calculate();
a1.display(12);
ConstructorLatest Cl=new ConstructorLatest(); //1
Cl.privateMethod();
this.privatemethod(); //2
this.publicMethod(); //3
}
ConstructorLatest C2=new ConstructorLatest(); //4
C2.privateMethod(); // 5
private void privateMethod()
{
System.out.println("this is a private method in main class");
}
void publicMethod()
{
System.out.println("this is a public method in main class");
}
this.privatemethod();
this.publicMethod();
}
class A
{
void calculate()
{
int x,y,sum;
Scanner sc=new Scanner(System.in);
x =sc.nextInt();
y =sc.nextInt();
sum=x+y;
display(sum);
}
void display(int sum)
{
System.out.println("no constructor created hence default constructor");
System.out.println(sum);
}
}
comment 1 Is there any need to create an object of the main class (in general).I have heard this() keyword can access all the method of a class,Then why their would be need to create an object of class ConstructorLatest inside the class.
comment 2 since privateMethod and public method are non static we cant access them inside static function.Am i right?
comment 5 why this line is showing error?IMO it is not inside a valid method
The main method is static. Therefore you cannot use thisin it. Static methods can be used without an object, but all non-static methods require one.
The statements with comment 5 does not belong to any method. This is not allowed in Java.
Why doesn't a static block in the class get executed when I don't create a reference variable for an object (anonymous) of that class?
For example, let us consider this simple class:
public class StaticDemo {
private static int x;
public static void display(){
System.out.println("Static Method: x = "+x);
}
static {
System.out.println("Static Block inside class");
}
public StaticDemo(){
System.out.println("Object created.");
}
}
Another class using it:
public class UseStaticDemo {
public static void main(String[] args) {
StaticDemo Obj = new StaticDemo();
Obj.display();
System.out.println("------------");
new StaticDemo().display();
}
}
Output:
Static Block inside class
Object created.
Static Method: x = 0
------------
Object created.
Static Method: x = 0
A static initializer block only runs once, when the class is loaded and initialized.
Also, static methods have absolutely no relation to any instances. Doing
new StaticDemo().display();
is pointless and unclear.
public class StaticInnerClass {
public static void main(String[] args) {
//Outers out=new Outers();
Outers.Inner1 in=new Outers.Inner2();
in.display();
}
}
class Outers
{
static class Inner1
{
static void display()
{
display();
System.out.println("Inner1");
}
}
static class Inner2 extends Inner1
{
static void display()
{
System.out.println("Inner2");
}
}
}
The above program gives a stackoverflow error. Please explain that why doesn't it display "Inner1" because static methods don't override.
The static method that executes is based on the static type, not the instance type:
Outers.Inner1 in=new Outers.Inner2();
So when you call this line, the static type is Outers.Inner1 and therefore it calls the display method that's part of this class, which calls itself repeatedly (causing the StackOverflowError.)
Static methods are not invoked polymorphically!
This will cause the method display to invoke itself again and again until you get Stack Overflow Error. Also, see this question : Polymorphism and Static Methods
A static method can't be overridden by sub class
Static methods should be called with Class not with an object, even though you use object, it still going to use the type of the object.
I created my own throwable exception but when i want to throw it, the editor says, that a reference to an enclosing class required. I don't know, what i need to write.
Here's code:
public class Main {
int i = 0;
public Main() {
if (i == 0) throw new MyException("i must not be 0"); //Here it says about enclosing class
}
public static void main(String[] args) throws Exception {
new Main();
}
public class MyException extends Exception {
public MyException(String e) {
super(e);
}
}
}
Someone can tell me, where and what i must write?
You've defined MyException as an inner class of Main, then created an instance of it with no corresponding instance of Main available (since the main method is a static method).
You need to declare the exception class separately, outside of Main. Changing the access from public to package-private would let you keep the declaration in the same file. Otherwise, since you can have only one public class per file, it would need to go in its own file.
Alternatively you can define this as a static inner class, like so:
public class Main {
int i = 0;
public static void main(String[] args) throws Exception {
if (i == 0) throw new MyException("i must not be 0"); //Here it says about enclosing class
}
static class MyException extends Exception {
public MyException(String e) {
super(e);
}
}
}
Making the class static means it does not refer to an instance of the enclosing class.
Either declare MyException class as static
public static class MyException extends Exception {
public MyException(String e) {
super(e);
}
}
Or declare it in its own compilable .java file.
The way you have it now, MyException is an inner class of Main which requires an instance of Main to be initialized.
throw new Main().new MyException("i must not be 0");
After your edit, obviously everything works...
This is a general problem: Your class MyException is a nested class to your Main class, and it will always hold a reference to its enclosing instance. You want to make that exception class static, too.
Alternatively, in general but probably not in this case, you can instantiate the inner class using an instance of the outer class:
Main m = new Main();
throw m.new MyException();
Yes, that’s a new after the dot.
It is said that non-static variables cannot be used in a static method. But public static void main does. How is that?
No, it doesn't.
public class A {
int a = 2;
public static void main(String[] args) {
System.out.println(a); // won't compile!!
}
}
but
public class A {
static int a = 2;
public static void main(String[] args) {
System.out.println(a); // this works!
}
}
or if you instantiate A
public class A {
int a = 2;
public static void main(String[] args) {
A myA = new A();
System.out.println(myA.a); // this works too!
}
}
Also
public class A {
public static void main(String[] args) {
int a = 2;
System.out.println(a); // this works too!
}
}
will work, since a is a local variable here, and not an instance variable. A method local variable is always reachable during the execution of the method, regardless of if the method is static or not.
Yes, the main method may access non-static variables, but only indirectly through actual instances.
Example:
public class Main {
public static void main(String[] args) {
Example ex = new Example();
ex.variable = 5;
}
}
class Example {
public int variable;
}
What people mean when they say "non-static variables cannot be used in a static method" is that non-static members of the same class can't be directly accessed (as shown in Keppils answer for instance).
Related question:
Accessing non-static members through the main method in Java
Update:
When talking about non-static variables one implicitly means member variables. (Since local variables can't possible have a static modifier anyway.)
In the code
public class A {
public static void main(String[] args) {
int a = 2;
System.out.println(a); // this works!
}
}
you're declaring a local variable (which typically is not referred to as non-static even though it doesn't have a static modifier).
The main method does not have access to non-static members either.
final public class Demo
{
private String instanceVariable;
private static String staticVariable;
public String instanceMethod()
{
return "instance";
}
public static String staticMethod()
{
return "static";
}
public static void main(String[] args)
{
System.out.println(staticVariable); // ok
System.out.println(Demo.staticMethod()); // ok
System.out.println(new Demo().instanceMethod()); // ok
System.out.println(new Demo().instanceVariable); // ok
System.out.println(Demo.instanceMethod()); // wrong
System.out.println(instanceVariable); // wrong
}
}
This is because by default when you call a method or variable it is really accessing the this.method() or this.variable. But in the main() method or any other static method(), no "this" objects has yet been created.
In this sense, the static method is not a part of the object instance of the class that contains it. This is the idea behind utility classes.
To call any non-static method or variable in a static context, you need to first construct the object with a constructor or a factory like your would anywhere outside of the class.
More depth:
Basically it's a flaw in the design of Java IMO which allows static members (methods and fields) to be referenced as if they were instance members. This can be very confusing in code like this:
Thread newThread = new Thread(runnable);
newThread.start();
newThread.sleep(1000);
That looks like it's sending the new thread to sleep, but it actually compiles down into code like this:
Thread newThread = new Thread(runnable);
newThread.start();
Thread.sleep(1000);
because sleep is a static method which only ever makes the current thread sleep.
Indeed, the variable isn't even checked for non-nullity (any more; it used to be, I believe):
Thread t = null;
t.sleep(1000);
Some IDEs can be configured to issue a warning or error for code like this - you shouldn't do it, as it hurts readability. (This is one of the flaws which was corrected by C#...)
**Here you can see table that clear the access of static and non-static data members in static and non-static methods. **
You can create non-static references in static methods like :
static void method() {
A a = new A();
}
Same thing we do in case of public static void main(String[] args) method
public class XYZ
{
int i=0;
public static void increament()
{
i++;
}
}
public class M
{
public static void main(String[] args)
{
XYZ o1=new XYZ();
XYZ o2=new XYZ();
o1.increament();
XYZ.increament(); //system wont be able to know i belongs to which object
//as its increament method(static method)can be called using class name system
//will be confused changes belongs to which object.
}
}