Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

questions from Marcus Green tutorial

 
kamilla miesak
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have two questions regarding the examples taken from Marcus Green tutorial.
Re #1:
public class MyIf{
public static void main(String argv[]){
MyIf mi = new MyIf();
}
MyIf(){
boolean b = false;
if(b=false){
System.out.println("The value of b is"+b);
}
}
}
Why does this code compile but produces no output?
I thougth it would print "The value of b is false".
Re# 2
public class MySwitch{
public static void main(String argv[]){
MySwitch ms= new MySwitch();
ms.amethod();
}
public void amethod(){
char k=10;
switch(k){
default:
System.out.println("This is the default output");
break;
case 10:
System.out.println("ten");
break;
case 20:
System.out.println("twenty");
break;
}
}
}
Can someone explain the line: char k = 10;
How come it's legal?
Thanks a lot!
 
Richa Jeetah
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
for your question :
Re #1:
public class MyIf{
public static void main(String argv[]){
MyIf mi = new MyIf();
}
MyIf(){
boolean b = false;
if(b=false){ // line 1
System.out.println("The value of b is"+b);
}
}
}
in line 1 you are assigning false to b, and since if condition runs only if its true.
the result you are desiring will be possible if you replace line 1 with 'if(b==false){'
Hope this helps
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For question 2:
A char is an unsigned 16-bit integer, so any assignment of a small enough integer constant is OK.
char c0 = -1; // illegal
char c1 = 10; // OK
char c2 = 32767; // OK
char c3 = 32768; // OK
char c4 = 65535; // OK
char c5 = 65536; // illegal
 
kamilla miesak
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to you both! Got it!
 
Barkat Mardhani
Ranch Hand
Posts: 787
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Kamila:
One more strange thing I noticed about (b=false) assignment is that the expression itself evaluates to false. And for (b=true) the expression itself evaluates to true. Later will produce the printout in your code even though it is an assignment and NOT comparision...
Thanks
Barkat
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An assignment expression always evaluates to the value assigned.
 
Rony Donald
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are these exams being updated for SCJP1.4???
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic