Final Declaration Statement - How To Use Named Constant

Feb 27, 2014

I'm new to Java and have been stuck on how to use a final declaration statement once it's made. Below is a class I'm creating with the intention of calling it under a main method. I don't understand if I'm supposed to do anything else, like do some sort of get/set, or if the final static line is all I need. And, I don't know how I call it to the main method once I do.

public class Shirt//class name.
{
int collarSize;//data field.
int sleeveLength;//data field.
public final static String MATERIAL = "cotton";//final data field for material.

[Code] ....

View Replies


ADVERTISEMENT

Declaration And Initialization On Separate Statement In A Class

Jan 29, 2015

I know that I can declare and initialize an member variable inside a class in a single statement but I can't do them on separate sentence. Why?

For example, I am allowed to do the following,

class A{
int a = 5;
// rest of the class
}

But I am not allowed to do this,
class A{
int a;
a = 5; // it doesn't compile even when the variable 'a' is static
// rest of the class
}

Why java don't allow me to do that?

View Replies View Related

Creating Final Arrays With Final Elements

Aug 2, 2013

I want to create a final array with final elements
 
{code}
final int[] array = {0, 1, 2, 3, 4, 5};
{code}
 
But here only the reference of the array is final , not it's elements ... So how can I do that??

View Replies View Related

Why Add Static To Make A Constant

Oct 30, 2014

public static final String NAME="JAVATAR";

"final" makes sure the constant has the same value and prevents it from being changed. So why add "static" to make it a constant. I figured the reason a few weeks back but don't remember it now.

View Replies View Related

How To Get Java Equivalent Of C++ Constant

Jun 10, 2014

How to make sure that a variable passed to a method isn't altered by the method? I know in C++ you can do something like

void aMethod(const Object &item) {
........
}

I know that you can stop a variable from being reinitialized in java by doing this

void aMethod(final Object item) {
.........
}

However, that won't stop it from calling a setter on the item or changing something in it. Is there some other keyword out there that can do this? I just found that java DOES recognize the const keyword but that it really is useless.

So, any practical way that const can be further approximated in java beyond using final?

View Replies View Related

What Is A Compile Time Constant

Jul 16, 2009

"Because X is a compile time constant, the compiler will Y"... But what exactly is a compile time constant? And how can we determine whether something is treated as such?Obviously, a compile time constant is a constant value that is known at compile time... ... Literals are, by definition, compile time constants -- as they are constants, known at compile time.

But the definition of a compile time constant is a bit more complex. To start, let's examine section 15.28 of the Java language specification.A compile-time constant expression is an expression denoting a value of primitive type or a String that is composed using only the following:

Literals of primitive type and literals of type String Casts to primitive types and casts to type StringThe unary operators +, -, ~, and ! (but not ++ or --)The multiplicative operators *, /, and %The additive operators + and - The shift operators <<, >>, and >>>The relational operators <, <=, >, and >= (but not instanceof)The equality operators == and !=The bitwise and logical operators &, ^, and |The conditional-and operator && and the conditional-or operator ||The ternary conditional operator ? : Simple names that refer to final variables whose initializers are constant expressions Qualified names of the form TypeName . Identifier that refer to final variables whose initializers are constant expressions

This is the full definition of a compile time constant. And as you can see, it contains more than just literals. In fact, literals are merely the first bullet point on the list. Also, note that a compile time constant can apply to any literal that is of primative or String type.The next few bullet points are the operations that can be applied to a constant at compile time. This list is actually pretty long, as it is possible to apply most of the operations at compile time. It may actually be easier to remember what can't be apply at compile time -- pre and post increment and decrement, instanceof operator, or any method calls, are not on the list.

The last few bullets are the most interesting. It is possible to use a variable in the expression -- provided that the variable is a compile time constant variable. So... what is a constant variable? Going back to the JLS (section 4.12.4 to be exact)..4.12.4 final Variables.A variable can be declared final. A final variable may only be assigned to once. It is a compile time error if a final variable is assigned to unless it is definitely unassigned (§16) immediately prior to the assignment.

We call a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28) a constant variable. Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9) and definite assignment (§16).The last part of the definition is the relevant part (I still find it amazing that this is that well hidden in the specification). To be a variable that is a compile time constant, the variable needs to be...declared as finalhave a primative or String typeinitialized (on the same line as the declaration)assigned to a compile time constant expression.

View Replies View Related

Implement Method Named ViewAllFactor

Jan 14, 2014

so, i have a problem in implement method named viewAllFactor(User us,ResultSet rs)when i call this method using <T> like objet dont work because T obj is nulli ask if i can try something to have a good result.

I have 2 classes BaseDao<T> (DAO Pattern) and Class User extends from BaseDao

this is the code

package appweb.core;
public abstract class BaseDao<T> {
public ArrayList<T> viewall() {
ResultSet rset = null;
ArrayList<T> listAll = new ArrayList<T>();
String sql = "SELECT* FROM "+ this.tableName;
System.out.println(sql);
try {
 
[code]....

View Replies View Related

Create A Method Header Named ConvertTOKM That Take Int Parameter

Feb 7, 2015

In my book for learning java, one of the questions asks us to create a method header named convertTOKM that takes an int parameter, which is the number of miles, and returns a double value for the converted value in kilometers. I made one, but wanted to know if I was right in any way.

Here it is:public double convertTOKM(int miles, double kilometers){

View Replies View Related

Java Program That Prints Out Taylor Series For Mathematical Constant E

May 10, 2015

I am trying to write a java program that prints out the number that is the mathematical constant e. As you input a number, the larger it gets , the closer it comes to 2.71828 . Here is my code:

//taylor series that prints out e^1=1+1/1!+1/2!+1/3!+.....
import java.util.Scanner;
public class taylor_1
{
public static void main(String args[]) {
 Scanner input=new Scanner(System.in);
int factorial =1;

[Code] .....

Here is the output of my code:

enter n
9
Taylor series is 9.0

View Replies View Related

Write A Class Named Calculator Add Four Methods To That Class

Jan 30, 2014

Write a class named Calculator add four methods to that class:

add(int a, int b)
sub(int a, int b)
mul(int a, int b)
div(int a, int b)

Then write a Tester class with main function and show the use of the methods in Calculator class..

View Replies View Related

Correct Declaration Of Method

Oct 26, 2014

Netbeans tells me it's an illegal start of expression during the initialisation of the interactWithUser method.
public class InvertLetter {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
/**
* String mit den Kleinbuchstaben.
*/
final String lowercase = "abcdefghijklmnopqrstuvwxyz";

[Code] ....

View Replies View Related

Variables Declaration And Visibility

Apr 9, 2015

Let's say within a class I create a method that takes care of creating a java swing layout with labels, buttons etc.. then attach an action listener (inner class) for each button to change a respective label text. All I would need is that the action listener method can access and modify the label as needed.

Have read about static, protected, private, getters and setters but honestly bit confused about which structure should be adopted as a best practice. Global static protected variables for the labels along with private inner classes implementing ActionListeners believe will do the trick and will be able to access the labels but not convinced this is good practice.

View Replies View Related

Two String Array Declaration?

Apr 30, 2015

My Question is Suppose I am declaring an String array as

String[] a
or
String a[]
or
Comparable[] a

Will there be any performance or other advantage or disadvantage using these syntax?

View Replies View Related

Invalid Method Declaration

Feb 26, 2015

import java.util.HashSet;
import java.util.ArrayList;
public class Graph
{
double [] [] adj;
graph (double [] [] a)
{
adj= new double [a.length][a.length];
for (int i=0;i<a.length;i++)
for (int j=0;j<a.length;j++)
adj[i][j]=a[i][j];
}

C:UserscDesktopGraph.java:: error: invalid method declaration; return type required
graph (double [] [] a)

View Replies View Related

How To Turn If Statement Into A Case / Switch Statement

Jun 19, 2014

So from what iv learnt in Java and programming in general is that using a case statement is far more efficient that using multiple IF statements. I have an multiple IF statements contained within a method of my program, and would like to instead use a case statement.

public String checkPasswordStrength(String passw) {
int strengthCount=0;
String strengthWord = "";
String[] partialRegexChecks = { ".*[a-z]+.*", // lower
".*[A-Z]+.*", // upper
".*[d]+.*", // digits
".*[@#$%!]+.*" // symbols

[code].....

View Replies View Related

How To Initialize Multidimensional Array Just After Declaration

Feb 13, 2014

I tried this:

String[][]f = new String[1][1] {{"Harry"}{"Hairy"}};

I also tried this:

String[][]f = new String[1][1] {{"Harry"},{"Hairy"}};

but I get an error

View Replies View Related

Objects Inside Class Declaration

Apr 13, 2014

Ok say you have

public class MyClass {
private int x = 5;
Object myObject = new Object();
public MyClass(){
}
}

When would the myObject be created? Before or after the constructor? And does this mean you can't pass
this into the parameters of that object?

View Replies View Related

JSP :: Unnecessary Complications In JSTL Taglib Declaration

Dec 23, 2014

I started learning JSTL (Java Standard Tag Library) and i got to know that i need to mention this directive in JSP page

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

in order to use JSTL tags.

I am not able to understand what does this URI exists at all ?? I feel it making things complex and meaningless or else i am missing something hidden and secret.

View Replies View Related

Multi-dimension Array Declaration And Instantiation?

May 17, 2015

Whilst pre-preparing for java certification, one of the online mock exams has slightly confused me by saying my answer was incorrect for multi-dimension array 'declaration and instantiation'.

This is one of the answers i chose - which was marked as incorrect

a)
int[][] array2d = {{123}, {4,5}};

Which looks absolutely fine to me.One of the other answers, which i agree is correct and so does the mock exam is

b)
int [][] array2d = new int[2][2];

View Replies View Related

Java Object Declaration Beyond Common Idiom

Feb 5, 2015

when a new object is created in Java it follows the idiom:

Object obj = new Object();
where the Object() constructor matches the object type Object.

But what if it doesn't? I understand from the Oracle Docs on creating objects and polymorphism that the constructor must be in that object's class or one of its subclasses. However, suppose we wanted to declare a new stack. My first instinct would be:

Stack s1 = new Stack();
But I assume it's valid to do it this way, too:

Object s2 = new Stack(); // Is there a difference here? What are we really saying about s2? I'm guessing s2 is simply an empty stack, but only has access to the Object class methods? I'm not sure why someone would ever do this, but I want to solidify my understanding of the Java hierarchy. Are there really any circumstances where someone would use a subclass's constructor when creating a new object?

View Replies View Related

Method Declaration - Partial Interface Implementation

Sep 3, 2014

I have one interface with three(more than one) method declaration. In the subclass that implements it I want to define only one method not all three not even blank definition of them.Is there any keyword or method for that. How to do it? Is it possible to do it? In GUI we use adapter classes to achieve it. What for console application?

View Replies View Related

String Declaration - Check A / B Returns False

Jan 30, 2014

I have doubts in string declaration. As I know we can declare string in two ways:

1. String a=new String("Hello");
2. String b="Hello";

What is exact difference between them? Another thing is when I check (a==b) it retuns me false, but when I check a.equals(b) it returns me with true. Why So?

View Replies View Related

User Event - Global Object Declaration

Mar 10, 2015

I have an application that uses an object that is declared globally for the class. Within a method that is triggered by a user event, it creates a new object and assigns it to this global object declaration. My question is, when the object is overwritten multiple times by the user selecting the button that calls this method, will the older instances be garbage collected or is there still a reference to them? Is there any downfall to this logic and if so what would be a solution.

View Replies View Related

Implementation Of Stack Methods - Declaration Of Stack1 And Stack2

Jun 3, 2014

I have to implement all the stack methods in java such as push, pop empty, not using the ready methods but have to create them and to execute an exercise but is sth wrong with it

public class Stiva {

/** the problem is here how to declare the stack 1 and stack 2 and kreu(head) gjmax(size)*/

int Gjmax;
int array[] = new int[Gjmax];
int kreu;
private Stiva stiva1;
private Stiva stiva2;

[Code] .....

View Replies View Related

Using Switch Statement Inside If Statement

Nov 18, 2014

So I want to make a simple Java that ask the user to pick a powers and it has two options.If the user picks magic then execute the first if statement then ask the user again which type of magic the user wants.I can't make it work it keeps printing the else statement. Why is that?

import java.util.Scanner;
public class Variable {
static Scanner zcan = new Scanner(System.in);
public static void main(String[] args)

[code]....

View Replies View Related

Converting Days Into Weeks / Months / Years - Invalid Method Declaration

May 29, 2014

import java.util.Scanner;
public class days
{ public EnumTest ()
{ this.day = weeks/months/years}
final int daysInMonth = 30; //constants
final int monthsInYear = 12;
final int daysInWeek = 7;
public void convert()

[Code] ....

after compiling it shows invalid method declaration ; return type required.

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved